[MINOR] Add missing finals. (#128)

Adrian Sutton 6 years ago committed by GitHub
parent d2d2a2a8fc
commit 45e0037321
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
  1. 2
      acceptance-tests/src/test/java/tech/pegasys/pantheon/tests/acceptance/dsl/node/PantheonNode.java
  2. 2
      acceptance-tests/src/test/java/tech/pegasys/pantheon/tests/acceptance/dsl/node/PantheonNodeRunner.java
  3. 2
      acceptance-tests/src/test/java/tech/pegasys/pantheon/tests/acceptance/dsl/node/ThreadPantheonNodeRunner.java
  4. 4
      acceptance-tests/src/test/java/tech/pegasys/pantheon/tests/acceptance/jsonrpc/EthGetWorkAcceptanceTest.java
  5. 2
      consensus/clique/src/main/java/tech/pegasys/pantheon/consensus/clique/CliqueExtraData.java
  6. 6
      consensus/clique/src/main/java/tech/pegasys/pantheon/consensus/clique/blockcreation/CliqueBlockScheduler.java
  7. 8
      consensus/clique/src/main/java/tech/pegasys/pantheon/consensus/clique/blockcreation/CliqueMinerExecutor.java
  8. 2
      consensus/clique/src/main/java/tech/pegasys/pantheon/consensus/clique/jsonrpc/methods/CliqueProposals.java
  9. 2
      consensus/clique/src/test/java/tech/pegasys/pantheon/consensus/clique/CliqueExtraDataTest.java
  10. 24
      consensus/clique/src/test/java/tech/pegasys/pantheon/consensus/clique/blockcreation/CliqueBlockSchedulerTest.java
  11. 4
      consensus/clique/src/test/java/tech/pegasys/pantheon/consensus/clique/blockcreation/CliqueMinerExecutorTest.java
  12. 4
      consensus/clique/src/test/java/tech/pegasys/pantheon/consensus/clique/jsonrpc/methods/CliqueProposalsTest.java
  13. 2
      consensus/ibft/src/main/java/tech/pegasys/pantheon/consensus/ibft/IbftVoteType.java
  14. 2
      consensus/ibft/src/main/java/tech/pegasys/pantheon/consensus/ibft/jsonrpc/IbftJsonRpcMethodsFactory.java
  15. 4
      consensus/ibft/src/main/java/tech/pegasys/pantheon/consensus/ibft/jsonrpc/methods/IbftProposeValidatorVote.java
  16. 4
      consensus/ibft/src/main/java/tech/pegasys/pantheon/consensus/ibft/network/IbftNetworkPeers.java
  17. 26
      consensus/ibft/src/test/java/tech/pegasys/pantheon/consensus/ibft/BlockTimerTest.java
  18. 20
      consensus/ibft/src/test/java/tech/pegasys/pantheon/consensus/ibft/Ibft2ExtraDataTest.java
  19. 3
      consensus/ibft/src/test/java/tech/pegasys/pantheon/consensus/ibft/IbftChainObserverTest.java
  20. 4
      consensus/ibft/src/test/java/tech/pegasys/pantheon/consensus/ibft/jsonrpc/methods/IbftDiscardValidatorVoteTest.java
  21. 8
      consensus/ibft/src/test/java/tech/pegasys/pantheon/consensus/ibft/jsonrpc/methods/IbftProposeValidatorVoteTest.java
  22. 16
      consensus/ibft/src/test/java/tech/pegasys/pantheon/consensus/ibft/network/IbftNetworkPeersTest.java
  23. 2
      consensus/ibftlegacy/src/main/java/tech/pegasys/pantheon/consensus/ibftlegacy/blockcreation/ProposerSelector.java
  24. 4
      crypto/src/main/java/tech/pegasys/pantheon/crypto/Hash.java
  25. 2
      crypto/src/main/java/tech/pegasys/pantheon/crypto/PersonalisationString.java
  26. 4
      ethereum/core/src/main/java/tech/pegasys/pantheon/ethereum/blockcreation/BlockMiner.java
  27. 2
      ethereum/core/src/main/java/tech/pegasys/pantheon/ethereum/chain/GenesisConfig.java
  28. 2
      ethereum/core/src/main/java/tech/pegasys/pantheon/ethereum/core/AbstractWorldUpdater.java
  29. 4
      ethereum/core/src/main/java/tech/pegasys/pantheon/ethereum/core/Transaction.java
  30. 2
      ethereum/core/src/main/java/tech/pegasys/pantheon/ethereum/mainnet/EthHashBlockCreator.java
  31. 11
      ethereum/core/src/main/java/tech/pegasys/pantheon/ethereum/util/BlockchainUtil.java
  32. 36
      ethereum/core/src/test/java/tech/pegasys/pantheon/ethereum/blockcreation/DefaultBlockSchedulerTest.java
  33. 16
      ethereum/core/src/test/java/tech/pegasys/pantheon/ethereum/db/GenesisBlockMismatchTest.java
  34. 16
      ethereum/core/src/test/java/tech/pegasys/pantheon/ethereum/mainnet/headervalidationrules/ProofOfWorkValidationRuleTest.java
  35. 4
      ethereum/core/src/test/java/tech/pegasys/pantheon/ethereum/util/BlockchainUtilParameterizedTest.java
  36. 2
      ethereum/eth/src/main/java/tech/pegasys/pantheon/ethereum/eth/manager/AbstractEthTask.java
  37. 2
      ethereum/eth/src/main/java/tech/pegasys/pantheon/ethereum/eth/manager/AbstractPeerTask.java
  38. 2
      ethereum/eth/src/main/java/tech/pegasys/pantheon/ethereum/eth/manager/EthServer.java
  39. 2
      ethereum/eth/src/main/java/tech/pegasys/pantheon/ethereum/eth/sync/BlockPropagationManager.java
  40. 2
      ethereum/eth/src/main/java/tech/pegasys/pantheon/ethereum/eth/sync/SynchronizerConfiguration.java
  41. 6
      ethereum/eth/src/main/java/tech/pegasys/pantheon/ethereum/eth/sync/tasks/DetermineCommonAncestorTask.java
  42. 41
      ethereum/eth/src/test/java/tech/pegasys/pantheon/ethereum/eth/manager/EthProtocolManagerTest.java
  43. 32
      ethereum/eth/src/test/java/tech/pegasys/pantheon/ethereum/eth/sync/tasks/DetermineCommonAncestorTaskTest.java
  44. 2
      ethereum/eth/src/test/java/tech/pegasys/pantheon/ethereum/eth/transactions/TestNodeList.java
  45. 9
      ethereum/jsonrpc/src/main/java/tech/pegasys/pantheon/ethereum/jsonrpc/internal/filter/FilterManager.java
  46. 2
      ethereum/jsonrpc/src/main/java/tech/pegasys/pantheon/ethereum/jsonrpc/internal/methods/EthCoinbase.java
  47. 2
      ethereum/jsonrpc/src/main/java/tech/pegasys/pantheon/ethereum/jsonrpc/internal/methods/EthGasPrice.java
  48. 8
      ethereum/jsonrpc/src/main/java/tech/pegasys/pantheon/ethereum/jsonrpc/internal/methods/EthGetWork.java
  49. 4
      ethereum/jsonrpc/src/main/java/tech/pegasys/pantheon/ethereum/jsonrpc/internal/methods/EthSendRawTransaction.java
  50. 2
      ethereum/jsonrpc/src/main/java/tech/pegasys/pantheon/ethereum/jsonrpc/internal/methods/miner/MinerSetCoinbase.java
  51. 4
      ethereum/jsonrpc/src/main/java/tech/pegasys/pantheon/ethereum/jsonrpc/websocket/WebSocketRequestHandler.java
  52. 2
      ethereum/jsonrpc/src/test/java/tech/pegasys/pantheon/ethereum/jsonrpc/AdminJsonRpcHttpServiceTest.java
  53. 2
      ethereum/jsonrpc/src/test/java/tech/pegasys/pantheon/ethereum/jsonrpc/EthJsonRpcHttpBySpecTest.java
  54. 4
      ethereum/jsonrpc/src/test/java/tech/pegasys/pantheon/ethereum/jsonrpc/internal/filter/FilterManagerLogFilterTest.java
  55. 4
      ethereum/jsonrpc/src/test/java/tech/pegasys/pantheon/ethereum/jsonrpc/internal/filter/FilterManagerTest.java
  56. 56
      ethereum/jsonrpc/src/test/java/tech/pegasys/pantheon/ethereum/jsonrpc/internal/filter/FilterRepositoryTest.java
  57. 6
      ethereum/jsonrpc/src/test/java/tech/pegasys/pantheon/ethereum/jsonrpc/internal/filter/FilterTest.java
  58. 4
      ethereum/jsonrpc/src/test/java/tech/pegasys/pantheon/ethereum/jsonrpc/internal/filter/FilterTimeoutMonitorTest.java
  59. 6
      ethereum/jsonrpc/src/test/java/tech/pegasys/pantheon/ethereum/jsonrpc/internal/methods/EthGetWorkTest.java
  60. 18
      ethereum/jsonrpc/src/test/java/tech/pegasys/pantheon/ethereum/jsonrpc/websocket/subscription/SubscriptionManagerTest.java
  61. 2
      ethereum/p2p/src/main/java/tech/pegasys/pantheon/ethereum/p2p/discovery/internal/Packet.java
  62. 2
      ethereum/p2p/src/main/java/tech/pegasys/pantheon/ethereum/p2p/discovery/internal/PeerTable.java
  63. 16
      ethereum/p2p/src/main/java/tech/pegasys/pantheon/ethereum/p2p/rlpx/handshake/ecies/ECIESEncryptionEngine.java
  64. 4
      ethereum/p2p/src/test/java/tech/pegasys/pantheon/ethereum/p2p/NettyP2PNetworkTest.java
  65. 22
      ethereum/p2p/src/test/java/tech/pegasys/pantheon/ethereum/p2p/NetworkingServiceLifecycleTest.java
  66. 4
      ethereum/p2p/src/test/java/tech/pegasys/pantheon/ethereum/p2p/discovery/AbstractPeerDiscoveryTest.java
  67. 2
      ethereum/p2p/src/test/java/tech/pegasys/pantheon/ethereum/p2p/discovery/PeerDiscoveryObserversTest.java
  68. 2
      ethereum/rlp/src/main/java/tech/pegasys/pantheon/ethereum/rlp/AbstractRLPOutput.java
  69. 4
      ethereum/rlp/src/main/java/tech/pegasys/pantheon/ethereum/rlp/RLP.java
  70. 2
      ethereum/trie/src/main/java/tech/pegasys/pantheon/ethereum/trie/CompactEncoding.java
  71. 8
      ethereum/trie/src/main/java/tech/pegasys/pantheon/ethereum/trie/StoredNodeFactory.java
  72. 2
      pantheon/src/main/java/tech/pegasys/pantheon/Runner.java
  73. 2
      pantheon/src/main/java/tech/pegasys/pantheon/RunnerBuilder.java
  74. 2
      pantheon/src/main/java/tech/pegasys/pantheon/cli/ConfigOptionSearchAndRunHandler.java
  75. 4
      pantheon/src/main/java/tech/pegasys/pantheon/cli/EthNetworkConfig.java
  76. 2
      pantheon/src/main/java/tech/pegasys/pantheon/cli/ExportPublicKeySubCommand.java
  77. 6
      pantheon/src/main/java/tech/pegasys/pantheon/cli/PantheonCommand.java
  78. 2
      pantheon/src/main/java/tech/pegasys/pantheon/cli/TomlConfigFileDefaultProvider.java
  79. 2
      pantheon/src/main/java/tech/pegasys/pantheon/cli/custom/CorsAllowedOriginsProperty.java
  80. 6
      pantheon/src/main/java/tech/pegasys/pantheon/util/BlockchainImporter.java
  81. 6
      pantheon/src/test/java/tech/pegasys/pantheon/cli/PantheonCommandTest.java
  82. 8
      pantheon/src/test/java/tech/pegasys/pantheon/cli/TomlConfigFileDefaultProviderTest.java
  83. 62
      quickstart/src/test/java/tech/pegasys/pantheon/tests/quickstart/DockerQuickstartTest.java
  84. 4
      util/src/main/java/tech/pegasys/pantheon/util/uint/UInt256Bytes.java

@ -179,7 +179,7 @@ public class PantheonNode implements Node, AutoCloseable {
}
private void loadPortsFile() {
try (FileInputStream fis =
try (final FileInputStream fis =
new FileInputStream(new File(homeDirectory.toFile(), "pantheon.ports"))) {
portsProperties.load(fis);
} catch (final IOException e) {

@ -42,7 +42,7 @@ public interface PantheonNodeRunner {
.until(
() -> {
if (file.exists()) {
try (Stream<String> s = Files.lines(file.toPath())) {
try (final Stream<String> s = Files.lines(file.toPath())) {
return s.count() > 0;
}
} else {

@ -50,7 +50,7 @@ public class ThreadPantheonNodeRunner implements PantheonNodeRunner {
final PantheonControllerBuilder builder = new PantheonControllerBuilder();
final EthNetworkConfig ethNetworkConfig =
new EthNetworkConfig.Builder(mainnet()).setNetworkId(NETWORK_ID).build();
PantheonController<?, ?> pantheonController;
final PantheonController<?, ?> pantheonController;
try {
pantheonController =
builder.build(

@ -38,14 +38,14 @@ public class EthGetWorkAcceptanceTest extends AcceptanceTestBase {
@Test
public void shouldReturnSuccessResponseWhenMining() throws Exception {
String[] response = minerNode.eth().getWork();
final String[] response = minerNode.eth().getWork();
assertThat(response).hasSize(3);
assertThat(response).doesNotContainNull();
}
@Test
public void shouldReturnErrorResponseWhenNotMining() {
Throwable thrown = catchThrowable(() -> fullNode.eth().getWork());
final Throwable thrown = catchThrowable(() -> fullNode.eth().getWork());
assertThat(thrown).isInstanceOf(ClientConnectionException.class);
assertThat(thrown.getMessage()).contains("No mining work available yet");
}

@ -120,7 +120,7 @@ public class CliqueExtraData {
private static List<Address> convertPrivKeysToAddresses(final List<PrivateKey> privKeys) {
final List<Address> validators = Lists.newArrayList();
for (PrivateKey privKey : privKeys) {
for (final PrivateKey privKey : privKeys) {
final PublicKey pubKey = PublicKey.create(privKey);
validators.add(Util.publicKeyToAddress(pubKey));
}

@ -63,9 +63,9 @@ public class CliqueBlockScheduler extends DefaultBlockScheduler {
}
private int calculatorOutOfTurnDelay(final ValidatorProvider validators) {
int countSigners = validators.getCurrentValidators().size();
int maxDelay = ((countSigners / 2) + 1) * OUT_OF_TURN_DELAY_MULTIPLIER_MILLIS;
Random r = new Random();
final int countSigners = validators.getCurrentValidators().size();
final int maxDelay = ((countSigners / 2) + 1) * OUT_OF_TURN_DELAY_MULTIPLIER_MILLIS;
final Random r = new Random();
return r.nextInt(maxDelay + 1);
}
}

@ -68,7 +68,7 @@ public class CliqueMinerExecutor extends AbstractMinerExecutor<CliqueContext, Cl
@Override
public CliqueBlockMiner startAsyncMining(
final Subscribers<MinedBlockObserver> observers, final BlockHeader parentHeader) {
CliqueBlockCreator blockCreator =
final CliqueBlockCreator blockCreator =
new CliqueBlockCreator(
localAddress, // TOOD(tmm): This can be removed (used for voting not coinbase).
this::calculateExtraData,
@ -80,7 +80,7 @@ public class CliqueMinerExecutor extends AbstractMinerExecutor<CliqueContext, Cl
minTransactionGasPrice,
parentHeader);
CliqueBlockMiner currentRunningMiner =
final CliqueBlockMiner currentRunningMiner =
new CliqueBlockMiner(
blockCreator,
protocolSchedule,
@ -94,7 +94,7 @@ public class CliqueMinerExecutor extends AbstractMinerExecutor<CliqueContext, Cl
}
public BytesValue calculateExtraData(final BlockHeader parentHeader) {
List<Address> validators = Lists.newArrayList();
final List<Address> validators = Lists.newArrayList();
final BytesValue vanityDataToInsert = createCorrectlySizedVanityData();
// Building ON TOP of canonical head, if the next block is epoch, include validators.
@ -110,7 +110,7 @@ public class CliqueMinerExecutor extends AbstractMinerExecutor<CliqueContext, Cl
}
private BytesValue createCorrectlySizedVanityData() {
int vanityPadding = Math.max(0, CliqueExtraData.EXTRA_VANITY_LENGTH - vanityData.size());
final int vanityPadding = Math.max(0, CliqueExtraData.EXTRA_VANITY_LENGTH - vanityData.size());
return BytesValues.concatenate(BytesValue.wrap(new byte[vanityPadding]), vanityData)
.slice(0, CliqueExtraData.EXTRA_VANITY_LENGTH);
}

@ -37,7 +37,7 @@ public class CliqueProposals implements JsonRpcMethod {
@Override
public JsonRpcResponse response(final JsonRpcRequest request) {
Map<String, Boolean> proposals =
final Map<String, Boolean> proposals =
voteProposer
.getProposals()
.entrySet()

@ -96,7 +96,7 @@ public class CliqueExtraDataTest {
@Test
public void privKeysToExtraDataString() {
List<KeyPair> nodeKeys = Lists.newArrayList();
final List<KeyPair> nodeKeys = Lists.newArrayList();
for (int i = 0; i < 4; i++) {
nodeKeys.add(KeyPair.generate());
}

@ -58,19 +58,19 @@ public class CliqueBlockSchedulerTest {
@Test
public void inturnValidatorWaitsExactlyBlockInterval() {
Clock clock = mock(Clock.class);
final Clock clock = mock(Clock.class);
final long currentSecondsSinceEpoch = 10L;
final long secondsBetweenBlocks = 5L;
when(clock.millisecondsSinceEpoch()).thenReturn(currentSecondsSinceEpoch * 1000);
CliqueBlockScheduler scheduler =
final CliqueBlockScheduler scheduler =
new CliqueBlockScheduler(clock, voteTallyCache, localAddr, secondsBetweenBlocks);
// There are 2 validators, therefore block 2 will put localAddr as the in-turn voter, therefore
// parent block should be number 1.
BlockHeader parentHeader =
final BlockHeader parentHeader =
blockHeaderBuilder.number(1).timestamp(currentSecondsSinceEpoch).buildHeader();
BlockCreationTimeResult result = scheduler.getNextTimestamp(parentHeader);
final BlockCreationTimeResult result = scheduler.getNextTimestamp(parentHeader);
assertThat(result.getTimestampForHeader())
.isEqualTo(currentSecondsSinceEpoch + secondsBetweenBlocks);
@ -79,19 +79,19 @@ public class CliqueBlockSchedulerTest {
@Test
public void outOfturnValidatorWaitsLongerThanBlockInterval() {
Clock clock = mock(Clock.class);
final Clock clock = mock(Clock.class);
final long currentSecondsSinceEpoch = 10L;
final long secondsBetweenBlocks = 5L;
when(clock.millisecondsSinceEpoch()).thenReturn(currentSecondsSinceEpoch * 1000);
CliqueBlockScheduler scheduler =
final CliqueBlockScheduler scheduler =
new CliqueBlockScheduler(clock, voteTallyCache, localAddr, secondsBetweenBlocks);
// There are 2 validators, therefore block 3 will put localAddr as the out-turn voter, therefore
// parent block should be number 2.
BlockHeader parentHeader =
final BlockHeader parentHeader =
blockHeaderBuilder.number(2).timestamp(currentSecondsSinceEpoch).buildHeader();
BlockCreationTimeResult result = scheduler.getNextTimestamp(parentHeader);
final BlockCreationTimeResult result = scheduler.getNextTimestamp(parentHeader);
assertThat(result.getTimestampForHeader())
.isEqualTo(currentSecondsSinceEpoch + secondsBetweenBlocks);
@ -100,22 +100,22 @@ public class CliqueBlockSchedulerTest {
@Test
public void inTurnValidatorCreatesBlockNowIFParentTimestampSufficientlyBehindNow() {
Clock clock = mock(Clock.class);
final Clock clock = mock(Clock.class);
final long currentSecondsSinceEpoch = 10L;
final long secondsBetweenBlocks = 5L;
when(clock.millisecondsSinceEpoch()).thenReturn(currentSecondsSinceEpoch * 1000);
CliqueBlockScheduler scheduler =
final CliqueBlockScheduler scheduler =
new CliqueBlockScheduler(clock, voteTallyCache, localAddr, secondsBetweenBlocks);
// There are 2 validators, therefore block 2 will put localAddr as the in-turn voter, therefore
// parent block should be number 1.
BlockHeader parentHeader =
final BlockHeader parentHeader =
blockHeaderBuilder
.number(1)
.timestamp(currentSecondsSinceEpoch - secondsBetweenBlocks)
.buildHeader();
BlockCreationTimeResult result = scheduler.getNextTimestamp(parentHeader);
final BlockCreationTimeResult result = scheduler.getNextTimestamp(parentHeader);
assertThat(result.getTimestampForHeader()).isEqualTo(currentSecondsSinceEpoch);
assertThat(result.getMillisecondsUntilValid()).isEqualTo(0);

@ -72,7 +72,7 @@ public class CliqueMinerExecutorTest {
@Test
public void extraDataCreatedOnEpochBlocksContainsValidators() {
byte[] vanityData = new byte[32];
final byte[] vanityData = new byte[32];
new Random().nextBytes(vanityData);
final BytesValue wrappedVanityData = BytesValue.wrap(vanityData);
final int EPOCH_LENGTH = 10;
@ -102,7 +102,7 @@ public class CliqueMinerExecutorTest {
@Test
public void extraDataForNonEpochBlocksDoesNotContainValidaors() {
byte[] vanityData = new byte[32];
final byte[] vanityData = new byte[32];
new Random().nextBytes(vanityData);
final BytesValue wrappedVanityData = BytesValue.wrap(vanityData);
final int EPOCH_LENGTH = 10;

@ -57,7 +57,7 @@ public class CliqueProposalsTest {
Address.fromHexString("2"),
VoteType.DROP));
JsonRpcResponse expectedResponse =
final JsonRpcResponse expectedResponse =
new JsonRpcSuccessResponse(
request.getId(),
ImmutableMap.of(
@ -66,7 +66,7 @@ public class CliqueProposalsTest {
"0x0000000000000000000000000000000000000002",
false));
JsonRpcResponse response = method.response(request);
final JsonRpcResponse response = method.response(request);
assertThat(response).isEqualToComparingFieldByField(expectedResponse);
}

@ -31,7 +31,7 @@ public enum IbftVoteType {
}
public static IbftVoteType readFrom(final RLPInput rlpInput) {
byte encodedByteValue = rlpInput.readByte();
final byte encodedByteValue = rlpInput.readByte();
for (final IbftVoteType voteType : values()) {
if (voteType.voteValue == encodedByteValue) {
return voteType;

@ -48,7 +48,7 @@ public class IbftJsonRpcMethodsFactory {
private void addMethods(
final Map<String, JsonRpcMethod> methods, final JsonRpcMethod... rpcMethods) {
for (JsonRpcMethod rpcMethod : rpcMethods) {
for (final JsonRpcMethod rpcMethod : rpcMethods) {
methods.put(rpcMethod.getName(), rpcMethod);
}
}

@ -38,8 +38,8 @@ public class IbftProposeValidatorVote implements JsonRpcMethod {
@Override
public JsonRpcResponse response(final JsonRpcRequest req) {
Address validatorAddress = parameters.required(req.getParams(), 0, Address.class);
Boolean add = parameters.required(req.getParams(), 1, Boolean.class);
final Address validatorAddress = parameters.required(req.getParams(), 0, Address.class);
final Boolean add = parameters.required(req.getParams(), 1, Boolean.class);
if (add) {
voteProposer.auth(validatorAddress);

@ -53,7 +53,7 @@ public class IbftNetworkPeers {
}
public void multicastToValidators(final MessageData message) {
Collection<Address> validators = validatorProvider.getCurrentValidators();
final Collection<Address> validators = validatorProvider.getCurrentValidators();
sendMessageToSpecificAddresses(validators, message);
}
@ -67,7 +67,7 @@ public class IbftNetworkPeers {
connection -> {
try {
connection.sendForProtocol(PROTOCOL_NAME, message);
} catch (PeerNotConnected peerNotConnected) {
} catch (final PeerNotConnected peerNotConnected) {
LOG.trace("Lost connection to a validator.");
}
});

@ -78,7 +78,8 @@ public class BlockTimerTest {
when(mockClock.millisecondsSinceEpoch()).thenReturn(NOW_MILLIS);
BlockHeader header = new BlockHeaderTestFixture().timestamp(BLOCK_TIME_STAMP).buildHeader();
final BlockHeader header =
new BlockHeaderTestFixture().timestamp(BLOCK_TIME_STAMP).buildHeader();
final ConsensusRoundIdentifier round =
new ConsensusRoundIdentifier(0xFEDBCA9876543210L, 0x12345678);
@ -102,11 +103,12 @@ public class BlockTimerTest {
when(mockClock.millisecondsSinceEpoch()).thenReturn(NOW_MILLIS);
BlockHeader header = new BlockHeaderTestFixture().timestamp(BLOCK_TIME_STAMP).buildHeader();
final BlockHeader header =
new BlockHeaderTestFixture().timestamp(BLOCK_TIME_STAMP).buildHeader();
final ConsensusRoundIdentifier round =
new ConsensusRoundIdentifier(0xFEDBCA9876543210L, 0x12345678);
BlockTimer timer =
final BlockTimer timer =
new BlockTimer(
mockQueue,
MINIMAL_TIME_BETWEEN_BLOCKS_MILLIS,
@ -122,7 +124,7 @@ public class BlockTimerTest {
.atLeast(EXPECTED_DELAY - 200, TimeUnit.MILLISECONDS)
.until(timer::isRunning, equalTo(false));
ArgumentCaptor<IbftEvent> ibftEventCaptor = ArgumentCaptor.forClass(IbftEvent.class);
final ArgumentCaptor<IbftEvent> ibftEventCaptor = ArgumentCaptor.forClass(IbftEvent.class);
verify(mockQueue).add(ibftEventCaptor.capture());
assertThat(ibftEventCaptor.getValue() instanceof BlockTimerExpiry).isTrue();
@ -142,14 +144,15 @@ public class BlockTimerTest {
when(mockClock.millisecondsSinceEpoch()).thenReturn(NOW_MILLIS);
BlockHeader header = new BlockHeaderTestFixture().timestamp(BLOCK_TIME_STAMP).buildHeader();
final BlockHeader header =
new BlockHeaderTestFixture().timestamp(BLOCK_TIME_STAMP).buildHeader();
final ConsensusRoundIdentifier round =
new ConsensusRoundIdentifier(0xFEDBCA9876543210L, 0x12345678);
timer.startTimer(round, header);
verify(mockExecutorService, never()).schedule(any(Runnable.class), anyLong(), any());
ArgumentCaptor<IbftEvent> ibftEventCaptor = ArgumentCaptor.forClass(IbftEvent.class);
final ArgumentCaptor<IbftEvent> ibftEventCaptor = ArgumentCaptor.forClass(IbftEvent.class);
verify(mockQueue).add(ibftEventCaptor.capture());
assertThat(ibftEventCaptor.getValue() instanceof BlockTimerExpiry).isTrue();
@ -169,14 +172,15 @@ public class BlockTimerTest {
when(mockClock.millisecondsSinceEpoch()).thenReturn(NOW_MILLIS);
BlockHeader header = new BlockHeaderTestFixture().timestamp(BLOCK_TIME_STAMP).buildHeader();
final BlockHeader header =
new BlockHeaderTestFixture().timestamp(BLOCK_TIME_STAMP).buildHeader();
final ConsensusRoundIdentifier round =
new ConsensusRoundIdentifier(0xFEDBCA9876543210L, 0x12345678);
timer.startTimer(round, header);
verify(mockExecutorService, never()).schedule(any(Runnable.class), anyLong(), any());
ArgumentCaptor<IbftEvent> ibftEventCaptor = ArgumentCaptor.forClass(IbftEvent.class);
final ArgumentCaptor<IbftEvent> ibftEventCaptor = ArgumentCaptor.forClass(IbftEvent.class);
verify(mockQueue).add(ibftEventCaptor.capture());
assertThat(ibftEventCaptor.getValue() instanceof BlockTimerExpiry).isTrue();
@ -196,7 +200,8 @@ public class BlockTimerTest {
when(mockClock.millisecondsSinceEpoch()).thenReturn(NOW_MILLIS);
BlockHeader header = new BlockHeaderTestFixture().timestamp(BLOCK_TIME_STAMP).buildHeader();
final BlockHeader header =
new BlockHeaderTestFixture().timestamp(BLOCK_TIME_STAMP).buildHeader();
final ConsensusRoundIdentifier round =
new ConsensusRoundIdentifier(0xFEDBCA9876543210L, 0x12345678);
final ScheduledFuture<?> mockedFuture = mock(ScheduledFuture.class);
@ -222,7 +227,8 @@ public class BlockTimerTest {
when(mockClock.millisecondsSinceEpoch()).thenReturn(NOW_MILLIS);
BlockHeader header = new BlockHeaderTestFixture().timestamp(BLOCK_TIME_STAMP).buildHeader();
final BlockHeader header =
new BlockHeaderTestFixture().timestamp(BLOCK_TIME_STAMP).buildHeader();
final ConsensusRoundIdentifier round =
new ConsensusRoundIdentifier(0xFEDBCA9876543210L, 0x12345678);

@ -175,7 +175,7 @@ public class Ibft2ExtraDataTest {
@Test
public void emptyVoteAndListIsEncodedCorrectly() {
final List<Address> validators = Lists.newArrayList();
Optional<Vote> vote = Optional.empty();
final Optional<Vote> vote = Optional.empty();
final int round = 0x00FEDCBA;
final List<Signature> committerSeals = Lists.newArrayList();
@ -183,10 +183,10 @@ public class Ibft2ExtraDataTest {
final byte[] vanity_bytes = new byte[32];
final BytesValue vanity_data = BytesValue.wrap(vanity_bytes);
Ibft2ExtraData expectedExtraData =
final Ibft2ExtraData expectedExtraData =
new Ibft2ExtraData(vanity_data, committerSeals, vote, round, validators);
Ibft2ExtraData actualExtraData = Ibft2ExtraData.decode(expectedExtraData.encode());
final Ibft2ExtraData actualExtraData = Ibft2ExtraData.decode(expectedExtraData.encode());
assertThat(actualExtraData).isEqualToComparingFieldByField(expectedExtraData);
}
@ -240,10 +240,10 @@ public class Ibft2ExtraDataTest {
final byte[] vanity_bytes = new byte[32];
final BytesValue vanity_data = BytesValue.wrap(vanity_bytes);
Ibft2ExtraData expectedExtraData =
final Ibft2ExtraData expectedExtraData =
new Ibft2ExtraData(vanity_data, committerSeals, vote, round, validators);
Ibft2ExtraData actualExtraData = Ibft2ExtraData.decode(expectedExtraData.encode());
final Ibft2ExtraData actualExtraData = Ibft2ExtraData.decode(expectedExtraData.encode());
assertThat(actualExtraData).isEqualToComparingFieldByField(expectedExtraData);
}
@ -306,17 +306,17 @@ public class Ibft2ExtraDataTest {
final byte[] vanity_bytes = createNonEmptyVanityData();
final BytesValue vanity_data = BytesValue.wrap(vanity_bytes);
Ibft2ExtraData expectedExtraData =
final Ibft2ExtraData expectedExtraData =
new Ibft2ExtraData(vanity_data, committerSeals, vote, round, validators);
Ibft2ExtraData actualExtraData = Ibft2ExtraData.decode(expectedExtraData.encode());
final Ibft2ExtraData actualExtraData = Ibft2ExtraData.decode(expectedExtraData.encode());
assertThat(actualExtraData).isEqualToComparingFieldByField(expectedExtraData);
}
@Test
public void encodingMatchesKnownRawHexString() {
BytesValue expectedRawDecoding = BytesValue.fromHexString(RAW_HEX_ENCODING_STRING);
final BytesValue expectedRawDecoding = BytesValue.fromHexString(RAW_HEX_ENCODING_STRING);
assertThat(DECODED_EXTRA_DATA_FOR_RAW_HEX_ENCODING_STRING.encode())
.isEqualTo(expectedRawDecoding);
}
@ -326,8 +326,8 @@ public class Ibft2ExtraDataTest {
final Ibft2ExtraData expectedExtraData = DECODED_EXTRA_DATA_FOR_RAW_HEX_ENCODING_STRING;
BytesValue rawDecoding = BytesValue.fromHexString(RAW_HEX_ENCODING_STRING);
Ibft2ExtraData actualExtraData = Ibft2ExtraData.decode(rawDecoding);
final BytesValue rawDecoding = BytesValue.fromHexString(RAW_HEX_ENCODING_STRING);
final Ibft2ExtraData actualExtraData = Ibft2ExtraData.decode(rawDecoding);
assertThat(actualExtraData).isEqualToComparingFieldByField(expectedExtraData);
}

@ -54,7 +54,8 @@ public class IbftChainObserverTest {
ibftChainObserver.onBlockAdded(mockBlockAddedEvent, mockBlockchain);
ArgumentCaptor<IbftEvent> ibftEventArgumentCaptor = ArgumentCaptor.forClass(IbftEvent.class);
final ArgumentCaptor<IbftEvent> ibftEventArgumentCaptor =
ArgumentCaptor.forClass(IbftEvent.class);
verify(mockQueue).add(ibftEventArgumentCaptor.capture());
assertThat(ibftEventArgumentCaptor.getValue() instanceof NewChainHead).isTrue();

@ -73,9 +73,9 @@ public class IbftDiscardValidatorVoteTest {
final Address parameterAddress = Address.fromHexString("1");
final JsonRpcRequest request = requestWithParams(parameterAddress);
JsonRpcResponse expectedResponse = new JsonRpcSuccessResponse(request.getId(), true);
final JsonRpcResponse expectedResponse = new JsonRpcSuccessResponse(request.getId(), true);
JsonRpcResponse response = method.response(request);
final JsonRpcResponse response = method.response(request);
assertThat(response).isEqualToComparingFieldByField(expectedResponse);

@ -92,9 +92,9 @@ public class IbftProposeValidatorVoteTest {
public void addValidator() {
final Address parameterAddress = Address.fromHexString("1");
final JsonRpcRequest request = requestWithParams(parameterAddress, "true");
JsonRpcResponse expectedResponse = new JsonRpcSuccessResponse(request.getId(), true);
final JsonRpcResponse expectedResponse = new JsonRpcSuccessResponse(request.getId(), true);
JsonRpcResponse response = method.response(request);
final JsonRpcResponse response = method.response(request);
assertThat(response).isEqualToComparingFieldByField(expectedResponse);
@ -105,9 +105,9 @@ public class IbftProposeValidatorVoteTest {
public void removeValidator() {
final Address parameterAddress = Address.fromHexString("1");
final JsonRpcRequest request = requestWithParams(parameterAddress, "false");
JsonRpcResponse expectedResponse = new JsonRpcSuccessResponse(request.getId(), true);
final JsonRpcResponse expectedResponse = new JsonRpcSuccessResponse(request.getId(), true);
JsonRpcResponse response = method.response(request);
final JsonRpcResponse response = method.response(request);
assertThat(response).isEqualToComparingFieldByField(expectedResponse);

@ -50,7 +50,7 @@ public class IbftNetworkPeersTest {
@Before
public void setup() {
for (int i = 0; i < 4; i++) {
PublicKey pubKey = PublicKey.create(BigInteger.valueOf(i));
final PublicKey pubKey = PublicKey.create(BigInteger.valueOf(i));
publicKeys.add(pubKey);
final PeerInfo peerInfo = mock(PeerInfo.class);
@ -66,15 +66,15 @@ public class IbftNetworkPeersTest {
public void onlyValidatorsAreSentAMessage() throws PeerNotConnected {
// Only add the first Peer's address to the validators.
validators.add(Util.publicKeyToAddress(publicKeys.get(0)));
ValidatorProvider validatorProvider = mock(ValidatorProvider.class);
final ValidatorProvider validatorProvider = mock(ValidatorProvider.class);
when(validatorProvider.getCurrentValidators()).thenReturn(validators);
IbftNetworkPeers peers = new IbftNetworkPeers(validatorProvider);
for (PeerConnection peer : peerConnections) {
final IbftNetworkPeers peers = new IbftNetworkPeers(validatorProvider);
for (final PeerConnection peer : peerConnections) {
peers.peerAdded(peer);
}
MessageData messageToSend = new RawMessage(1, EMPTY_BUFFER);
final MessageData messageToSend = new RawMessage(1, EMPTY_BUFFER);
peers.multicastToValidators(messageToSend);
verify(peerConnections.get(0), times(1)).sendForProtocol("IBF", messageToSend);
@ -87,15 +87,15 @@ public class IbftNetworkPeersTest {
public void doesntSendToValidatorsWhichAreNotDirectlyConnected() throws PeerNotConnected {
validators.add(Util.publicKeyToAddress(publicKeys.get(0)));
ValidatorProvider validatorProvider = mock(ValidatorProvider.class);
final ValidatorProvider validatorProvider = mock(ValidatorProvider.class);
when(validatorProvider.getCurrentValidators()).thenReturn(validators);
IbftNetworkPeers peers = new IbftNetworkPeers(validatorProvider);
final IbftNetworkPeers peers = new IbftNetworkPeers(validatorProvider);
// only add peer connections 1, 2 & 3, none of which should be invoked.
Lists.newArrayList(1, 2, 3).stream().forEach(i -> peers.peerAdded(peerConnections.get(i)));
MessageData messageToSend = new RawMessage(1, EMPTY_BUFFER);
final MessageData messageToSend = new RawMessage(1, EMPTY_BUFFER);
peers.multicastToValidators(messageToSend);
verify(peerConnections.get(0), never()).sendForProtocol(any(), any());

@ -96,7 +96,7 @@ public class ProposerSelector {
final Address prevBlockProposer, final ConsensusRoundIdentifier roundIdentifier) {
final NavigableSet<Address> validatorSet = new TreeSet<>(validators.getCurrentValidators());
final SortedSet<Address> latterValidators = validatorSet.tailSet(prevBlockProposer, false);
Address nextProposer;
final Address nextProposer;
if (latterValidators.isEmpty()) {
// i.e. prevBlockProposer was at the end of the validator list, so the right validator for
// the start of this round is the first.

@ -42,7 +42,7 @@ public abstract class Hash {
* @return A digest.
*/
private static byte[] digestUsingAlgorithm(final byte[] input, final String alg) {
MessageDigest digest;
final MessageDigest digest;
try {
digest = BouncyCastleMessageDigestFactory.create(alg);
digest.update(input);
@ -60,7 +60,7 @@ public abstract class Hash {
* @return A digest.
*/
private static byte[] digestUsingAlgorithm(final BytesValue input, final String alg) {
MessageDigest digest;
final MessageDigest digest;
try {
digest = BouncyCastleMessageDigestFactory.create(alg);
input.update(digest);

@ -53,7 +53,7 @@ public class PersonalisationString {
}
}
}
} catch (SocketException | BufferOverflowException e) {
} catch (final SocketException | BufferOverflowException e) {
LOG.warn(
"Failed to obtain network hardware address for use in random number personalisation string, "
+ "continuing without this piece of random information",

@ -84,10 +84,10 @@ public class BlockMiner<C, M extends AbstractBlockCreator<C>> implements Runnabl
// Ensure the block is allowed to be mined - i.e. the timestamp on the new block is sufficiently
// ahead of the parent, and still within allowable clock tolerance.
LOG.trace("Started a mining operation.");
long newBlockTimestamp = scheduler.waitUntilNextBlockCanBeMined(parentHeader);
final long newBlockTimestamp = scheduler.waitUntilNextBlockCanBeMined(parentHeader);
LOG.trace("Mining a new block with timestamp {}", newBlockTimestamp);
Block block = blockCreator.createBlock(newBlockTimestamp);
final Block block = blockCreator.createBlock(newBlockTimestamp);
LOG.info(
"Block created, importing to local chain, block includes {} transactions",
block.getBody().getTransactions().size());

@ -312,7 +312,7 @@ public final class GenesisConfig<C> {
}
private Wei parseBalance(final String balance) {
BigInteger val;
final BigInteger val;
if (balance.startsWith("0x")) {
val = new BigInteger(1, BytesValue.fromHexStringLenient(balance).extractArray());
} else {

@ -308,7 +308,7 @@ public abstract class AbstractWorldUpdater<W extends WorldView, A extends Accoun
@Override
public NavigableMap<Bytes32, UInt256> storageEntriesFrom(
final Bytes32 startKeyHash, final int limit) {
NavigableMap<Bytes32, UInt256> entries;
final NavigableMap<Bytes32, UInt256> entries;
if (account != null) {
entries = account.storageEntriesFrom(startKeyHash, limit);
} else {

@ -88,7 +88,7 @@ public class Transaction {
.payload(input.readBytesValue());
final int v = input.readIntScalar();
byte recId;
final byte recId;
int chainId = -1;
if (v == REPLAY_UNPROTECTED_V_BASE || v == REPLAY_UNPROTECTED_V_BASE + 1) {
recId = (byte) (v - REPLAY_UNPROTECTED_V_BASE);
@ -285,7 +285,7 @@ public class Transaction {
}
public int getV() {
int v;
final int v;
if (!chainId.isPresent()) {
v = signature.getRecId() + REPLAY_UNPROTECTED_V_BASE;
} else {

@ -61,7 +61,7 @@ public class EthHashBlockCreator extends AbstractBlockCreator<Void> {
@Override
protected BlockHeader createFinalBlockHeader(final SealableBlockHeader sealableBlockHeader) {
final EthHashSolverInputs workDefinition = generateNonceSolverInputs(sealableBlockHeader);
EthHashSolution solution;
final EthHashSolution solution;
try {
solution = nonceSolver.solveFor(EthHashSolverJob.createFromInputs(workDefinition));
} catch (final InterruptedException ex) {

@ -39,11 +39,12 @@ public class BlockchainUtil {
final Blockchain blockchain,
final List<BlockHeader> headers,
final boolean ascendingHeaderOrder) {
int offset = ascendingHeaderOrder ? -1 : 0;
Comparator<BlockHeader> comparator = knownBlockComparator(blockchain, ascendingHeaderOrder);
final int offset = ascendingHeaderOrder ? -1 : 0;
final Comparator<BlockHeader> comparator =
knownBlockComparator(blockchain, ascendingHeaderOrder);
int insertionIndex = -Collections.binarySearch(headers, null, comparator) - 1;
int ancestorIndex = insertionIndex + offset;
final int insertionIndex = -Collections.binarySearch(headers, null, comparator) - 1;
final int ancestorIndex = insertionIndex + offset;
if (ancestorIndex < 0 || ancestorIndex >= headers.size()) {
return OptionalInt.empty();
}
@ -52,7 +53,7 @@ public class BlockchainUtil {
private static Comparator<BlockHeader> knownBlockComparator(
final Blockchain blockchain, final boolean ascendingHeaderOrder) {
Comparator<BlockHeader> comparator =
final Comparator<BlockHeader> comparator =
(final BlockHeader element0, final BlockHeader element1) -> {
if (element0 == null) {
return blockchain.contains(element1.getHash()) ? -1 : 1;

@ -31,8 +31,8 @@ public class DefaultBlockSchedulerTest {
@Test
public void canMineBlockOnLimitOfClockDrift() {
Clock clock = mock(Clock.class);
DefaultBlockScheduler scheduler =
final Clock clock = mock(Clock.class);
final DefaultBlockScheduler scheduler =
new DefaultBlockScheduler(interBlockSeconds, acceptableClockDrift, clock);
// Determine the system time of parent block creation, which means child will occur on
@ -40,9 +40,9 @@ public class DefaultBlockSchedulerTest {
final long parentBlockSystemTimeCreation = parentTimeStamp - acceptableClockDrift + 1;
when(clock.millisecondsSinceEpoch()).thenReturn(parentBlockSystemTimeCreation * 1000);
BlockHeaderTestFixture headerBuilder = new BlockHeaderTestFixture();
BlockHeader parentBlock = headerBuilder.timestamp(parentTimeStamp).buildHeader();
BlockCreationTimeResult result = scheduler.getNextTimestamp(parentBlock);
final BlockHeaderTestFixture headerBuilder = new BlockHeaderTestFixture();
final BlockHeader parentBlock = headerBuilder.timestamp(parentTimeStamp).buildHeader();
final BlockCreationTimeResult result = scheduler.getNextTimestamp(parentBlock);
assertThat(result.getTimestampForHeader()).isEqualTo(parentTimeStamp + interBlockSeconds);
assertThat(result.getMillisecondsUntilValid()).isEqualTo(0);
@ -50,15 +50,15 @@ public class DefaultBlockSchedulerTest {
@Test
public void childBlockWithinClockDriftReportsTimeToValidOfZero() {
Clock clock = mock(Clock.class);
DefaultBlockScheduler scheduler =
final Clock clock = mock(Clock.class);
final DefaultBlockScheduler scheduler =
new DefaultBlockScheduler(interBlockSeconds, acceptableClockDrift, clock);
when(clock.millisecondsSinceEpoch()).thenReturn(parentTimeStamp * 1000);
BlockHeaderTestFixture headerBuilder = new BlockHeaderTestFixture();
BlockHeader parentBlock = headerBuilder.timestamp(parentTimeStamp).buildHeader();
BlockCreationTimeResult result = scheduler.getNextTimestamp(parentBlock);
final BlockHeaderTestFixture headerBuilder = new BlockHeaderTestFixture();
final BlockHeader parentBlock = headerBuilder.timestamp(parentTimeStamp).buildHeader();
final BlockCreationTimeResult result = scheduler.getNextTimestamp(parentBlock);
assertThat(result.getMillisecondsUntilValid()).isEqualTo(0);
}
@ -73,9 +73,9 @@ public class DefaultBlockSchedulerTest {
when(clock.millisecondsSinceEpoch())
.thenReturn((parentTimeStamp - acceptableClockDrift) * 1000);
BlockHeaderTestFixture headerBuilder = new BlockHeaderTestFixture();
BlockHeader parentBlock = headerBuilder.timestamp(parentTimeStamp).buildHeader();
BlockCreationTimeResult result = scheduler.getNextTimestamp(parentBlock);
final BlockHeaderTestFixture headerBuilder = new BlockHeaderTestFixture();
final BlockHeader parentBlock = headerBuilder.timestamp(parentTimeStamp).buildHeader();
final BlockCreationTimeResult result = scheduler.getNextTimestamp(parentBlock);
assertThat(result.getMillisecondsUntilValid()).isEqualTo(interBlockSeconds * 1000);
}
@ -84,15 +84,15 @@ public class DefaultBlockSchedulerTest {
public void ifParentTimestampIsBehindCurrentTimeChildUsesCurrentTime() {
final long secondsSinceEpoch = parentTimeStamp + 5L; // i.e. time is ahead of blockchain
Clock clock = mock(Clock.class);
DefaultBlockScheduler scheduler =
final Clock clock = mock(Clock.class);
final DefaultBlockScheduler scheduler =
new DefaultBlockScheduler(interBlockSeconds, acceptableClockDrift, clock);
when(clock.millisecondsSinceEpoch()).thenReturn(secondsSinceEpoch * 1000);
BlockHeaderTestFixture headerBuilder = new BlockHeaderTestFixture();
BlockHeader parentBlock = headerBuilder.timestamp(parentTimeStamp).buildHeader();
BlockCreationTimeResult result = scheduler.getNextTimestamp(parentBlock);
final BlockHeaderTestFixture headerBuilder = new BlockHeaderTestFixture();
final BlockHeader parentBlock = headerBuilder.timestamp(parentTimeStamp).buildHeader();
final BlockCreationTimeResult result = scheduler.getNextTimestamp(parentBlock);
assertThat(result.getTimestampForHeader()).isEqualTo(secondsSinceEpoch);
}

@ -38,8 +38,8 @@ public class GenesisBlockMismatchTest {
@Test
public void suppliedGenesisBlockMismatchStoredChainDataException() {
KeyValueStorage kvStore = new InMemoryKeyValueStorage();
BlockHeader genesisHeader00 =
final KeyValueStorage kvStore = new InMemoryKeyValueStorage();
final BlockHeader genesisHeader00 =
BlockHeaderBuilder.create()
.parentHash(Hash.ZERO)
.ommersHash(Hash.ZERO)
@ -58,12 +58,12 @@ public class GenesisBlockMismatchTest {
.nonce(0L)
.blockHashFunction(MainnetBlockHashFunction::createHash)
.buildBlockHeader();
BlockBody genesisBody00 = new BlockBody(Collections.emptyList(), Collections.emptyList());
Block genesisBlock00 = new Block(genesisHeader00, genesisBody00);
DefaultMutableBlockchain blockchain00 =
final BlockBody genesisBody00 = new BlockBody(Collections.emptyList(), Collections.emptyList());
final Block genesisBlock00 = new Block(genesisHeader00, genesisBody00);
final DefaultMutableBlockchain blockchain00 =
new DefaultMutableBlockchain(genesisBlock00, kvStore, MainnetBlockHashFunction::createHash);
BlockHeader genesisHeader01 =
final BlockHeader genesisHeader01 =
BlockHeaderBuilder.create()
.parentHash(Hash.ZERO)
.ommersHash(Hash.ZERO)
@ -82,8 +82,8 @@ public class GenesisBlockMismatchTest {
.nonce(0L)
.blockHashFunction(MainnetBlockHashFunction::createHash)
.buildBlockHeader();
BlockBody genesisBody01 = new BlockBody(Collections.emptyList(), Collections.emptyList());
Block genesisBlock01 = new Block(genesisHeader01, genesisBody01);
final BlockBody genesisBody01 = new BlockBody(Collections.emptyList(), Collections.emptyList());
final Block genesisBlock01 = new Block(genesisHeader01, genesisBody01);
assertThatExceptionOfType(InvalidConfigurationException.class)
.isThrownBy(() -> blockchain00.setGenesis(genesisBlock01))

@ -67,7 +67,7 @@ public class ProofOfWorkValidationRuleTest {
@Test
public void failsBlockWithZeroValuedDifficulty() {
BlockHeader header =
final BlockHeader header =
BlockHeaderBuilder.fromHeader(blockHeader)
.difficulty(UInt256.ZERO)
.blockHashFunction(mainnetBlockHashFunction())
@ -77,8 +77,8 @@ public class ProofOfWorkValidationRuleTest {
@Test
public void failsWithVeryLargeDifficulty() {
UInt256 largeDifficulty = UInt256.of(BigInteger.valueOf(2).pow(255));
BlockHeader header =
final UInt256 largeDifficulty = UInt256.of(BigInteger.valueOf(2).pow(255));
final BlockHeader header =
BlockHeaderBuilder.fromHeader(blockHeader)
.difficulty(largeDifficulty)
.blockHashFunction(mainnetBlockHashFunction())
@ -88,8 +88,8 @@ public class ProofOfWorkValidationRuleTest {
@Test
public void failsWithMisMatchedMixHash() {
Hash updateMixHash = Hash.wrap(blockHeader.getMixHash().asUInt256().minus(1L).getBytes());
BlockHeader header =
final Hash updateMixHash = Hash.wrap(blockHeader.getMixHash().asUInt256().minus(1L).getBytes());
final BlockHeader header =
BlockHeaderBuilder.fromHeader(blockHeader)
.mixHash(updateMixHash)
.blockHashFunction(mainnetBlockHashFunction())
@ -99,8 +99,8 @@ public class ProofOfWorkValidationRuleTest {
@Test
public void failsWithMisMatchedNonce() {
long updatedNonce = blockHeader.getNonce() + 1;
BlockHeader header =
final long updatedNonce = blockHeader.getNonce() + 1;
final BlockHeader header =
BlockHeaderBuilder.fromHeader(blockHeader)
.nonce(updatedNonce)
.blockHashFunction(mainnetBlockHashFunction())
@ -109,7 +109,7 @@ public class ProofOfWorkValidationRuleTest {
}
private BlockHashFunction mainnetBlockHashFunction() {
ProtocolSchedule<Void> protocolSchedule = MainnetProtocolSchedule.create();
final ProtocolSchedule<Void> protocolSchedule = MainnetProtocolSchedule.create();
return ScheduleBasedBlockHashFunction.create(protocolSchedule);
}
}

@ -131,7 +131,7 @@ public class BlockchainUtilParameterizedTest {
@Test
public void searchesAscending() {
OptionalInt maybeAncestorNumber =
final OptionalInt maybeAncestorNumber =
BlockchainUtil.findHighestKnownBlockIndex(localBlockchain, headers, true);
assertThat(maybeAncestorNumber.getAsInt()).isEqualTo(Math.toIntExact(commonHeader.getNumber()));
}
@ -139,7 +139,7 @@ public class BlockchainUtilParameterizedTest {
@Test
public void searchesDescending() {
Collections.reverse(headers);
OptionalInt maybeAncestorNumber =
final OptionalInt maybeAncestorNumber =
BlockchainUtil.findHighestKnownBlockIndex(localBlockchain, headers, false);
assertThat(maybeAncestorNumber.getAsInt())
.isEqualTo(Math.toIntExact(chainHeight - commonHeader.getNumber()));

@ -109,7 +109,7 @@ public abstract class AbstractEthTask<T> implements EthTask<T> {
}
try {
return result.get().get();
} catch (InterruptedException | ExecutionException e) {
} catch (final InterruptedException | ExecutionException e) {
return null;
}
}

@ -29,7 +29,7 @@ public abstract class AbstractPeerTask<R> extends AbstractEthTask<PeerTaskResult
@Override
protected void executeTask() {
EthPeer peer;
final EthPeer peer;
if (assignedPeer.isPresent()) {
peer = assignedPeer.get();
} else {

@ -123,7 +123,7 @@ class EthServer {
final int skip = getHeaders.skip();
final int maxHeaders = Math.min(requestLimit, getHeaders.maxHeaders());
final boolean reversed = getHeaders.reverse();
BlockHeader firstHeader;
final BlockHeader firstHeader;
if (hash.isPresent()) {
final Hash startHash = hash.get();
firstHeader = blockchain.getBlockHeader(startHash).orElse(null);

@ -101,7 +101,7 @@ public class BlockPropagationManager<C> {
// Check to see if any of our pending blocks are now ready for import
final Block newBlock = blockAddedEvent.getBlock();
List<Block> readyForImport;
final List<Block> readyForImport;
synchronized (pendingBlocks) {
// Remove block from pendingBlocks list
pendingBlocks.deregisterPendingBlock(newBlock);

@ -95,7 +95,7 @@ public class SynchronizerConfiguration {
return this;
}
SyncMode actualSyncMode;
final SyncMode actualSyncMode;
if (requestedSyncMode.equals(SyncMode.FAST)) {
final boolean blockchainIsEmpty =
blockchain.getChainHeadBlockNumber() != BlockHeader.GENESIS_BLOCK_NUMBER;

@ -128,9 +128,9 @@ public class DetermineCommonAncestorTask<C> extends AbstractEthTask<BlockHeader>
private CompletableFuture<Void> processHeaders(
final AbstractPeerTask.PeerTaskResult<List<BlockHeader>> headersResult) {
initialQuery = false;
List<BlockHeader> headers = headersResult.getResult();
final List<BlockHeader> headers = headersResult.getResult();
OptionalInt maybeAncestorNumber =
final OptionalInt maybeAncestorNumber =
BlockchainUtil.findHighestKnownBlockIndex(protocolContext.getBlockchain(), headers, false);
// Means the insertion point is in the next header request.
@ -138,7 +138,7 @@ public class DetermineCommonAncestorTask<C> extends AbstractEthTask<BlockHeader>
maximumPossibleCommonAncestorNumber = headers.get(headers.size() - 1).getNumber() - 1L;
return CompletableFuture.completedFuture(null);
}
int ancestorNumber = maybeAncestorNumber.getAsInt();
final int ancestorNumber = maybeAncestorNumber.getAsInt();
commonAncestorCandidate = headers.get(ancestorNumber);
if (ancestorNumber - 1 >= 0) {

@ -87,7 +87,7 @@ public final class EthProtocolManagerTest {
@Test
public void disconnectOnUnsolicitedMessage() {
try (EthProtocolManager ethManager = new EthProtocolManager(blockchain, 1, true, 1)) {
try (final EthProtocolManager ethManager = new EthProtocolManager(blockchain, 1, true, 1)) {
final MessageData messageData =
BlockHeadersMessage.create(Collections.singletonList(blockchain.getBlockHeader(1).get()));
final MockPeerConnection peer = setupPeer(ethManager, (cap, msg, conn) -> {});
@ -98,7 +98,7 @@ public final class EthProtocolManagerTest {
@Test
public void disconnectOnFailureToSendStatusMessage() {
try (EthProtocolManager ethManager = new EthProtocolManager(blockchain, 1, true, 1)) {
try (final EthProtocolManager ethManager = new EthProtocolManager(blockchain, 1, true, 1)) {
final MessageData messageData =
BlockHeadersMessage.create(Collections.singletonList(blockchain.getBlockHeader(1).get()));
final MockPeerConnection peer =
@ -110,7 +110,7 @@ public final class EthProtocolManagerTest {
@Test
public void disconnectOnWrongChainId() {
try (EthProtocolManager ethManager = new EthProtocolManager(blockchain, 1, true, 1)) {
try (final EthProtocolManager ethManager = new EthProtocolManager(blockchain, 1, true, 1)) {
final MessageData messageData =
BlockHeadersMessage.create(Collections.singletonList(blockchain.getBlockHeader(1).get()));
final MockPeerConnection peer =
@ -133,7 +133,7 @@ public final class EthProtocolManagerTest {
@Test
public void disconnectOnWrongGenesisHash() {
try (EthProtocolManager ethManager = new EthProtocolManager(blockchain, 1, true, 1)) {
try (final EthProtocolManager ethManager = new EthProtocolManager(blockchain, 1, true, 1)) {
final MessageData messageData =
BlockHeadersMessage.create(Collections.singletonList(blockchain.getBlockHeader(1).get()));
final MockPeerConnection peer =
@ -156,7 +156,7 @@ public final class EthProtocolManagerTest {
@Test(expected = ConditionTimeoutException.class)
public void doNotDisconnectOnValidMessage() {
try (EthProtocolManager ethManager = new EthProtocolManager(blockchain, 1, true, 1)) {
try (final EthProtocolManager ethManager = new EthProtocolManager(blockchain, 1, true, 1)) {
final MessageData messageData =
GetBlockBodiesMessage.create(Collections.singletonList(gen.hash()));
final MockPeerConnection peer = setupPeer(ethManager, (cap, msg, conn) -> {});
@ -171,7 +171,7 @@ public final class EthProtocolManagerTest {
@Test
public void respondToGetHeaders() throws ExecutionException, InterruptedException {
final CompletableFuture<Void> done = new CompletableFuture<>();
try (EthProtocolManager ethManager = new EthProtocolManager(blockchain, 1, true, 1)) {
try (final EthProtocolManager ethManager = new EthProtocolManager(blockchain, 1, true, 1)) {
final long startBlock = 5L;
final int blockCount = 5;
final MessageData messageData =
@ -203,7 +203,8 @@ public final class EthProtocolManagerTest {
public void respondToGetHeadersWithinLimits() throws ExecutionException, InterruptedException {
final CompletableFuture<Void> done = new CompletableFuture<>();
final int limit = 5;
try (EthProtocolManager ethManager = new EthProtocolManager(blockchain, 1, true, 1, limit)) {
try (final EthProtocolManager ethManager =
new EthProtocolManager(blockchain, 1, true, 1, limit)) {
final long startBlock = 5L;
final int blockCount = 10;
final MessageData messageData =
@ -234,7 +235,7 @@ public final class EthProtocolManagerTest {
@Test
public void respondToGetHeadersReversed() throws ExecutionException, InterruptedException {
final CompletableFuture<Void> done = new CompletableFuture<>();
try (EthProtocolManager ethManager = new EthProtocolManager(blockchain, 1, true, 1)) {
try (final EthProtocolManager ethManager = new EthProtocolManager(blockchain, 1, true, 1)) {
final long endBlock = 10L;
final int blockCount = 5;
final MessageData messageData = GetBlockHeadersMessage.create(endBlock, blockCount, true, 0);
@ -264,7 +265,7 @@ public final class EthProtocolManagerTest {
@Test
public void respondToGetHeadersWithSkip() throws ExecutionException, InterruptedException {
final CompletableFuture<Void> done = new CompletableFuture<>();
try (EthProtocolManager ethManager = new EthProtocolManager(blockchain, 1, true, 1)) {
try (final EthProtocolManager ethManager = new EthProtocolManager(blockchain, 1, true, 1)) {
final long startBlock = 5L;
final int blockCount = 5;
final int skip = 1;
@ -297,7 +298,7 @@ public final class EthProtocolManagerTest {
public void respondToGetHeadersReversedWithSkip()
throws ExecutionException, InterruptedException {
final CompletableFuture<Void> done = new CompletableFuture<>();
try (EthProtocolManager ethManager = new EthProtocolManager(blockchain, 1, true, 1)) {
try (final EthProtocolManager ethManager = new EthProtocolManager(blockchain, 1, true, 1)) {
final long endBlock = 10L;
final int blockCount = 5;
final int skip = 1;
@ -351,7 +352,7 @@ public final class EthProtocolManagerTest {
@Test
public void respondToGetHeadersPartial() throws ExecutionException, InterruptedException {
final CompletableFuture<Void> done = new CompletableFuture<>();
try (EthProtocolManager ethManager = new EthProtocolManager(blockchain, 1, true, 1)) {
try (final EthProtocolManager ethManager = new EthProtocolManager(blockchain, 1, true, 1)) {
final long startBlock = blockchain.getChainHeadBlockNumber() - 1L;
final int blockCount = 5;
final MessageData messageData =
@ -382,7 +383,7 @@ public final class EthProtocolManagerTest {
@Test
public void respondToGetHeadersEmpty() throws ExecutionException, InterruptedException {
final CompletableFuture<Void> done = new CompletableFuture<>();
try (EthProtocolManager ethManager = new EthProtocolManager(blockchain, 1, true, 1)) {
try (final EthProtocolManager ethManager = new EthProtocolManager(blockchain, 1, true, 1)) {
final long startBlock = blockchain.getChainHeadBlockNumber() + 1;
final int blockCount = 5;
final MessageData messageData =
@ -410,7 +411,7 @@ public final class EthProtocolManagerTest {
@Test
public void respondToGetBodies() throws ExecutionException, InterruptedException {
final CompletableFuture<Void> done = new CompletableFuture<>();
try (EthProtocolManager ethManager = new EthProtocolManager(blockchain, 1, true, 1)) {
try (final EthProtocolManager ethManager = new EthProtocolManager(blockchain, 1, true, 1)) {
// Setup blocks query
final long startBlock = blockchain.getChainHeadBlockNumber() - 5;
final int blockCount = 2;
@ -454,7 +455,8 @@ public final class EthProtocolManagerTest {
public void respondToGetBodiesWithinLimits() throws ExecutionException, InterruptedException {
final CompletableFuture<Void> done = new CompletableFuture<>();
final int limit = 5;
try (EthProtocolManager ethManager = new EthProtocolManager(blockchain, 1, true, 1, limit)) {
try (final EthProtocolManager ethManager =
new EthProtocolManager(blockchain, 1, true, 1, limit)) {
// Setup blocks query
final int blockCount = 10;
final long startBlock = blockchain.getChainHeadBlockNumber() - blockCount;
@ -497,7 +499,7 @@ public final class EthProtocolManagerTest {
@Test
public void respondToGetBodiesPartial() throws ExecutionException, InterruptedException {
final CompletableFuture<Void> done = new CompletableFuture<>();
try (EthProtocolManager ethManager = new EthProtocolManager(blockchain, 1, true, 1)) {
try (final EthProtocolManager ethManager = new EthProtocolManager(blockchain, 1, true, 1)) {
// Setup blocks query
final long expectedBlockNumber = blockchain.getChainHeadBlockNumber() - 1;
final BlockHeader header = blockchain.getBlockHeader(expectedBlockNumber).get();
@ -534,7 +536,7 @@ public final class EthProtocolManagerTest {
@Test
public void respondToGetReceipts() throws ExecutionException, InterruptedException {
final CompletableFuture<Void> done = new CompletableFuture<>();
try (EthProtocolManager ethManager = new EthProtocolManager(blockchain, 1, true, 1)) {
try (final EthProtocolManager ethManager = new EthProtocolManager(blockchain, 1, true, 1)) {
// Setup blocks query
final long startBlock = blockchain.getChainHeadBlockNumber() - 5;
final int blockCount = 2;
@ -577,7 +579,8 @@ public final class EthProtocolManagerTest {
public void respondToGetReceiptsWithinLimits() throws ExecutionException, InterruptedException {
final CompletableFuture<Void> done = new CompletableFuture<>();
final int limit = 5;
try (EthProtocolManager ethManager = new EthProtocolManager(blockchain, 1, true, 1, limit)) {
try (final EthProtocolManager ethManager =
new EthProtocolManager(blockchain, 1, true, 1, limit)) {
// Setup blocks query
final int blockCount = 10;
final long startBlock = blockchain.getChainHeadBlockNumber() - blockCount;
@ -619,7 +622,7 @@ public final class EthProtocolManagerTest {
@Test
public void respondToGetReceiptsPartial() throws ExecutionException, InterruptedException {
final CompletableFuture<Void> done = new CompletableFuture<>();
try (EthProtocolManager ethManager = new EthProtocolManager(blockchain, 1, true, 1)) {
try (final EthProtocolManager ethManager = new EthProtocolManager(blockchain, 1, true, 1)) {
// Setup blocks query
final long blockNumber = blockchain.getChainHeadBlockNumber() - 5;
final int blockCount = 2;
@ -721,7 +724,7 @@ public final class EthProtocolManagerTest {
blockchain.appendBlock(block, receipts);
final CompletableFuture<Void> done = new CompletableFuture<>();
try (EthProtocolManager ethManager = new EthProtocolManager(blockchain, 1, true, 1)) {
try (final EthProtocolManager ethManager = new EthProtocolManager(blockchain, 1, true, 1)) {
final long startBlock = 1L;
final int requestedBlockCount = 13;
final int receivedBlockCount = 2;

@ -308,7 +308,7 @@ public class DetermineCommonAncestorTaskTest {
@Test
public void shouldShortCircuitOnHeaderInInitialRequest() {
DefaultMutableBlockchain remoteBlockchain =
final DefaultMutableBlockchain remoteBlockchain =
new DefaultMutableBlockchain(
genesisBlock, new InMemoryKeyValueStorage(), MainnetBlockHashFunction::createHash);
@ -316,56 +316,58 @@ public class DetermineCommonAncestorTaskTest {
// Populate common chain
for (long i = 1; i <= 95; i++) {
BlockDataGenerator.BlockOptions options =
final BlockDataGenerator.BlockOptions options =
new BlockDataGenerator.BlockOptions()
.setBlockNumber(i)
.setParentHash(localBlockchain.getBlockHashByNumber(i - 1).get());
commonBlock = blockDataGenerator.block(options);
List<TransactionReceipt> receipts = blockDataGenerator.receipts(commonBlock);
final List<TransactionReceipt> receipts = blockDataGenerator.receipts(commonBlock);
localBlockchain.appendBlock(commonBlock, receipts);
remoteBlockchain.appendBlock(commonBlock, receipts);
}
// Populate local chain
for (long i = 96; i <= 99; i++) {
BlockDataGenerator.BlockOptions options00 =
final BlockDataGenerator.BlockOptions options00 =
new BlockDataGenerator.BlockOptions()
.setBlockNumber(i)
.setParentHash(localBlockchain.getBlockHashByNumber(i - 1).get());
Block block00 = blockDataGenerator.block(options00);
List<TransactionReceipt> receipts00 = blockDataGenerator.receipts(block00);
final Block block00 = blockDataGenerator.block(options00);
final List<TransactionReceipt> receipts00 = blockDataGenerator.receipts(block00);
localBlockchain.appendBlock(block00, receipts00);
}
// Populate remote chain
for (long i = 96; i <= 99; i++) {
BlockDataGenerator.BlockOptions options01 =
final BlockDataGenerator.BlockOptions options01 =
new BlockDataGenerator.BlockOptions()
.setDifficulty(UInt256.ONE)
.setBlockNumber(i)
.setParentHash(remoteBlockchain.getBlockHashByNumber(i - 1).get());
Block block01 = blockDataGenerator.block(options01);
List<TransactionReceipt> receipts01 = blockDataGenerator.receipts(block01);
final Block block01 = blockDataGenerator.block(options01);
final List<TransactionReceipt> receipts01 = blockDataGenerator.receipts(block01);
remoteBlockchain.appendBlock(block01, receipts01);
}
RespondingEthPeer.Responder responder = RespondingEthPeer.blockchainResponder(remoteBlockchain);
RespondingEthPeer respondingEthPeer = EthProtocolManagerTestUtil.createPeer(ethProtocolManager);
final RespondingEthPeer.Responder responder =
RespondingEthPeer.blockchainResponder(remoteBlockchain);
final RespondingEthPeer respondingEthPeer =
EthProtocolManagerTestUtil.createPeer(ethProtocolManager);
DetermineCommonAncestorTask<Void> task =
final DetermineCommonAncestorTask<Void> task =
DetermineCommonAncestorTask.create(
protocolSchedule,
protocolContext,
ethContext,
respondingEthPeer.getEthPeer(),
defaultHeaderRequestSize);
DetermineCommonAncestorTask<Void> spy = spy(task);
final DetermineCommonAncestorTask<Void> spy = spy(task);
// Execute task
CompletableFuture<BlockHeader> future = spy.run();
final CompletableFuture<BlockHeader> future = spy.run();
respondingEthPeer.respondWhile(responder, () -> !future.isDone());
AtomicReference<BlockHeader> result = new AtomicReference<>();
final AtomicReference<BlockHeader> result = new AtomicReference<>();
future.whenComplete(
(response, error) -> {
result.set(response);

@ -80,7 +80,7 @@ public class TestNodeList implements Closeable {
.atMost(30, TimeUnit.SECONDS)
.until(() -> hasConnection(destination, source));
LOG.info("Successfully connected " + source.shortId() + " to dest " + destination);
} catch (InterruptedException | ExecutionException | TimeoutException e) {
} catch (final InterruptedException | ExecutionException | TimeoutException e) {
final String msg =
format(
"Error connecting source node %s to destination node %s in time allotted.",

@ -124,7 +124,8 @@ public class FilterManager extends AbstractVerticle {
public void recordBlockEvent(final BlockAddedEvent event, final Blockchain blockchain) {
final Hash blockHash = event.getBlock().getHash();
Collection<BlockFilter> blockFilters = filterRepository.getFiltersOfType(BlockFilter.class);
final Collection<BlockFilter> blockFilters =
filterRepository.getFiltersOfType(BlockFilter.class);
blockFilters.forEach(
(filter) -> {
synchronized (filter) {
@ -136,7 +137,7 @@ public class FilterManager extends AbstractVerticle {
}
private void checkBlockchainForMatchingLogsForFilters() {
Collection<LogFilter> logFilters = filterRepository.getFiltersOfType(LogFilter.class);
final Collection<LogFilter> logFilters = filterRepository.getFiltersOfType(LogFilter.class);
logFilters.forEach(
(filter) -> {
final long headBlockNumber = blockchainQueries.headBlockNumber();
@ -150,7 +151,7 @@ public class FilterManager extends AbstractVerticle {
@VisibleForTesting
void recordPendingTransactionEvent(final Transaction transaction) {
Collection<PendingTransactionFilter> pendingTransactionFilters =
final Collection<PendingTransactionFilter> pendingTransactionFilters =
filterRepository.getFiltersOfType(PendingTransactionFilter.class);
if (pendingTransactionFilters.isEmpty()) {
return;
@ -213,7 +214,7 @@ public class FilterManager extends AbstractVerticle {
return null;
}
List<LogWithMetadata> logs;
final List<LogWithMetadata> logs;
synchronized (filter) {
logs = new ArrayList<>(filter.logs());
filter.clearLogs();

@ -43,7 +43,7 @@ public class EthCoinbase implements JsonRpcMethod {
return new JsonRpcSuccessResponse(req.getId(), coinbase.get().toString());
}
return new JsonRpcErrorResponse(req.getId(), JsonRpcError.COINBASE_NOT_SPECIFIED);
} catch (UnsupportedOperationException ex) {
} catch (final UnsupportedOperationException ex) {
return new JsonRpcErrorResponse(req.getId(), JsonRpcError.INVALID_REQUEST);
}
}

@ -37,7 +37,7 @@ public class EthGasPrice<C, M extends BlockMiner<C, ? extends AbstractBlockCreat
@Override
public JsonRpcResponse response(final JsonRpcRequest req) {
Wei gasPrice;
final Wei gasPrice;
Object result = null;
gasPrice = miningCoordinator.getMinTransactionGasPrice();
if (gasPrice != null) {

@ -44,11 +44,11 @@ public class EthGetWork implements JsonRpcMethod {
@Override
public JsonRpcResponse response(final JsonRpcRequest req) {
Optional<EthHashSolverInputs> solver = miner.getWorkDefinition();
final Optional<EthHashSolverInputs> solver = miner.getWorkDefinition();
if (solver.isPresent()) {
EthHashSolverInputs rawResult = solver.get();
byte[] dagSeed = DirectAcyclicGraphSeed.dagSeed(rawResult.getBlockNumber());
String[] result = {
final EthHashSolverInputs rawResult = solver.get();
final byte[] dagSeed = DirectAcyclicGraphSeed.dagSeed(rawResult.getBlockNumber());
final String[] result = {
"0x" + BaseEncoding.base16().lowerCase().encode(rawResult.getPrePowHash()),
"0x" + BaseEncoding.base16().lowerCase().encode(dagSeed),
rawResult.getTarget().toHexString()

@ -57,7 +57,7 @@ public class EthSendRawTransaction implements JsonRpcMethod {
}
final String rawTransaction = parameters.required(request.getParams(), 0, String.class);
Transaction transaction;
final Transaction transaction;
try {
transaction = decodeRawTransaction(rawTransaction);
} catch (final InvalidJsonRpcRequestException e) {
@ -77,7 +77,7 @@ public class EthSendRawTransaction implements JsonRpcMethod {
throws InvalidJsonRpcRequestException {
try {
return Transaction.readFrom(RLP.input(BytesValue.fromHexString(hash)));
} catch (IllegalArgumentException | RLPException e) {
} catch (final IllegalArgumentException | RLPException e) {
LOG.debug(e);
throw new InvalidJsonRpcRequestException("Invalid raw transaction hex", e);
}

@ -44,7 +44,7 @@ public class MinerSetCoinbase implements JsonRpcMethod {
final Address coinbase = parameters.required(req.getParams(), 0, Address.class);
miningCoordinator.setCoinbase(coinbase);
return new JsonRpcSuccessResponse(req.getId(), true);
} catch (UnsupportedOperationException ex) {
} catch (final UnsupportedOperationException ex) {
return new JsonRpcErrorResponse(req.getId(), JsonRpcError.INVALID_REQUEST);
}
}

@ -40,10 +40,10 @@ public class WebSocketRequestHandler {
public void handle(final String id, final Buffer buffer) {
vertx.executeBlocking(
future -> {
WebSocketRpcRequest request;
final WebSocketRpcRequest request;
try {
request = buffer.toJsonObject().mapTo(WebSocketRpcRequest.class);
} catch (IllegalArgumentException | DecodeException e) {
} catch (final IllegalArgumentException | DecodeException e) {
LOG.debug("Error mapping json to WebSocketRpcRequest", e);
future.complete(JsonRpcError.INVALID_REQUEST);
return;

@ -71,7 +71,7 @@ public class AdminJsonRpcHttpServiceTest extends JsonRpcHttpServiceTest {
"{\"jsonrpc\":\"2.0\",\"id\":" + Json.encode(id) + ",\"method\":\"admin_peers\"}");
final Request request = new Request.Builder().post(body).url(baseUrl).build();
LOG.info("Request: " + request);
try (Response resp = client.newCall(request).execute()) {
try (final Response resp = client.newCall(request).execute()) {
LOG.info("Response: " + resp);
assertThat(resp.code()).isEqualTo(200);

@ -255,7 +255,7 @@ public class EthJsonRpcHttpBySpecTest extends AbstractEthJsonRpcHttpServiceTest
final Request request = new Request.Builder().post(requestBody).url(baseUrl).build();
importBlocks(1, BLOCKS.size());
try (Response resp = client.newCall(request).execute()) {
try (final Response resp = client.newCall(request).execute()) {
final int expectedStatusCode = spec.getInteger("statusCode");
assertThat(resp.code()).isEqualTo(expectedStatusCode);

@ -167,7 +167,7 @@ public class FilterManagerLogFilterTest {
@Test
public void getLogsChangesShouldResetFilterExpireDate() {
LogFilter filter = spy(new LogFilter("foo", latest(), latest(), logsQuery()));
final LogFilter filter = spy(new LogFilter("foo", latest(), latest(), logsQuery()));
doReturn(Optional.of(filter)).when(filterRepository).getFilter(eq("foo"), eq(LogFilter.class));
filterManager.logsChanges("foo");
@ -177,7 +177,7 @@ public class FilterManagerLogFilterTest {
@Test
public void getLogsShouldResetFilterExpireDate() {
LogFilter filter = spy(new LogFilter("foo", latest(), latest(), logsQuery()));
final LogFilter filter = spy(new LogFilter("foo", latest(), latest(), logsQuery()));
doReturn(Optional.of(filter)).when(filterRepository).getFilter(eq("foo"), eq(LogFilter.class));
filterManager.logs("foo");

@ -201,7 +201,7 @@ public class FilterManagerTest {
@Test
public void getBlockChangesShouldResetFilterExpireDate() {
BlockFilter filter = spy(new BlockFilter("foo"));
final BlockFilter filter = spy(new BlockFilter("foo"));
doReturn(Optional.of(filter))
.when(filterRepository)
.getFilter(eq("foo"), eq(BlockFilter.class));
@ -213,7 +213,7 @@ public class FilterManagerTest {
@Test
public void getPendingTransactionsChangesShouldResetFilterExpireDate() {
PendingTransactionFilter filter = spy(new PendingTransactionFilter("foo"));
final PendingTransactionFilter filter = spy(new PendingTransactionFilter("foo"));
doReturn(Optional.of(filter))
.when(filterRepository)
.getFilter(eq("foo"), eq(PendingTransactionFilter.class));

@ -33,12 +33,12 @@ public class FilterRepositoryTest {
@Test
public void getFiltersShouldReturnAllFilters() {
BlockFilter filter1 = new BlockFilter("foo");
BlockFilter filter2 = new BlockFilter("bar");
final BlockFilter filter1 = new BlockFilter("foo");
final BlockFilter filter2 = new BlockFilter("bar");
repository.save(filter1);
repository.save(filter2);
Collection<Filter> filters = repository.getFilters();
final Collection<Filter> filters = repository.getFilters();
assertThat(filters).containsExactlyInAnyOrderElementsOf(Lists.newArrayList(filter1, filter2));
}
@ -50,17 +50,17 @@ public class FilterRepositoryTest {
@Test
public void saveShouldAddFilterToRepository() {
BlockFilter filter = new BlockFilter("id");
final BlockFilter filter = new BlockFilter("id");
repository.save(filter);
BlockFilter retrievedFilter = repository.getFilter("id", BlockFilter.class).get();
final BlockFilter retrievedFilter = repository.getFilter("id", BlockFilter.class).get();
assertThat(retrievedFilter).isEqualToComparingFieldByField(filter);
}
@Test
public void saveNullFilterShouldFail() {
Throwable throwable = catchThrowable(() -> repository.save(null));
final Throwable throwable = catchThrowable(() -> repository.save(null));
assertThat(throwable)
.isInstanceOf(IllegalArgumentException.class)
@ -69,10 +69,10 @@ public class FilterRepositoryTest {
@Test
public void saveFilterWithSameIdShouldFail() {
BlockFilter filter = new BlockFilter("x");
final BlockFilter filter = new BlockFilter("x");
repository.save(filter);
Throwable throwable = catchThrowable(() -> repository.save(filter));
final Throwable throwable = catchThrowable(() -> repository.save(filter));
assertThat(throwable)
.isInstanceOf(IllegalArgumentException.class)
@ -81,10 +81,10 @@ public class FilterRepositoryTest {
@Test
public void getSingleFilterShouldReturnExistingFilterOfCorrectType() {
BlockFilter filter = new BlockFilter("id");
final BlockFilter filter = new BlockFilter("id");
repository.save(filter);
Optional<BlockFilter> optional = repository.getFilter(filter.getId(), BlockFilter.class);
final Optional<BlockFilter> optional = repository.getFilter(filter.getId(), BlockFilter.class);
assertThat(optional.isPresent()).isTrue();
assertThat(optional.get()).isEqualToComparingFieldByField(filter);
@ -92,10 +92,10 @@ public class FilterRepositoryTest {
@Test
public void getSingleFilterShouldReturnEmptyForFilterOfIncorrectType() {
BlockFilter filter = new BlockFilter("id");
final BlockFilter filter = new BlockFilter("id");
repository.save(filter);
Optional<PendingTransactionFilter> optional =
final Optional<PendingTransactionFilter> optional =
repository.getFilter(filter.getId(), PendingTransactionFilter.class);
assertThat(optional.isPresent()).isFalse();
@ -103,58 +103,58 @@ public class FilterRepositoryTest {
@Test
public void getSingleFilterShouldReturnEmptyForAbsentId() {
BlockFilter filter = new BlockFilter("foo");
final BlockFilter filter = new BlockFilter("foo");
repository.save(filter);
Optional<BlockFilter> optional = repository.getFilter("bar", BlockFilter.class);
final Optional<BlockFilter> optional = repository.getFilter("bar", BlockFilter.class);
assertThat(optional.isPresent()).isFalse();
}
@Test
public void getSingleFilterShouldReturnEmptyForEmptyRepository() {
Optional<BlockFilter> optional = repository.getFilter("id", BlockFilter.class);
final Optional<BlockFilter> optional = repository.getFilter("id", BlockFilter.class);
assertThat(optional.isPresent()).isFalse();
}
@Test
public void getFilterCollectionShouldReturnAllFiltersOfSpecificType() {
BlockFilter blockFilter1 = new BlockFilter("foo");
BlockFilter blockFilter2 = new BlockFilter("biz");
PendingTransactionFilter pendingTxFilter1 = new PendingTransactionFilter("bar");
final BlockFilter blockFilter1 = new BlockFilter("foo");
final BlockFilter blockFilter2 = new BlockFilter("biz");
final PendingTransactionFilter pendingTxFilter1 = new PendingTransactionFilter("bar");
Collection<BlockFilter> expectedFilters = Lists.newArrayList(blockFilter1, blockFilter2);
final Collection<BlockFilter> expectedFilters = Lists.newArrayList(blockFilter1, blockFilter2);
repository.save(blockFilter1);
repository.save(blockFilter2);
repository.save(pendingTxFilter1);
Collection<BlockFilter> blockFilters = repository.getFiltersOfType(BlockFilter.class);
final Collection<BlockFilter> blockFilters = repository.getFiltersOfType(BlockFilter.class);
assertThat(blockFilters).containsExactlyInAnyOrderElementsOf(expectedFilters);
}
@Test
public void getFilterCollectionShouldReturnEmptyForNoneMatchingTypes() {
PendingTransactionFilter filter = new PendingTransactionFilter("foo");
final PendingTransactionFilter filter = new PendingTransactionFilter("foo");
repository.save(filter);
Collection<BlockFilter> filters = repository.getFiltersOfType(BlockFilter.class);
final Collection<BlockFilter> filters = repository.getFiltersOfType(BlockFilter.class);
assertThat(filters).isEmpty();
}
@Test
public void getFilterCollectionShouldReturnEmptyListForEmptyRepository() {
Collection<BlockFilter> filters = repository.getFiltersOfType(BlockFilter.class);
final Collection<BlockFilter> filters = repository.getFiltersOfType(BlockFilter.class);
assertThat(filters).isEmpty();
}
@Test
public void existsShouldReturnTrueForExistingId() {
BlockFilter filter = new BlockFilter("id");
final BlockFilter filter = new BlockFilter("id");
repository.save(filter);
assertThat(repository.exists("id")).isTrue();
@ -162,7 +162,7 @@ public class FilterRepositoryTest {
@Test
public void existsShouldReturnFalseForAbsentId() {
BlockFilter filter = new BlockFilter("foo");
final BlockFilter filter = new BlockFilter("foo");
repository.save(filter);
assertThat(repository.exists("bar")).isFalse();
@ -175,7 +175,7 @@ public class FilterRepositoryTest {
@Test
public void deleteExistingFilterShouldDeleteSuccessfully() {
BlockFilter filter = new BlockFilter("foo");
final BlockFilter filter = new BlockFilter("foo");
repository.save(filter);
repository.delete(filter.getId());
@ -190,8 +190,8 @@ public class FilterRepositoryTest {
@Test
public void deleteAllShouldClearFilters() {
BlockFilter filter1 = new BlockFilter("foo");
BlockFilter filter2 = new BlockFilter("biz");
final BlockFilter filter1 = new BlockFilter("foo");
final BlockFilter filter2 = new BlockFilter("biz");
repository.save(filter1);
repository.save(filter2);

@ -23,14 +23,14 @@ public class FilterTest {
@Test
public void filterJustCreatedShouldNotBeExpired() {
BlockFilter filter = new BlockFilter("foo");
final BlockFilter filter = new BlockFilter("foo");
assertThat(filter.isExpired()).isFalse();
}
@Test
public void isExpiredShouldReturnTrueForExpiredFilter() {
BlockFilter filter = new BlockFilter("foo");
final BlockFilter filter = new BlockFilter("foo");
filter.setExpireTime(Instant.now().minusSeconds(1));
assertThat(filter.isExpired()).isTrue();
@ -38,7 +38,7 @@ public class FilterTest {
@Test
public void resetExpireDateShouldIncrementExpireDate() {
BlockFilter filter = new BlockFilter("foo");
final BlockFilter filter = new BlockFilter("foo");
filter.setExpireTime(Instant.now().minus(Duration.ofDays(1)));
filter.resetExpireTime();

@ -41,7 +41,7 @@ public class FilterTimeoutMonitorTest {
@Test
public void expiredFilterShouldBeDeleted() {
Filter filter = spy(new BlockFilter("foo"));
final Filter filter = spy(new BlockFilter("foo"));
when(filter.isExpired()).thenReturn(true);
when(filterRepository.getFilters()).thenReturn(Lists.newArrayList(filter));
@ -54,7 +54,7 @@ public class FilterTimeoutMonitorTest {
@Test
public void nonExpiredFilterShouldNotBeDeleted() {
Filter filter = mock(Filter.class);
final Filter filter = mock(Filter.class);
when(filter.isExpired()).thenReturn(false);
when(filterRepository.getFilters()).thenReturn(Lists.newArrayList(filter));

@ -69,7 +69,7 @@ public class EthGetWorkTest {
new JsonRpcSuccessResponse(request.getId(), expectedValue);
when(miningCoordinator.getWorkDefinition()).thenReturn(Optional.of(values));
JsonRpcResponse actualResponse = method.response(request);
final JsonRpcResponse actualResponse = method.response(request);
assertThat(actualResponse).isEqualToComparingFieldByField(expectedResponse);
}
@ -89,7 +89,7 @@ public class EthGetWorkTest {
final JsonRpcResponse expectedResponse =
new JsonRpcSuccessResponse(request.getId(), expectedValue);
when(miningCoordinator.getWorkDefinition()).thenReturn(Optional.of(values));
JsonRpcResponse actualResponse = method.response(request);
final JsonRpcResponse actualResponse = method.response(request);
assertThat(actualResponse).isEqualToComparingFieldByField(expectedResponse);
}
@ -100,7 +100,7 @@ public class EthGetWorkTest {
new JsonRpcErrorResponse(request.getId(), JsonRpcError.NO_MINING_WORK_FOUND);
when(miningCoordinator.getWorkDefinition()).thenReturn(Optional.empty());
JsonRpcResponse actualResponse = method.response(request);
final JsonRpcResponse actualResponse = method.response(request);
assertThat(actualResponse).isEqualToComparingFieldByField(expectedResponse);
}

@ -197,10 +197,10 @@ public class SubscriptionManagerTest {
@Test
public void unsubscribeOthersSubscriptionsNotHavingOwnSubscriptionShouldReturnNotFound() {
SubscribeRequest subscribeRequest = subscribeRequest(CONNECTION_ID);
Long subscriptionId = subscriptionManager.subscribe(subscribeRequest);
final SubscribeRequest subscribeRequest = subscribeRequest(CONNECTION_ID);
final Long subscriptionId = subscriptionManager.subscribe(subscribeRequest);
UnsubscribeRequest unsubscribeRequest =
final UnsubscribeRequest unsubscribeRequest =
new UnsubscribeRequest(subscriptionId, UUID.randomUUID().toString());
final Throwable thrown =
@ -210,15 +210,15 @@ public class SubscriptionManagerTest {
@Test
public void unsubscribeOthersSubscriptionsHavingOwnSubscriptionShouldReturnNotFound() {
String ownConnectionId = UUID.randomUUID().toString();
SubscribeRequest ownSubscribeRequest = subscribeRequest(ownConnectionId);
final String ownConnectionId = UUID.randomUUID().toString();
final SubscribeRequest ownSubscribeRequest = subscribeRequest(ownConnectionId);
subscriptionManager.subscribe(ownSubscribeRequest);
String otherConnectionId = UUID.randomUUID().toString();
SubscribeRequest otherSubscribeRequest = subscribeRequest(otherConnectionId);
Long otherSubscriptionId = subscriptionManager.subscribe(otherSubscribeRequest);
final String otherConnectionId = UUID.randomUUID().toString();
final SubscribeRequest otherSubscribeRequest = subscribeRequest(otherConnectionId);
final Long otherSubscriptionId = subscriptionManager.subscribe(otherSubscribeRequest);
UnsubscribeRequest unsubscribeRequest =
final UnsubscribeRequest unsubscribeRequest =
new UnsubscribeRequest(otherSubscriptionId, ownConnectionId);
final Throwable thrown =

@ -110,7 +110,7 @@ public class Packet {
new PeerDiscoveryPacketDecodingException("Unrecognized packet type: " + type));
final PacketType.Deserializer<?> deserializer = packetType.getDeserializer();
PacketData packetData;
final PacketData packetData;
try {
packetData = deserializer.deserialize(RLP.input(message, PACKET_DATA_INDEX));
} catch (final RLPException e) {

@ -122,7 +122,7 @@ public class PeerTable {
// and an eviction
// candidate is proposed. The Bucket#add method will raise an exception if the peer already
// existed.
Optional<DiscoveryPeer> res;
final Optional<DiscoveryPeer> res;
try {
res = bucket.add(peer);
} catch (final IllegalArgumentException ex) {

@ -165,10 +165,10 @@ public class ECIESEncryptionEngine {
private byte[] encrypt(final byte[] in, final int inOff, final int inLen, final byte[] macData)
throws InvalidCipherTextException {
byte[] C;
byte[] K;
byte[] K1;
byte[] K2;
final byte[] C;
final byte[] K;
final byte[] K1;
final byte[] K2;
int len;
@ -245,10 +245,10 @@ public class ECIESEncryptionEngine {
private byte[] decrypt(
final byte[] inEnc, final int inOff, final int inLen, final byte[] commonMac)
throws InvalidCipherTextException {
byte[] M;
byte[] K;
byte[] K1;
byte[] K2;
final byte[] M;
final byte[] K;
final byte[] K1;
final byte[] K2;
int len;

@ -294,8 +294,8 @@ public final class NettyP2PNetworkTest {
final SECP256K1.KeyPair remoteKp = SECP256K1.KeyPair.generate();
final BytesValue localId = localKp.getPublicKey().getEncodedBytes();
final BytesValue remoteId = remoteKp.getPublicKey().getEncodedBytes();
PeerBlacklist localBlacklist = new PeerBlacklist();
PeerBlacklist remoteBlacklist = new PeerBlacklist();
final PeerBlacklist localBlacklist = new PeerBlacklist();
final PeerBlacklist remoteBlacklist = new PeerBlacklist();
final SubProtocol subprotocol = subProtocol();
final Capability cap = Capability.create(subprotocol.getName(), 63);

@ -45,7 +45,7 @@ public class NetworkingServiceLifecycleTest {
@Test
public void createPeerDiscoveryAgent() {
final SECP256K1.KeyPair keyPair = SECP256K1.KeyPair.generate();
try (NettyP2PNetwork service =
try (final NettyP2PNetwork service =
new NettyP2PNetwork(
vertx,
keyPair,
@ -67,7 +67,7 @@ public class NetworkingServiceLifecycleTest {
final NetworkingConfiguration config =
NetworkingConfiguration.create()
.setDiscovery(DiscoveryConfiguration.create().setBindHost(null));
try (P2PNetwork broken =
try (final P2PNetwork broken =
new NettyP2PNetwork(vertx, keyPair, config, emptyList(), () -> true, new PeerBlacklist())) {
Assertions.fail("Expected Exception");
}
@ -79,7 +79,7 @@ public class NetworkingServiceLifecycleTest {
final NetworkingConfiguration config =
NetworkingConfiguration.create()
.setDiscovery(DiscoveryConfiguration.create().setBindHost("fake.fake.fake"));
try (P2PNetwork broken =
try (final P2PNetwork broken =
new NettyP2PNetwork(vertx, keyPair, config, emptyList(), () -> true, new PeerBlacklist())) {
Assertions.fail("Expected Exception");
}
@ -91,7 +91,7 @@ public class NetworkingServiceLifecycleTest {
final NetworkingConfiguration config =
NetworkingConfiguration.create()
.setDiscovery(DiscoveryConfiguration.create().setBindPort(-1));
try (P2PNetwork broken =
try (final P2PNetwork broken =
new NettyP2PNetwork(vertx, keyPair, config, emptyList(), () -> true, new PeerBlacklist())) {
Assertions.fail("Expected Exception");
}
@ -99,7 +99,7 @@ public class NetworkingServiceLifecycleTest {
@Test(expected = IllegalArgumentException.class)
public void createPeerDiscoveryAgent_NullKeyPair() throws IOException {
try (P2PNetwork broken =
try (final P2PNetwork broken =
new NettyP2PNetwork(
vertx, null, configWithRandomPorts(), emptyList(), () -> true, new PeerBlacklist())) {
Assertions.fail("Expected Exception");
@ -109,7 +109,7 @@ public class NetworkingServiceLifecycleTest {
@Test
public void startStopPeerDiscoveryAgent() {
final SECP256K1.KeyPair keyPair = SECP256K1.KeyPair.generate();
try (NettyP2PNetwork service =
try (final NettyP2PNetwork service =
new NettyP2PNetwork(
vertx,
keyPair,
@ -126,7 +126,7 @@ public class NetworkingServiceLifecycleTest {
@Test
public void startDiscoveryAgentBackToBack() {
final SECP256K1.KeyPair keyPair = SECP256K1.KeyPair.generate();
try (NettyP2PNetwork service1 =
try (final NettyP2PNetwork service1 =
new NettyP2PNetwork(
vertx,
keyPair,
@ -134,7 +134,7 @@ public class NetworkingServiceLifecycleTest {
emptyList(),
() -> true,
new PeerBlacklist());
NettyP2PNetwork service2 =
final NettyP2PNetwork service2 =
new NettyP2PNetwork(
vertx,
keyPair,
@ -152,7 +152,7 @@ public class NetworkingServiceLifecycleTest {
@Test
public void startDiscoveryPortInUse() {
final SECP256K1.KeyPair keyPair = SECP256K1.KeyPair.generate();
try (NettyP2PNetwork service1 =
try (final NettyP2PNetwork service1 =
new NettyP2PNetwork(
vertx,
keyPair,
@ -163,7 +163,7 @@ public class NetworkingServiceLifecycleTest {
service1.run();
final NetworkingConfiguration config = configWithRandomPorts();
config.getDiscovery().setBindPort(service1.getDiscoverySocketAddress().getPort());
try (NettyP2PNetwork service2 =
try (final NettyP2PNetwork service2 =
new NettyP2PNetwork(
vertx, keyPair, config, emptyList(), () -> true, new PeerBlacklist())) {
try {
@ -186,7 +186,7 @@ public class NetworkingServiceLifecycleTest {
@Test
public void createPeerDiscoveryAgent_NoActivePeers() {
final SECP256K1.KeyPair keyPair = SECP256K1.KeyPair.generate();
try (NettyP2PNetwork agent =
try (final NettyP2PNetwork agent =
new NettyP2PNetwork(
vertx,
keyPair,

@ -189,7 +189,7 @@ public abstract class AbstractPeerDiscoveryTest {
result.complete(discoveryTestSocket);
});
DiscoveryTestSocket discoveryTestSocket;
final DiscoveryTestSocket discoveryTestSocket;
try {
discoveryTestSocket = result.get(TEST_SOCKET_START_TIMEOUT_SECS, TimeUnit.SECONDS);
} catch (final Exception ex) {
@ -268,7 +268,7 @@ public abstract class AbstractPeerDiscoveryTest {
* @return the head of the queue
*/
public Packet compulsoryPoll() {
Packet packet;
final Packet packet;
try {
packet = queue.poll(5, TimeUnit.SECONDS);
} catch (final Exception e) {

@ -121,7 +121,7 @@ public class PeerDiscoveryObserversTest extends AbstractPeerDiscoveryTest {
await()
.atMost(5, TimeUnit.SECONDS)
.untilAsserted(() -> assertThat(queue.size()).isEqualTo(5));
} catch (ConditionTimeoutException | AssertionError e) {
} catch (final ConditionTimeoutException | AssertionError e) {
final List<String> events = new ArrayList<>();
queue.forEach(evt -> events.add(evt.toString()));
LOG.error("Queue:\n" + String.join("\n", events), e);

@ -149,7 +149,7 @@ abstract class AbstractRLPOutput implements RLPOutput {
assert values.size() == 1;
final BytesValue value = values.get(0);
int finalOffset;
final int finalOffset;
// Single non-list value.
if (rlpEncoded.get(0)) {
value.copyTo(res, 0);

@ -226,8 +226,8 @@ public abstract class RLP {
return encodedValue;
}
int offset;
int size;
final int offset;
final int size;
if (kind == Kind.SHORT_ELEMENT) {
offset = 1;
size = prefix - 0x80;

@ -95,7 +95,7 @@ abstract class CompactEncoding {
final boolean isLeaf = (metadata & 0x20) != 0;
final int pathLength = ((size - 1) * 2) + (isLeaf ? 1 : 0);
MutableBytesValue path;
final MutableBytesValue path;
int i = 0;
if ((metadata & 0x10) != 0) {

@ -119,7 +119,7 @@ class StoredNodeFactory<V> implements NodeFactory<V> {
case 2:
final BytesValue encodedPath = nodeRLPs.readBytesValue();
BytesValue path;
final BytesValue path;
try {
path = CompactEncoding.decode(encodedPath);
} catch (final IllegalArgumentException ex) {
@ -175,7 +175,7 @@ class StoredNodeFactory<V> implements NodeFactory<V> {
}
}
Optional<V> value;
final Optional<V> value;
if (nodeRLPs.nextIsNull()) {
nodeRLPs.skipNext();
value = Optional.empty();
@ -205,7 +205,7 @@ class StoredNodeFactory<V> implements NodeFactory<V> {
}
private V decodeValue(final RLPInput valueRlp, final Supplier<String> errMessage) {
BytesValue bytes;
final BytesValue bytes;
try {
bytes = valueRlp.readBytesValue();
} catch (final RLPException ex) {
@ -216,7 +216,7 @@ class StoredNodeFactory<V> implements NodeFactory<V> {
}
private V deserializeValue(final Supplier<String> errMessage, final BytesValue bytes) {
V value;
final V value;
try {
value = valueDeserializer.apply(bytes);
} catch (final IllegalArgumentException ex) {

@ -118,7 +118,7 @@ public class Runner implements AutoCloseable {
final File portsFile = new File(dataDir.toFile(), "pantheon.ports");
portsFile.deleteOnExit();
try (FileOutputStream fileOutputStream = new FileOutputStream(portsFile)) {
try (final FileOutputStream fileOutputStream = new FileOutputStream(portsFile)) {
properties.store(
fileOutputStream,
"This file contains the ports used by the running instance of Pantheon. This file will be deleted after the node is shutdown.");

@ -200,7 +200,7 @@ public class RunnerBuilder {
private FilterManager createFilterManager(
final Vertx vertx, final ProtocolContext<?> context, final TransactionPool transactionPool) {
FilterManager filterManager =
final FilterManager filterManager =
new FilterManager(
new BlockchainQueries(context.getBlockchain(), context.getWorldStateArchive()),
transactionPool,

@ -46,7 +46,7 @@ class ConfigOptionSearchAndRunHandler extends AbstractParseResultHandler<List<Ob
final CommandLine commandLine = parseResult.asCommandLineList().get(0);
if (parseResult.hasMatchedOption(configFileOptionName)) {
final OptionSpec configFileOption = parseResult.matchedOption(configFileOptionName);
File configFile;
final File configFile;
try {
configFile = configFileOption.getter().get();
} catch (final Exception e) {

@ -61,7 +61,7 @@ public class EthNetworkConfig {
if (o == null || getClass() != o.getClass()) {
return false;
}
EthNetworkConfig that = (EthNetworkConfig) o;
final EthNetworkConfig that = (EthNetworkConfig) o;
return networkId == that.networkId
&& Objects.equals(genesisConfig, that.genesisConfig)
&& Objects.equals(bootNodes, that.bootNodes);
@ -97,7 +97,7 @@ public class EthNetworkConfig {
private static URI jsonConfigURI(final String resourceName) {
try {
return Resources.getResource(resourceName).toURI();
} catch (URISyntaxException e) {
} catch (final URISyntaxException e) {
throw new IllegalStateException(e);
}
}

@ -58,7 +58,7 @@ class ExportPublicKeySubCommand implements Runnable {
//noinspection ConstantConditions
final Path path = publicKeyExportFile.toPath();
try (BufferedWriter fileWriter = Files.newBufferedWriter(path, UTF_8)) {
try (final BufferedWriter fileWriter = Files.newBufferedWriter(path, UTF_8)) {
fileWriter.write(keyPair.getPublicKey().toString());
} catch (final IOException e) {
LOG.error("An error occurred while trying to write the public key", e);

@ -102,7 +102,7 @@ public class PantheonCommand implements Runnable {
public static class RpcApisConverter implements ITypeConverter<RpcApi> {
@Override
public RpcApi convert(final String name) throws RpcApisConversionException {
String uppercaseName = name.trim().toUpperCase();
final String uppercaseName = name.trim().toUpperCase();
return Stream.<Function<String, Optional<RpcApi>>>of(
RpcApis::valueOf, CliqueRpcApis::valueOf, IbftRpcApis::valueOf)
@ -514,7 +514,7 @@ public class PantheonCommand implements Runnable {
private Path getDefaultPantheonDataDir() {
// this property is retrieved from Gradle tasks or Pantheon running shell script.
final String pantheonHomeProperty = System.getProperty(PANTHEON_HOME_PROPERTY_NAME);
Path pantheonHome;
final Path pantheonHome;
// If prop is found, then use it
if (pantheonHomeProperty != null) {
@ -569,7 +569,7 @@ public class PantheonCommand implements Runnable {
}
private EthNetworkConfig updateNetworkConfig(final EthNetworkConfig ethNetworkConfig) {
EthNetworkConfig.Builder builder = new EthNetworkConfig.Builder(ethNetworkConfig);
final EthNetworkConfig.Builder builder = new EthNetworkConfig.Builder(ethNetworkConfig);
if (genesisFile != null) {
builder.setGenesisConfig(genesisFile.toPath().toUri());
}

@ -54,7 +54,7 @@ public class TomlConfigFileDefaultProvider implements IDefaultValueProvider {
private String getConfigurationValue(final OptionSpec optionSpec) {
final String optionKey = getConfigurationKey(optionSpec);
String
final String
defaultValue; // Convert values to the right string representation for default string value
if (optionSpec.type().equals(Boolean.class)) {
defaultValue = getBooleanEntryAsString(optionKey);

@ -42,7 +42,7 @@ public class CorsAllowedOriginsProperty {
@Override
public CorsAllowedOriginsProperty convert(final String value) throws IllegalArgumentException {
List<String> domains;
final List<String> domains;
if (value != null && !value.isEmpty()) {
domains = new ArrayList<>(Arrays.asList(value.split("\\s*,\\s*")));
} else {

@ -126,13 +126,13 @@ public class BlockchainImporter extends BlockImporter {
final FileRLPInput rlp = new FileRLPInput(file, true);
LOG.info("Import started.");
BlockchainImporter.ImportResult blockImportResults;
final BlockchainImporter.ImportResult blockImportResults;
blockImportResults =
importBlockchain(
pantheonController, rlp, isSkipBlocks, metricsIntervalSec, worldStateOffset);
if (!isSkipAccounts) {
Hash worldStateRootHash;
final Hash worldStateRootHash;
worldStateRootHash =
importWorldState(pantheonController, rlp, metricsIntervalSec, accountCommitInterval);
validateWorldStateRootHash(pantheonController, worldStateRootHash);
@ -277,7 +277,7 @@ public class BlockchainImporter extends BlockImporter {
itemStartingOffset, header, body, receiptsStr));
}
tech.pegasys.pantheon.ethereum.core.BlockImporter<C> blockImporter;
final tech.pegasys.pantheon.ethereum.core.BlockImporter<C> blockImporter;
blockImporter = protocolSpec.getBlockImporter();
if (!isSkipBlocks) {

@ -185,7 +185,7 @@ public class PantheonCommandTest extends CommandTestAbstract {
// We write a config file to prevent an invalid file in resource folder to raise errors in
// code checks (CI + IDE)
final File tempConfigFile = temp.newFile("invalid_config.toml");
try (Writer fileWriter = Files.newBufferedWriter(tempConfigFile.toPath(), UTF_8)) {
try (final Writer fileWriter = Files.newBufferedWriter(tempConfigFile.toPath(), UTF_8)) {
fileWriter.write("."); // an invalid toml content
fileWriter.flush();
@ -206,7 +206,7 @@ public class PantheonCommandTest extends CommandTestAbstract {
// We write a config file to prevent an invalid file in resource folder to raise errors in
// code checks (CI + IDE)
final File tempConfigFile = temp.newFile("invalid_config.toml");
try (Writer fileWriter = Files.newBufferedWriter(tempConfigFile.toPath(), UTF_8)) {
try (final Writer fileWriter = Files.newBufferedWriter(tempConfigFile.toPath(), UTF_8)) {
fileWriter.write("tester===========......."); // an invalid toml content
fileWriter.flush();
@ -261,7 +261,7 @@ public class PantheonCommandTest extends CommandTestAbstract {
asList("enode://001@123:4567", "enode://002@123:4567", "enode://003@123:4567");
assertThat(stringListArgumentCaptor.getValue()).isEqualTo(nodes);
EthNetworkConfig networkConfig =
final EthNetworkConfig networkConfig =
new Builder(EthNetworkConfig.mainnet())
.setGenesisConfig(new File("~/genesys.json").toPath().toUri())
.setBootNodes(nodes)

@ -44,7 +44,7 @@ public class TomlConfigFileDefaultProviderTest {
@Test
public void defaultValueIsNullIfNoMatchingKeyFoundOtherwiseTheValue() throws IOException {
final File tempConfigFile = temp.newFile("config.toml");
try (Writer fileWriter = Files.newBufferedWriter(tempConfigFile.toPath(), UTF_8)) {
try (final Writer fileWriter = Files.newBufferedWriter(tempConfigFile.toPath(), UTF_8)) {
fileWriter.write("an-option='123'");
fileWriter.flush();
@ -64,7 +64,8 @@ public class TomlConfigFileDefaultProviderTest {
@Test
public void defaultValueForOptionMustMatchType() throws IOException {
final File tempConfigFile = temp.newFile("config.toml");
try (BufferedWriter fileWriter = Files.newBufferedWriter(tempConfigFile.toPath(), UTF_8)) {
try (final BufferedWriter fileWriter =
Files.newBufferedWriter(tempConfigFile.toPath(), UTF_8)) {
fileWriter.write("a-boolean-option=true");
fileWriter.newLine();
@ -137,7 +138,8 @@ public class TomlConfigFileDefaultProviderTest {
+ "\"\"\", a number, a boolean, a date/time, an array, or a table (line 1, column 19)");
final File tempConfigFile = temp.newFile("config.toml");
try (BufferedWriter fileWriter = Files.newBufferedWriter(tempConfigFile.toPath(), UTF_8)) {
try (final BufferedWriter fileWriter =
Files.newBufferedWriter(tempConfigFile.toPath(), UTF_8)) {
fileWriter.write("an-invalid-syntax=======....");
fileWriter.flush();

@ -67,12 +67,13 @@ public class DockerQuickstartTest {
@BeforeClass
public static void runPantheonPrivateNetwork() throws IOException, InterruptedException {
ProcessBuilder processBuilder = new ProcessBuilder("quickstart/runPantheonPrivateNetwork.sh");
final ProcessBuilder processBuilder =
new ProcessBuilder("quickstart/runPantheonPrivateNetwork.sh");
processBuilder.directory(new File(PROJECT_ROOT)); // going up one level is the project root
processBuilder.inheritIO(); // redirect all output to logs
Process process = processBuilder.start();
final Process process = processBuilder.start();
int exitValue = process.waitFor();
final int exitValue = process.waitFor();
if (exitValue != 0) {
// check for errors, error messages and causes are redirected to logs already
@ -82,21 +83,22 @@ public class DockerQuickstartTest {
@Before
public void listQuickstartServices() throws IOException, InterruptedException {
ProcessBuilder processBuilder = new ProcessBuilder("quickstart/listQuickstartServices.sh");
final ProcessBuilder processBuilder =
new ProcessBuilder("quickstart/listQuickstartServices.sh");
processBuilder.directory(new File(PROJECT_ROOT)); // going up one level is the project root
// redirect only error output to logs as we want to be able to
// keep the standard output available for reading
processBuilder.redirectError(Redirect.INHERIT);
Process process = processBuilder.start();
final Process process = processBuilder.start();
int exitValue = process.waitFor();
final int exitValue = process.waitFor();
if (exitValue != 0) {
// check for errors, error messages and causes are redirected to logs already
throw new RuntimeException("execution of script failed!");
}
BufferedReader reader =
final BufferedReader reader =
new BufferedReader(new InputStreamReader(process.getInputStream(), UTF_8));
reader.lines().forEach(this::populateServicesAndEndpoints);
@ -125,25 +127,25 @@ public class DockerQuickstartTest {
// We check that the output of the script displays the right endpoints and services states
// each endpoint and service will be stored in a map for later use.
for (ServicesIdentifier servicesIdentifier : ServicesIdentifier.values()) {
Matcher regexMatcher = servicesIdentifier.pattern.matcher(line);
for (final ServicesIdentifier servicesIdentifier : ServicesIdentifier.values()) {
final Matcher regexMatcher = servicesIdentifier.pattern.matcher(line);
if (regexMatcher.find()) {
Service service = new Service();
final Service service = new Service();
service.name = regexMatcher.group(1);
service.state = regexMatcher.group(2).toLowerCase();
String portMappings[] = regexMatcher.group(3).split(",", -1);
for (String mapping : portMappings) {
ExposedPort port = new ExposedPort(mapping);
final String[] portMappings = regexMatcher.group(3).split(",", -1);
for (final String mapping : portMappings) {
final ExposedPort port = new ExposedPort(mapping);
service.exposedPorts.put(port.internalPort, port);
}
services.put(servicesIdentifier, service);
}
}
for (EndpointsIdentifier endpointsIdentifier : EndpointsIdentifier.values()) {
Matcher regexMatcher = endpointsIdentifier.pattern.matcher(line);
for (final EndpointsIdentifier endpointsIdentifier : EndpointsIdentifier.values()) {
final Matcher regexMatcher = endpointsIdentifier.pattern.matcher(line);
if (regexMatcher.find()) {
String endpoint = regexMatcher.group(1);
final String endpoint = regexMatcher.group(1);
endpoints.put(endpointsIdentifier, endpoint);
}
}
@ -157,13 +159,13 @@ public class DockerQuickstartTest {
@AfterClass
public static void removePantheonPrivateNetwork() throws IOException, InterruptedException {
ProcessBuilder processBuilder =
final ProcessBuilder processBuilder =
new ProcessBuilder("quickstart/removePantheonPrivateNetwork.sh");
processBuilder.inheritIO(); // redirect all output to logs
processBuilder.directory(new File(PROJECT_ROOT)); // going up one level is the project root
Process process = processBuilder.start();
final Process process = processBuilder.start();
int exitValue = process.waitFor();
final int exitValue = process.waitFor();
if (exitValue != 0) {
// check for errors, all output and then also error messages and causes are redirected to logs
throw new RuntimeException("execution of script failed!");
@ -202,7 +204,7 @@ public class DockerQuickstartTest {
public void rpcNodeShouldFindPeers() {
// Peers are those defined in docker-compose.yml and launched with scaling of 4 regular nodes
// which gives us 6 peers of the RPC node: bootnode, minernode and 4 regular nodes.
int expectecNumberOfPeers = 6;
final int expectecNumberOfPeers = 6;
Awaitility.await()
.ignoreExceptions()
@ -215,7 +217,7 @@ public class DockerQuickstartTest {
@Test
public void rpcNodeShouldReturnCorrectVersion() {
String expectedVersion = PantheonInfo.version();
final String expectedVersion = PantheonInfo.version();
Awaitility.await()
.ignoreExceptions()
.atMost(60, TimeUnit.SECONDS)
@ -228,7 +230,7 @@ public class DockerQuickstartTest {
@Test
public void mustMineSomeBlocks() {
// A bug occurred that failed mining after 2 blocks, so testing at least 10.
int expectedAtLeastBlockNumber = 10;
final int expectedAtLeastBlockNumber = 10;
Awaitility.await()
.ignoreExceptions()
.atMost(5, TimeUnit.MINUTES)
@ -240,7 +242,7 @@ public class DockerQuickstartTest {
@Test
public void webSocketRpcServiceMustConnect() {
RequestOptions options = new RequestOptions();
final RequestOptions options = new RequestOptions();
options.setPort(
services
.get(ServicesIdentifier.RPCNODE)
@ -271,14 +273,14 @@ public class DockerQuickstartTest {
// we have to check that the sed command well replaced the endpoint placeholder with the
// real dynamic endpoint. But as this is a react app, we have to search for the value in the JS
// as we can't find it in the HTML page because source code is rendered dynamically.
Request request =
final Request request =
new Request.Builder()
.get()
.url(endpoints.get(EndpointsIdentifier.EXPLORER) + "/static/js/bundle.js")
.build();
OkHttpClient httpClient = new OkHttpClient();
try (Response resp = httpClient.newCall(request).execute()) {
final OkHttpClient httpClient = new OkHttpClient();
try (final Response resp = httpClient.newCall(request).execute()) {
assertThat(resp.code()).isEqualTo(200);
assertThat(resp.body()).isNotNull();
assertThat(resp.body().string())
@ -333,15 +335,15 @@ public class DockerQuickstartTest {
ExposedPort(final String portDescription) {
if (portDescription.contains("->")) {
String[] ports = portDescription.split("->", 2);
final String[] ports = portDescription.split("->", 2);
String[] internalPortInfos = ports[1].split("/", 2);
final String[] internalPortInfos = ports[1].split("/", 2);
internalPort = Integer.valueOf(internalPortInfos[0]);
String[] externalPortInfos = ports[0].split(":", 2);
final String[] externalPortInfos = ports[0].split(":", 2);
externalPort = Integer.valueOf(externalPortInfos[1]);
} else {
Matcher regexMatcher = pattern.matcher(portDescription);
final Matcher regexMatcher = pattern.matcher(portDescription);
internalPort = regexMatcher.find() ? Integer.valueOf(regexMatcher.group(0)) : null;
externalPort = null;
}

@ -159,8 +159,8 @@ public abstract class UInt256Bytes {
return;
}
Bytes32 a;
Bytes32 b;
final Bytes32 a;
final Bytes32 b;
if (sign > 0) {
a = v1;
b = v2;

Loading…
Cancel
Save