From 45e0037321e6e41cfcbeda799c73bbea7c4815c5 Mon Sep 17 00:00:00 2001 From: Adrian Sutton Date: Wed, 24 Oct 2018 08:04:23 +1000 Subject: [PATCH] [MINOR] Add missing finals. (#128) --- .../acceptance/dsl/node/PantheonNode.java | 2 +- .../dsl/node/PantheonNodeRunner.java | 2 +- .../dsl/node/ThreadPantheonNodeRunner.java | 2 +- .../jsonrpc/EthGetWorkAcceptanceTest.java | 4 +- .../consensus/clique/CliqueExtraData.java | 2 +- .../blockcreation/CliqueBlockScheduler.java | 6 +- .../blockcreation/CliqueMinerExecutor.java | 8 +-- .../jsonrpc/methods/CliqueProposals.java | 2 +- .../consensus/clique/CliqueExtraDataTest.java | 2 +- .../CliqueBlockSchedulerTest.java | 24 +++---- .../CliqueMinerExecutorTest.java | 4 +- .../jsonrpc/methods/CliqueProposalsTest.java | 4 +- .../pantheon/consensus/ibft/IbftVoteType.java | 2 +- .../jsonrpc/IbftJsonRpcMethodsFactory.java | 2 +- .../methods/IbftProposeValidatorVote.java | 4 +- .../ibft/network/IbftNetworkPeers.java | 4 +- .../consensus/ibft/BlockTimerTest.java | 26 +++++--- .../consensus/ibft/Ibft2ExtraDataTest.java | 20 +++--- .../consensus/ibft/IbftChainObserverTest.java | 3 +- .../methods/IbftDiscardValidatorVoteTest.java | 4 +- .../methods/IbftProposeValidatorVoteTest.java | 8 +-- .../ibft/network/IbftNetworkPeersTest.java | 16 ++--- .../blockcreation/ProposerSelector.java | 2 +- .../tech/pegasys/pantheon/crypto/Hash.java | 4 +- .../crypto/PersonalisationString.java | 2 +- .../ethereum/blockcreation/BlockMiner.java | 4 +- .../ethereum/chain/GenesisConfig.java | 2 +- .../ethereum/core/AbstractWorldUpdater.java | 2 +- .../pantheon/ethereum/core/Transaction.java | 4 +- .../ethereum/mainnet/EthHashBlockCreator.java | 2 +- .../ethereum/util/BlockchainUtil.java | 11 ++-- .../DefaultBlockSchedulerTest.java | 36 +++++------ .../ethereum/db/GenesisBlockMismatchTest.java | 16 ++--- .../ProofOfWorkValidationRuleTest.java | 16 ++--- .../util/BlockchainUtilParameterizedTest.java | 4 +- .../ethereum/eth/manager/AbstractEthTask.java | 2 +- .../eth/manager/AbstractPeerTask.java | 2 +- .../ethereum/eth/manager/EthServer.java | 2 +- .../eth/sync/BlockPropagationManager.java | 2 +- .../eth/sync/SynchronizerConfiguration.java | 2 +- .../tasks/DetermineCommonAncestorTask.java | 6 +- .../eth/manager/EthProtocolManagerTest.java | 41 ++++++------ .../DetermineCommonAncestorTaskTest.java | 32 +++++----- .../eth/transactions/TestNodeList.java | 2 +- .../internal/filter/FilterManager.java | 9 +-- .../jsonrpc/internal/methods/EthCoinbase.java | 2 +- .../jsonrpc/internal/methods/EthGasPrice.java | 2 +- .../jsonrpc/internal/methods/EthGetWork.java | 8 +-- .../methods/EthSendRawTransaction.java | 4 +- .../methods/miner/MinerSetCoinbase.java | 2 +- .../websocket/WebSocketRequestHandler.java | 4 +- .../jsonrpc/AdminJsonRpcHttpServiceTest.java | 2 +- .../jsonrpc/EthJsonRpcHttpBySpecTest.java | 2 +- .../filter/FilterManagerLogFilterTest.java | 4 +- .../internal/filter/FilterManagerTest.java | 4 +- .../internal/filter/FilterRepositoryTest.java | 56 ++++++++--------- .../jsonrpc/internal/filter/FilterTest.java | 6 +- .../filter/FilterTimeoutMonitorTest.java | 4 +- .../internal/methods/EthGetWorkTest.java | 6 +- .../subscription/SubscriptionManagerTest.java | 18 +++--- .../p2p/discovery/internal/Packet.java | 2 +- .../p2p/discovery/internal/PeerTable.java | 2 +- .../ecies/ECIESEncryptionEngine.java | 16 ++--- .../ethereum/p2p/NettyP2PNetworkTest.java | 4 +- .../p2p/NetworkingServiceLifecycleTest.java | 22 +++---- .../discovery/AbstractPeerDiscoveryTest.java | 4 +- .../discovery/PeerDiscoveryObserversTest.java | 2 +- .../ethereum/rlp/AbstractRLPOutput.java | 2 +- .../pegasys/pantheon/ethereum/rlp/RLP.java | 4 +- .../ethereum/trie/CompactEncoding.java | 2 +- .../ethereum/trie/StoredNodeFactory.java | 8 +-- .../java/tech/pegasys/pantheon/Runner.java | 2 +- .../tech/pegasys/pantheon/RunnerBuilder.java | 2 +- .../cli/ConfigOptionSearchAndRunHandler.java | 2 +- .../pantheon/cli/EthNetworkConfig.java | 4 +- .../cli/ExportPublicKeySubCommand.java | 2 +- .../pegasys/pantheon/cli/PantheonCommand.java | 6 +- .../cli/TomlConfigFileDefaultProvider.java | 2 +- .../custom/CorsAllowedOriginsProperty.java | 2 +- .../pantheon/util/BlockchainImporter.java | 6 +- .../pantheon/cli/PantheonCommandTest.java | 6 +- .../TomlConfigFileDefaultProviderTest.java | 8 ++- .../quickstart/DockerQuickstartTest.java | 62 ++++++++++--------- .../pantheon/util/uint/UInt256Bytes.java | 4 +- 84 files changed, 337 insertions(+), 319 deletions(-) diff --git a/acceptance-tests/src/test/java/tech/pegasys/pantheon/tests/acceptance/dsl/node/PantheonNode.java b/acceptance-tests/src/test/java/tech/pegasys/pantheon/tests/acceptance/dsl/node/PantheonNode.java index 8aa7a484ed..10e3955dd0 100644 --- a/acceptance-tests/src/test/java/tech/pegasys/pantheon/tests/acceptance/dsl/node/PantheonNode.java +++ b/acceptance-tests/src/test/java/tech/pegasys/pantheon/tests/acceptance/dsl/node/PantheonNode.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) { diff --git a/acceptance-tests/src/test/java/tech/pegasys/pantheon/tests/acceptance/dsl/node/PantheonNodeRunner.java b/acceptance-tests/src/test/java/tech/pegasys/pantheon/tests/acceptance/dsl/node/PantheonNodeRunner.java index 48948e7ec5..75e12cb6f9 100644 --- a/acceptance-tests/src/test/java/tech/pegasys/pantheon/tests/acceptance/dsl/node/PantheonNodeRunner.java +++ b/acceptance-tests/src/test/java/tech/pegasys/pantheon/tests/acceptance/dsl/node/PantheonNodeRunner.java @@ -42,7 +42,7 @@ public interface PantheonNodeRunner { .until( () -> { if (file.exists()) { - try (Stream s = Files.lines(file.toPath())) { + try (final Stream s = Files.lines(file.toPath())) { return s.count() > 0; } } else { diff --git a/acceptance-tests/src/test/java/tech/pegasys/pantheon/tests/acceptance/dsl/node/ThreadPantheonNodeRunner.java b/acceptance-tests/src/test/java/tech/pegasys/pantheon/tests/acceptance/dsl/node/ThreadPantheonNodeRunner.java index 04e49191f6..f1b79285f7 100644 --- a/acceptance-tests/src/test/java/tech/pegasys/pantheon/tests/acceptance/dsl/node/ThreadPantheonNodeRunner.java +++ b/acceptance-tests/src/test/java/tech/pegasys/pantheon/tests/acceptance/dsl/node/ThreadPantheonNodeRunner.java @@ -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( diff --git a/acceptance-tests/src/test/java/tech/pegasys/pantheon/tests/acceptance/jsonrpc/EthGetWorkAcceptanceTest.java b/acceptance-tests/src/test/java/tech/pegasys/pantheon/tests/acceptance/jsonrpc/EthGetWorkAcceptanceTest.java index c2b99bf420..58db8fabd1 100644 --- a/acceptance-tests/src/test/java/tech/pegasys/pantheon/tests/acceptance/jsonrpc/EthGetWorkAcceptanceTest.java +++ b/acceptance-tests/src/test/java/tech/pegasys/pantheon/tests/acceptance/jsonrpc/EthGetWorkAcceptanceTest.java @@ -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"); } diff --git a/consensus/clique/src/main/java/tech/pegasys/pantheon/consensus/clique/CliqueExtraData.java b/consensus/clique/src/main/java/tech/pegasys/pantheon/consensus/clique/CliqueExtraData.java index dcd59b6af9..544c38fd13 100644 --- a/consensus/clique/src/main/java/tech/pegasys/pantheon/consensus/clique/CliqueExtraData.java +++ b/consensus/clique/src/main/java/tech/pegasys/pantheon/consensus/clique/CliqueExtraData.java @@ -120,7 +120,7 @@ public class CliqueExtraData { private static List
convertPrivKeysToAddresses(final List privKeys) { final List
validators = Lists.newArrayList(); - for (PrivateKey privKey : privKeys) { + for (final PrivateKey privKey : privKeys) { final PublicKey pubKey = PublicKey.create(privKey); validators.add(Util.publicKeyToAddress(pubKey)); } diff --git a/consensus/clique/src/main/java/tech/pegasys/pantheon/consensus/clique/blockcreation/CliqueBlockScheduler.java b/consensus/clique/src/main/java/tech/pegasys/pantheon/consensus/clique/blockcreation/CliqueBlockScheduler.java index 40242748e2..9c0c68e707 100644 --- a/consensus/clique/src/main/java/tech/pegasys/pantheon/consensus/clique/blockcreation/CliqueBlockScheduler.java +++ b/consensus/clique/src/main/java/tech/pegasys/pantheon/consensus/clique/blockcreation/CliqueBlockScheduler.java @@ -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); } } diff --git a/consensus/clique/src/main/java/tech/pegasys/pantheon/consensus/clique/blockcreation/CliqueMinerExecutor.java b/consensus/clique/src/main/java/tech/pegasys/pantheon/consensus/clique/blockcreation/CliqueMinerExecutor.java index f7099fad1a..4b1df0b0e0 100644 --- a/consensus/clique/src/main/java/tech/pegasys/pantheon/consensus/clique/blockcreation/CliqueMinerExecutor.java +++ b/consensus/clique/src/main/java/tech/pegasys/pantheon/consensus/clique/blockcreation/CliqueMinerExecutor.java @@ -68,7 +68,7 @@ public class CliqueMinerExecutor extends AbstractMinerExecutor 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 validators = Lists.newArrayList(); + final List
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 proposals = + final Map proposals = voteProposer .getProposals() .entrySet() diff --git a/consensus/clique/src/test/java/tech/pegasys/pantheon/consensus/clique/CliqueExtraDataTest.java b/consensus/clique/src/test/java/tech/pegasys/pantheon/consensus/clique/CliqueExtraDataTest.java index 8d17892b8a..2f4c13f135 100644 --- a/consensus/clique/src/test/java/tech/pegasys/pantheon/consensus/clique/CliqueExtraDataTest.java +++ b/consensus/clique/src/test/java/tech/pegasys/pantheon/consensus/clique/CliqueExtraDataTest.java @@ -96,7 +96,7 @@ public class CliqueExtraDataTest { @Test public void privKeysToExtraDataString() { - List nodeKeys = Lists.newArrayList(); + final List nodeKeys = Lists.newArrayList(); for (int i = 0; i < 4; i++) { nodeKeys.add(KeyPair.generate()); } diff --git a/consensus/clique/src/test/java/tech/pegasys/pantheon/consensus/clique/blockcreation/CliqueBlockSchedulerTest.java b/consensus/clique/src/test/java/tech/pegasys/pantheon/consensus/clique/blockcreation/CliqueBlockSchedulerTest.java index 2d1b7e8aa9..e730d49343 100644 --- a/consensus/clique/src/test/java/tech/pegasys/pantheon/consensus/clique/blockcreation/CliqueBlockSchedulerTest.java +++ b/consensus/clique/src/test/java/tech/pegasys/pantheon/consensus/clique/blockcreation/CliqueBlockSchedulerTest.java @@ -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); diff --git a/consensus/clique/src/test/java/tech/pegasys/pantheon/consensus/clique/blockcreation/CliqueMinerExecutorTest.java b/consensus/clique/src/test/java/tech/pegasys/pantheon/consensus/clique/blockcreation/CliqueMinerExecutorTest.java index eb20e660ea..3c4ab24673 100644 --- a/consensus/clique/src/test/java/tech/pegasys/pantheon/consensus/clique/blockcreation/CliqueMinerExecutorTest.java +++ b/consensus/clique/src/test/java/tech/pegasys/pantheon/consensus/clique/blockcreation/CliqueMinerExecutorTest.java @@ -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; diff --git a/consensus/clique/src/test/java/tech/pegasys/pantheon/consensus/clique/jsonrpc/methods/CliqueProposalsTest.java b/consensus/clique/src/test/java/tech/pegasys/pantheon/consensus/clique/jsonrpc/methods/CliqueProposalsTest.java index 96215e6f27..8c6c93108c 100644 --- a/consensus/clique/src/test/java/tech/pegasys/pantheon/consensus/clique/jsonrpc/methods/CliqueProposalsTest.java +++ b/consensus/clique/src/test/java/tech/pegasys/pantheon/consensus/clique/jsonrpc/methods/CliqueProposalsTest.java @@ -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); } diff --git a/consensus/ibft/src/main/java/tech/pegasys/pantheon/consensus/ibft/IbftVoteType.java b/consensus/ibft/src/main/java/tech/pegasys/pantheon/consensus/ibft/IbftVoteType.java index 89a0f6985b..13e4b75e13 100644 --- a/consensus/ibft/src/main/java/tech/pegasys/pantheon/consensus/ibft/IbftVoteType.java +++ b/consensus/ibft/src/main/java/tech/pegasys/pantheon/consensus/ibft/IbftVoteType.java @@ -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; diff --git a/consensus/ibft/src/main/java/tech/pegasys/pantheon/consensus/ibft/jsonrpc/IbftJsonRpcMethodsFactory.java b/consensus/ibft/src/main/java/tech/pegasys/pantheon/consensus/ibft/jsonrpc/IbftJsonRpcMethodsFactory.java index bc155765ed..14bec82cbf 100644 --- a/consensus/ibft/src/main/java/tech/pegasys/pantheon/consensus/ibft/jsonrpc/IbftJsonRpcMethodsFactory.java +++ b/consensus/ibft/src/main/java/tech/pegasys/pantheon/consensus/ibft/jsonrpc/IbftJsonRpcMethodsFactory.java @@ -48,7 +48,7 @@ public class IbftJsonRpcMethodsFactory { private void addMethods( final Map methods, final JsonRpcMethod... rpcMethods) { - for (JsonRpcMethod rpcMethod : rpcMethods) { + for (final JsonRpcMethod rpcMethod : rpcMethods) { methods.put(rpcMethod.getName(), rpcMethod); } } diff --git a/consensus/ibft/src/main/java/tech/pegasys/pantheon/consensus/ibft/jsonrpc/methods/IbftProposeValidatorVote.java b/consensus/ibft/src/main/java/tech/pegasys/pantheon/consensus/ibft/jsonrpc/methods/IbftProposeValidatorVote.java index be1032d21b..9217e2e21e 100644 --- a/consensus/ibft/src/main/java/tech/pegasys/pantheon/consensus/ibft/jsonrpc/methods/IbftProposeValidatorVote.java +++ b/consensus/ibft/src/main/java/tech/pegasys/pantheon/consensus/ibft/jsonrpc/methods/IbftProposeValidatorVote.java @@ -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); diff --git a/consensus/ibft/src/main/java/tech/pegasys/pantheon/consensus/ibft/network/IbftNetworkPeers.java b/consensus/ibft/src/main/java/tech/pegasys/pantheon/consensus/ibft/network/IbftNetworkPeers.java index 82913d3b99..c3c064d598 100644 --- a/consensus/ibft/src/main/java/tech/pegasys/pantheon/consensus/ibft/network/IbftNetworkPeers.java +++ b/consensus/ibft/src/main/java/tech/pegasys/pantheon/consensus/ibft/network/IbftNetworkPeers.java @@ -53,7 +53,7 @@ public class IbftNetworkPeers { } public void multicastToValidators(final MessageData message) { - Collection
validators = validatorProvider.getCurrentValidators(); + final Collection
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."); } }); diff --git a/consensus/ibft/src/test/java/tech/pegasys/pantheon/consensus/ibft/BlockTimerTest.java b/consensus/ibft/src/test/java/tech/pegasys/pantheon/consensus/ibft/BlockTimerTest.java index c164f099f5..3bc68167a4 100644 --- a/consensus/ibft/src/test/java/tech/pegasys/pantheon/consensus/ibft/BlockTimerTest.java +++ b/consensus/ibft/src/test/java/tech/pegasys/pantheon/consensus/ibft/BlockTimerTest.java @@ -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 ibftEventCaptor = ArgumentCaptor.forClass(IbftEvent.class); + final ArgumentCaptor 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 ibftEventCaptor = ArgumentCaptor.forClass(IbftEvent.class); + final ArgumentCaptor 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 ibftEventCaptor = ArgumentCaptor.forClass(IbftEvent.class); + final ArgumentCaptor 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); diff --git a/consensus/ibft/src/test/java/tech/pegasys/pantheon/consensus/ibft/Ibft2ExtraDataTest.java b/consensus/ibft/src/test/java/tech/pegasys/pantheon/consensus/ibft/Ibft2ExtraDataTest.java index 4aa801039c..4fecb8cf93 100644 --- a/consensus/ibft/src/test/java/tech/pegasys/pantheon/consensus/ibft/Ibft2ExtraDataTest.java +++ b/consensus/ibft/src/test/java/tech/pegasys/pantheon/consensus/ibft/Ibft2ExtraDataTest.java @@ -175,7 +175,7 @@ public class Ibft2ExtraDataTest { @Test public void emptyVoteAndListIsEncodedCorrectly() { final List
validators = Lists.newArrayList(); - Optional vote = Optional.empty(); + final Optional vote = Optional.empty(); final int round = 0x00FEDCBA; final List 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); } diff --git a/consensus/ibft/src/test/java/tech/pegasys/pantheon/consensus/ibft/IbftChainObserverTest.java b/consensus/ibft/src/test/java/tech/pegasys/pantheon/consensus/ibft/IbftChainObserverTest.java index 52052e11c4..edccd14feb 100644 --- a/consensus/ibft/src/test/java/tech/pegasys/pantheon/consensus/ibft/IbftChainObserverTest.java +++ b/consensus/ibft/src/test/java/tech/pegasys/pantheon/consensus/ibft/IbftChainObserverTest.java @@ -54,7 +54,8 @@ public class IbftChainObserverTest { ibftChainObserver.onBlockAdded(mockBlockAddedEvent, mockBlockchain); - ArgumentCaptor ibftEventArgumentCaptor = ArgumentCaptor.forClass(IbftEvent.class); + final ArgumentCaptor ibftEventArgumentCaptor = + ArgumentCaptor.forClass(IbftEvent.class); verify(mockQueue).add(ibftEventArgumentCaptor.capture()); assertThat(ibftEventArgumentCaptor.getValue() instanceof NewChainHead).isTrue(); diff --git a/consensus/ibft/src/test/java/tech/pegasys/pantheon/consensus/ibft/jsonrpc/methods/IbftDiscardValidatorVoteTest.java b/consensus/ibft/src/test/java/tech/pegasys/pantheon/consensus/ibft/jsonrpc/methods/IbftDiscardValidatorVoteTest.java index 8999d9d7ff..9fde1f3e84 100644 --- a/consensus/ibft/src/test/java/tech/pegasys/pantheon/consensus/ibft/jsonrpc/methods/IbftDiscardValidatorVoteTest.java +++ b/consensus/ibft/src/test/java/tech/pegasys/pantheon/consensus/ibft/jsonrpc/methods/IbftDiscardValidatorVoteTest.java @@ -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); diff --git a/consensus/ibft/src/test/java/tech/pegasys/pantheon/consensus/ibft/jsonrpc/methods/IbftProposeValidatorVoteTest.java b/consensus/ibft/src/test/java/tech/pegasys/pantheon/consensus/ibft/jsonrpc/methods/IbftProposeValidatorVoteTest.java index 2d63918466..59f86bc3cc 100644 --- a/consensus/ibft/src/test/java/tech/pegasys/pantheon/consensus/ibft/jsonrpc/methods/IbftProposeValidatorVoteTest.java +++ b/consensus/ibft/src/test/java/tech/pegasys/pantheon/consensus/ibft/jsonrpc/methods/IbftProposeValidatorVoteTest.java @@ -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); diff --git a/consensus/ibft/src/test/java/tech/pegasys/pantheon/consensus/ibft/network/IbftNetworkPeersTest.java b/consensus/ibft/src/test/java/tech/pegasys/pantheon/consensus/ibft/network/IbftNetworkPeersTest.java index 3d94a9a865..1a90a07038 100644 --- a/consensus/ibft/src/test/java/tech/pegasys/pantheon/consensus/ibft/network/IbftNetworkPeersTest.java +++ b/consensus/ibft/src/test/java/tech/pegasys/pantheon/consensus/ibft/network/IbftNetworkPeersTest.java @@ -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()); diff --git a/consensus/ibftlegacy/src/main/java/tech/pegasys/pantheon/consensus/ibftlegacy/blockcreation/ProposerSelector.java b/consensus/ibftlegacy/src/main/java/tech/pegasys/pantheon/consensus/ibftlegacy/blockcreation/ProposerSelector.java index 506110323c..75d3874bb9 100644 --- a/consensus/ibftlegacy/src/main/java/tech/pegasys/pantheon/consensus/ibftlegacy/blockcreation/ProposerSelector.java +++ b/consensus/ibftlegacy/src/main/java/tech/pegasys/pantheon/consensus/ibftlegacy/blockcreation/ProposerSelector.java @@ -96,7 +96,7 @@ public class ProposerSelector { final Address prevBlockProposer, final ConsensusRoundIdentifier roundIdentifier) { final NavigableSet
validatorSet = new TreeSet<>(validators.getCurrentValidators()); final SortedSet
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. diff --git a/crypto/src/main/java/tech/pegasys/pantheon/crypto/Hash.java b/crypto/src/main/java/tech/pegasys/pantheon/crypto/Hash.java index de3cccbc1d..326e5427f4 100644 --- a/crypto/src/main/java/tech/pegasys/pantheon/crypto/Hash.java +++ b/crypto/src/main/java/tech/pegasys/pantheon/crypto/Hash.java @@ -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); diff --git a/crypto/src/main/java/tech/pegasys/pantheon/crypto/PersonalisationString.java b/crypto/src/main/java/tech/pegasys/pantheon/crypto/PersonalisationString.java index e4288c730b..b663dda8a0 100644 --- a/crypto/src/main/java/tech/pegasys/pantheon/crypto/PersonalisationString.java +++ b/crypto/src/main/java/tech/pegasys/pantheon/crypto/PersonalisationString.java @@ -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", diff --git a/ethereum/core/src/main/java/tech/pegasys/pantheon/ethereum/blockcreation/BlockMiner.java b/ethereum/core/src/main/java/tech/pegasys/pantheon/ethereum/blockcreation/BlockMiner.java index d3c0ff6214..5a64a66ca0 100644 --- a/ethereum/core/src/main/java/tech/pegasys/pantheon/ethereum/blockcreation/BlockMiner.java +++ b/ethereum/core/src/main/java/tech/pegasys/pantheon/ethereum/blockcreation/BlockMiner.java @@ -84,10 +84,10 @@ public class BlockMiner> 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()); diff --git a/ethereum/core/src/main/java/tech/pegasys/pantheon/ethereum/chain/GenesisConfig.java b/ethereum/core/src/main/java/tech/pegasys/pantheon/ethereum/chain/GenesisConfig.java index 7f999f721a..c7230de9dc 100644 --- a/ethereum/core/src/main/java/tech/pegasys/pantheon/ethereum/chain/GenesisConfig.java +++ b/ethereum/core/src/main/java/tech/pegasys/pantheon/ethereum/chain/GenesisConfig.java @@ -312,7 +312,7 @@ public final class GenesisConfig { } private Wei parseBalance(final String balance) { - BigInteger val; + final BigInteger val; if (balance.startsWith("0x")) { val = new BigInteger(1, BytesValue.fromHexStringLenient(balance).extractArray()); } else { diff --git a/ethereum/core/src/main/java/tech/pegasys/pantheon/ethereum/core/AbstractWorldUpdater.java b/ethereum/core/src/main/java/tech/pegasys/pantheon/ethereum/core/AbstractWorldUpdater.java index f3b6e40ccf..cdcd11f80e 100644 --- a/ethereum/core/src/main/java/tech/pegasys/pantheon/ethereum/core/AbstractWorldUpdater.java +++ b/ethereum/core/src/main/java/tech/pegasys/pantheon/ethereum/core/AbstractWorldUpdater.java @@ -308,7 +308,7 @@ public abstract class AbstractWorldUpdater storageEntriesFrom( final Bytes32 startKeyHash, final int limit) { - NavigableMap entries; + final NavigableMap entries; if (account != null) { entries = account.storageEntriesFrom(startKeyHash, limit); } else { diff --git a/ethereum/core/src/main/java/tech/pegasys/pantheon/ethereum/core/Transaction.java b/ethereum/core/src/main/java/tech/pegasys/pantheon/ethereum/core/Transaction.java index 24caf1ad82..8b752ade5c 100644 --- a/ethereum/core/src/main/java/tech/pegasys/pantheon/ethereum/core/Transaction.java +++ b/ethereum/core/src/main/java/tech/pegasys/pantheon/ethereum/core/Transaction.java @@ -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 { diff --git a/ethereum/core/src/main/java/tech/pegasys/pantheon/ethereum/mainnet/EthHashBlockCreator.java b/ethereum/core/src/main/java/tech/pegasys/pantheon/ethereum/mainnet/EthHashBlockCreator.java index 5397293d9d..ad60de8d27 100644 --- a/ethereum/core/src/main/java/tech/pegasys/pantheon/ethereum/mainnet/EthHashBlockCreator.java +++ b/ethereum/core/src/main/java/tech/pegasys/pantheon/ethereum/mainnet/EthHashBlockCreator.java @@ -61,7 +61,7 @@ public class EthHashBlockCreator extends AbstractBlockCreator { @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) { diff --git a/ethereum/core/src/main/java/tech/pegasys/pantheon/ethereum/util/BlockchainUtil.java b/ethereum/core/src/main/java/tech/pegasys/pantheon/ethereum/util/BlockchainUtil.java index 14ffa6e48d..b7fd8584b8 100644 --- a/ethereum/core/src/main/java/tech/pegasys/pantheon/ethereum/util/BlockchainUtil.java +++ b/ethereum/core/src/main/java/tech/pegasys/pantheon/ethereum/util/BlockchainUtil.java @@ -39,11 +39,12 @@ public class BlockchainUtil { final Blockchain blockchain, final List headers, final boolean ascendingHeaderOrder) { - int offset = ascendingHeaderOrder ? -1 : 0; - Comparator comparator = knownBlockComparator(blockchain, ascendingHeaderOrder); + final int offset = ascendingHeaderOrder ? -1 : 0; + final Comparator 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 knownBlockComparator( final Blockchain blockchain, final boolean ascendingHeaderOrder) { - Comparator comparator = + final Comparator comparator = (final BlockHeader element0, final BlockHeader element1) -> { if (element0 == null) { return blockchain.contains(element1.getHash()) ? -1 : 1; diff --git a/ethereum/core/src/test/java/tech/pegasys/pantheon/ethereum/blockcreation/DefaultBlockSchedulerTest.java b/ethereum/core/src/test/java/tech/pegasys/pantheon/ethereum/blockcreation/DefaultBlockSchedulerTest.java index f6ff665a6c..07bbf3b249 100644 --- a/ethereum/core/src/test/java/tech/pegasys/pantheon/ethereum/blockcreation/DefaultBlockSchedulerTest.java +++ b/ethereum/core/src/test/java/tech/pegasys/pantheon/ethereum/blockcreation/DefaultBlockSchedulerTest.java @@ -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); } diff --git a/ethereum/core/src/test/java/tech/pegasys/pantheon/ethereum/db/GenesisBlockMismatchTest.java b/ethereum/core/src/test/java/tech/pegasys/pantheon/ethereum/db/GenesisBlockMismatchTest.java index b1d81eaff4..b36ca47889 100644 --- a/ethereum/core/src/test/java/tech/pegasys/pantheon/ethereum/db/GenesisBlockMismatchTest.java +++ b/ethereum/core/src/test/java/tech/pegasys/pantheon/ethereum/db/GenesisBlockMismatchTest.java @@ -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)) diff --git a/ethereum/core/src/test/java/tech/pegasys/pantheon/ethereum/mainnet/headervalidationrules/ProofOfWorkValidationRuleTest.java b/ethereum/core/src/test/java/tech/pegasys/pantheon/ethereum/mainnet/headervalidationrules/ProofOfWorkValidationRuleTest.java index 88daee1dc5..768281caa1 100644 --- a/ethereum/core/src/test/java/tech/pegasys/pantheon/ethereum/mainnet/headervalidationrules/ProofOfWorkValidationRuleTest.java +++ b/ethereum/core/src/test/java/tech/pegasys/pantheon/ethereum/mainnet/headervalidationrules/ProofOfWorkValidationRuleTest.java @@ -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 protocolSchedule = MainnetProtocolSchedule.create(); + final ProtocolSchedule protocolSchedule = MainnetProtocolSchedule.create(); return ScheduleBasedBlockHashFunction.create(protocolSchedule); } } diff --git a/ethereum/core/src/test/java/tech/pegasys/pantheon/ethereum/util/BlockchainUtilParameterizedTest.java b/ethereum/core/src/test/java/tech/pegasys/pantheon/ethereum/util/BlockchainUtilParameterizedTest.java index 667101a70a..e5939a5df1 100644 --- a/ethereum/core/src/test/java/tech/pegasys/pantheon/ethereum/util/BlockchainUtilParameterizedTest.java +++ b/ethereum/core/src/test/java/tech/pegasys/pantheon/ethereum/util/BlockchainUtilParameterizedTest.java @@ -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())); diff --git a/ethereum/eth/src/main/java/tech/pegasys/pantheon/ethereum/eth/manager/AbstractEthTask.java b/ethereum/eth/src/main/java/tech/pegasys/pantheon/ethereum/eth/manager/AbstractEthTask.java index 07b445e26b..9f9564840a 100644 --- a/ethereum/eth/src/main/java/tech/pegasys/pantheon/ethereum/eth/manager/AbstractEthTask.java +++ b/ethereum/eth/src/main/java/tech/pegasys/pantheon/ethereum/eth/manager/AbstractEthTask.java @@ -109,7 +109,7 @@ public abstract class AbstractEthTask implements EthTask { } try { return result.get().get(); - } catch (InterruptedException | ExecutionException e) { + } catch (final InterruptedException | ExecutionException e) { return null; } } diff --git a/ethereum/eth/src/main/java/tech/pegasys/pantheon/ethereum/eth/manager/AbstractPeerTask.java b/ethereum/eth/src/main/java/tech/pegasys/pantheon/ethereum/eth/manager/AbstractPeerTask.java index dcd24d8176..00525ae56e 100644 --- a/ethereum/eth/src/main/java/tech/pegasys/pantheon/ethereum/eth/manager/AbstractPeerTask.java +++ b/ethereum/eth/src/main/java/tech/pegasys/pantheon/ethereum/eth/manager/AbstractPeerTask.java @@ -29,7 +29,7 @@ public abstract class AbstractPeerTask extends AbstractEthTask { // Check to see if any of our pending blocks are now ready for import final Block newBlock = blockAddedEvent.getBlock(); - List readyForImport; + final List readyForImport; synchronized (pendingBlocks) { // Remove block from pendingBlocks list pendingBlocks.deregisterPendingBlock(newBlock); diff --git a/ethereum/eth/src/main/java/tech/pegasys/pantheon/ethereum/eth/sync/SynchronizerConfiguration.java b/ethereum/eth/src/main/java/tech/pegasys/pantheon/ethereum/eth/sync/SynchronizerConfiguration.java index 2f1733ef38..59f4b879ec 100644 --- a/ethereum/eth/src/main/java/tech/pegasys/pantheon/ethereum/eth/sync/SynchronizerConfiguration.java +++ b/ethereum/eth/src/main/java/tech/pegasys/pantheon/ethereum/eth/sync/SynchronizerConfiguration.java @@ -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; diff --git a/ethereum/eth/src/main/java/tech/pegasys/pantheon/ethereum/eth/sync/tasks/DetermineCommonAncestorTask.java b/ethereum/eth/src/main/java/tech/pegasys/pantheon/ethereum/eth/sync/tasks/DetermineCommonAncestorTask.java index 2d052a0505..74e91436df 100644 --- a/ethereum/eth/src/main/java/tech/pegasys/pantheon/ethereum/eth/sync/tasks/DetermineCommonAncestorTask.java +++ b/ethereum/eth/src/main/java/tech/pegasys/pantheon/ethereum/eth/sync/tasks/DetermineCommonAncestorTask.java @@ -128,9 +128,9 @@ public class DetermineCommonAncestorTask extends AbstractEthTask private CompletableFuture processHeaders( final AbstractPeerTask.PeerTaskResult> headersResult) { initialQuery = false; - List headers = headersResult.getResult(); + final List 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 extends AbstractEthTask 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) { diff --git a/ethereum/eth/src/test/java/tech/pegasys/pantheon/ethereum/eth/manager/EthProtocolManagerTest.java b/ethereum/eth/src/test/java/tech/pegasys/pantheon/ethereum/eth/manager/EthProtocolManagerTest.java index 2250982593..165f3f53c3 100644 --- a/ethereum/eth/src/test/java/tech/pegasys/pantheon/ethereum/eth/manager/EthProtocolManagerTest.java +++ b/ethereum/eth/src/test/java/tech/pegasys/pantheon/ethereum/eth/manager/EthProtocolManagerTest.java @@ -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 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 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 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 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 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 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 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 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 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 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 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 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 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 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; diff --git a/ethereum/eth/src/test/java/tech/pegasys/pantheon/ethereum/eth/sync/tasks/DetermineCommonAncestorTaskTest.java b/ethereum/eth/src/test/java/tech/pegasys/pantheon/ethereum/eth/sync/tasks/DetermineCommonAncestorTaskTest.java index 18c86b6697..61892b8c5f 100644 --- a/ethereum/eth/src/test/java/tech/pegasys/pantheon/ethereum/eth/sync/tasks/DetermineCommonAncestorTaskTest.java +++ b/ethereum/eth/src/test/java/tech/pegasys/pantheon/ethereum/eth/sync/tasks/DetermineCommonAncestorTaskTest.java @@ -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 receipts = blockDataGenerator.receipts(commonBlock); + final List 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 receipts00 = blockDataGenerator.receipts(block00); + final Block block00 = blockDataGenerator.block(options00); + final List 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 receipts01 = blockDataGenerator.receipts(block01); + final Block block01 = blockDataGenerator.block(options01); + final List 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 task = + final DetermineCommonAncestorTask task = DetermineCommonAncestorTask.create( protocolSchedule, protocolContext, ethContext, respondingEthPeer.getEthPeer(), defaultHeaderRequestSize); - DetermineCommonAncestorTask spy = spy(task); + final DetermineCommonAncestorTask spy = spy(task); // Execute task - CompletableFuture future = spy.run(); + final CompletableFuture future = spy.run(); respondingEthPeer.respondWhile(responder, () -> !future.isDone()); - AtomicReference result = new AtomicReference<>(); + final AtomicReference result = new AtomicReference<>(); future.whenComplete( (response, error) -> { result.set(response); diff --git a/ethereum/eth/src/test/java/tech/pegasys/pantheon/ethereum/eth/transactions/TestNodeList.java b/ethereum/eth/src/test/java/tech/pegasys/pantheon/ethereum/eth/transactions/TestNodeList.java index 2872b8b661..86a928d3ef 100644 --- a/ethereum/eth/src/test/java/tech/pegasys/pantheon/ethereum/eth/transactions/TestNodeList.java +++ b/ethereum/eth/src/test/java/tech/pegasys/pantheon/ethereum/eth/transactions/TestNodeList.java @@ -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.", diff --git a/ethereum/jsonrpc/src/main/java/tech/pegasys/pantheon/ethereum/jsonrpc/internal/filter/FilterManager.java b/ethereum/jsonrpc/src/main/java/tech/pegasys/pantheon/ethereum/jsonrpc/internal/filter/FilterManager.java index 914b8e7168..c3a9c5725a 100644 --- a/ethereum/jsonrpc/src/main/java/tech/pegasys/pantheon/ethereum/jsonrpc/internal/filter/FilterManager.java +++ b/ethereum/jsonrpc/src/main/java/tech/pegasys/pantheon/ethereum/jsonrpc/internal/filter/FilterManager.java @@ -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 blockFilters = filterRepository.getFiltersOfType(BlockFilter.class); + final Collection blockFilters = + filterRepository.getFiltersOfType(BlockFilter.class); blockFilters.forEach( (filter) -> { synchronized (filter) { @@ -136,7 +137,7 @@ public class FilterManager extends AbstractVerticle { } private void checkBlockchainForMatchingLogsForFilters() { - Collection logFilters = filterRepository.getFiltersOfType(LogFilter.class); + final Collection 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 pendingTransactionFilters = + final Collection pendingTransactionFilters = filterRepository.getFiltersOfType(PendingTransactionFilter.class); if (pendingTransactionFilters.isEmpty()) { return; @@ -213,7 +214,7 @@ public class FilterManager extends AbstractVerticle { return null; } - List logs; + final List logs; synchronized (filter) { logs = new ArrayList<>(filter.logs()); filter.clearLogs(); diff --git a/ethereum/jsonrpc/src/main/java/tech/pegasys/pantheon/ethereum/jsonrpc/internal/methods/EthCoinbase.java b/ethereum/jsonrpc/src/main/java/tech/pegasys/pantheon/ethereum/jsonrpc/internal/methods/EthCoinbase.java index d78803ba82..070efc28a1 100644 --- a/ethereum/jsonrpc/src/main/java/tech/pegasys/pantheon/ethereum/jsonrpc/internal/methods/EthCoinbase.java +++ b/ethereum/jsonrpc/src/main/java/tech/pegasys/pantheon/ethereum/jsonrpc/internal/methods/EthCoinbase.java @@ -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); } } diff --git a/ethereum/jsonrpc/src/main/java/tech/pegasys/pantheon/ethereum/jsonrpc/internal/methods/EthGasPrice.java b/ethereum/jsonrpc/src/main/java/tech/pegasys/pantheon/ethereum/jsonrpc/internal/methods/EthGasPrice.java index bd0ad62087..f15be34146 100644 --- a/ethereum/jsonrpc/src/main/java/tech/pegasys/pantheon/ethereum/jsonrpc/internal/methods/EthGasPrice.java +++ b/ethereum/jsonrpc/src/main/java/tech/pegasys/pantheon/ethereum/jsonrpc/internal/methods/EthGasPrice.java @@ -37,7 +37,7 @@ public class EthGasPrice solver = miner.getWorkDefinition(); + final Optional 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() diff --git a/ethereum/jsonrpc/src/main/java/tech/pegasys/pantheon/ethereum/jsonrpc/internal/methods/EthSendRawTransaction.java b/ethereum/jsonrpc/src/main/java/tech/pegasys/pantheon/ethereum/jsonrpc/internal/methods/EthSendRawTransaction.java index 7e92d238bb..ca7307102a 100644 --- a/ethereum/jsonrpc/src/main/java/tech/pegasys/pantheon/ethereum/jsonrpc/internal/methods/EthSendRawTransaction.java +++ b/ethereum/jsonrpc/src/main/java/tech/pegasys/pantheon/ethereum/jsonrpc/internal/methods/EthSendRawTransaction.java @@ -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); } diff --git a/ethereum/jsonrpc/src/main/java/tech/pegasys/pantheon/ethereum/jsonrpc/internal/methods/miner/MinerSetCoinbase.java b/ethereum/jsonrpc/src/main/java/tech/pegasys/pantheon/ethereum/jsonrpc/internal/methods/miner/MinerSetCoinbase.java index 2c3796c147..3d3056be89 100644 --- a/ethereum/jsonrpc/src/main/java/tech/pegasys/pantheon/ethereum/jsonrpc/internal/methods/miner/MinerSetCoinbase.java +++ b/ethereum/jsonrpc/src/main/java/tech/pegasys/pantheon/ethereum/jsonrpc/internal/methods/miner/MinerSetCoinbase.java @@ -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); } } diff --git a/ethereum/jsonrpc/src/main/java/tech/pegasys/pantheon/ethereum/jsonrpc/websocket/WebSocketRequestHandler.java b/ethereum/jsonrpc/src/main/java/tech/pegasys/pantheon/ethereum/jsonrpc/websocket/WebSocketRequestHandler.java index 70af1ca18b..c84b9ef431 100644 --- a/ethereum/jsonrpc/src/main/java/tech/pegasys/pantheon/ethereum/jsonrpc/websocket/WebSocketRequestHandler.java +++ b/ethereum/jsonrpc/src/main/java/tech/pegasys/pantheon/ethereum/jsonrpc/websocket/WebSocketRequestHandler.java @@ -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; diff --git a/ethereum/jsonrpc/src/test/java/tech/pegasys/pantheon/ethereum/jsonrpc/AdminJsonRpcHttpServiceTest.java b/ethereum/jsonrpc/src/test/java/tech/pegasys/pantheon/ethereum/jsonrpc/AdminJsonRpcHttpServiceTest.java index 8528c16762..395f2c4f6b 100644 --- a/ethereum/jsonrpc/src/test/java/tech/pegasys/pantheon/ethereum/jsonrpc/AdminJsonRpcHttpServiceTest.java +++ b/ethereum/jsonrpc/src/test/java/tech/pegasys/pantheon/ethereum/jsonrpc/AdminJsonRpcHttpServiceTest.java @@ -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); diff --git a/ethereum/jsonrpc/src/test/java/tech/pegasys/pantheon/ethereum/jsonrpc/EthJsonRpcHttpBySpecTest.java b/ethereum/jsonrpc/src/test/java/tech/pegasys/pantheon/ethereum/jsonrpc/EthJsonRpcHttpBySpecTest.java index 49a8a0b512..e39fbb5bc2 100644 --- a/ethereum/jsonrpc/src/test/java/tech/pegasys/pantheon/ethereum/jsonrpc/EthJsonRpcHttpBySpecTest.java +++ b/ethereum/jsonrpc/src/test/java/tech/pegasys/pantheon/ethereum/jsonrpc/EthJsonRpcHttpBySpecTest.java @@ -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); diff --git a/ethereum/jsonrpc/src/test/java/tech/pegasys/pantheon/ethereum/jsonrpc/internal/filter/FilterManagerLogFilterTest.java b/ethereum/jsonrpc/src/test/java/tech/pegasys/pantheon/ethereum/jsonrpc/internal/filter/FilterManagerLogFilterTest.java index 56d98d20cf..24bc26ace5 100644 --- a/ethereum/jsonrpc/src/test/java/tech/pegasys/pantheon/ethereum/jsonrpc/internal/filter/FilterManagerLogFilterTest.java +++ b/ethereum/jsonrpc/src/test/java/tech/pegasys/pantheon/ethereum/jsonrpc/internal/filter/FilterManagerLogFilterTest.java @@ -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"); diff --git a/ethereum/jsonrpc/src/test/java/tech/pegasys/pantheon/ethereum/jsonrpc/internal/filter/FilterManagerTest.java b/ethereum/jsonrpc/src/test/java/tech/pegasys/pantheon/ethereum/jsonrpc/internal/filter/FilterManagerTest.java index 5a1a9c145e..8ae78e5a8f 100644 --- a/ethereum/jsonrpc/src/test/java/tech/pegasys/pantheon/ethereum/jsonrpc/internal/filter/FilterManagerTest.java +++ b/ethereum/jsonrpc/src/test/java/tech/pegasys/pantheon/ethereum/jsonrpc/internal/filter/FilterManagerTest.java @@ -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)); diff --git a/ethereum/jsonrpc/src/test/java/tech/pegasys/pantheon/ethereum/jsonrpc/internal/filter/FilterRepositoryTest.java b/ethereum/jsonrpc/src/test/java/tech/pegasys/pantheon/ethereum/jsonrpc/internal/filter/FilterRepositoryTest.java index f1887d0b0e..4054f6a535 100644 --- a/ethereum/jsonrpc/src/test/java/tech/pegasys/pantheon/ethereum/jsonrpc/internal/filter/FilterRepositoryTest.java +++ b/ethereum/jsonrpc/src/test/java/tech/pegasys/pantheon/ethereum/jsonrpc/internal/filter/FilterRepositoryTest.java @@ -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 filters = repository.getFilters(); + final Collection 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 optional = repository.getFilter(filter.getId(), BlockFilter.class); + final Optional 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 optional = + final Optional 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 optional = repository.getFilter("bar", BlockFilter.class); + final Optional optional = repository.getFilter("bar", BlockFilter.class); assertThat(optional.isPresent()).isFalse(); } @Test public void getSingleFilterShouldReturnEmptyForEmptyRepository() { - Optional optional = repository.getFilter("id", BlockFilter.class); + final Optional 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 expectedFilters = Lists.newArrayList(blockFilter1, blockFilter2); + final Collection expectedFilters = Lists.newArrayList(blockFilter1, blockFilter2); repository.save(blockFilter1); repository.save(blockFilter2); repository.save(pendingTxFilter1); - Collection blockFilters = repository.getFiltersOfType(BlockFilter.class); + final Collection 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 filters = repository.getFiltersOfType(BlockFilter.class); + final Collection filters = repository.getFiltersOfType(BlockFilter.class); assertThat(filters).isEmpty(); } @Test public void getFilterCollectionShouldReturnEmptyListForEmptyRepository() { - Collection filters = repository.getFiltersOfType(BlockFilter.class); + final Collection 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); diff --git a/ethereum/jsonrpc/src/test/java/tech/pegasys/pantheon/ethereum/jsonrpc/internal/filter/FilterTest.java b/ethereum/jsonrpc/src/test/java/tech/pegasys/pantheon/ethereum/jsonrpc/internal/filter/FilterTest.java index 8ab5e6b176..fc0fad9248 100644 --- a/ethereum/jsonrpc/src/test/java/tech/pegasys/pantheon/ethereum/jsonrpc/internal/filter/FilterTest.java +++ b/ethereum/jsonrpc/src/test/java/tech/pegasys/pantheon/ethereum/jsonrpc/internal/filter/FilterTest.java @@ -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(); diff --git a/ethereum/jsonrpc/src/test/java/tech/pegasys/pantheon/ethereum/jsonrpc/internal/filter/FilterTimeoutMonitorTest.java b/ethereum/jsonrpc/src/test/java/tech/pegasys/pantheon/ethereum/jsonrpc/internal/filter/FilterTimeoutMonitorTest.java index 6c44cc1a36..d31465801f 100644 --- a/ethereum/jsonrpc/src/test/java/tech/pegasys/pantheon/ethereum/jsonrpc/internal/filter/FilterTimeoutMonitorTest.java +++ b/ethereum/jsonrpc/src/test/java/tech/pegasys/pantheon/ethereum/jsonrpc/internal/filter/FilterTimeoutMonitorTest.java @@ -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)); diff --git a/ethereum/jsonrpc/src/test/java/tech/pegasys/pantheon/ethereum/jsonrpc/internal/methods/EthGetWorkTest.java b/ethereum/jsonrpc/src/test/java/tech/pegasys/pantheon/ethereum/jsonrpc/internal/methods/EthGetWorkTest.java index bc8e848b0b..bd85ac7fd1 100644 --- a/ethereum/jsonrpc/src/test/java/tech/pegasys/pantheon/ethereum/jsonrpc/internal/methods/EthGetWorkTest.java +++ b/ethereum/jsonrpc/src/test/java/tech/pegasys/pantheon/ethereum/jsonrpc/internal/methods/EthGetWorkTest.java @@ -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); } diff --git a/ethereum/jsonrpc/src/test/java/tech/pegasys/pantheon/ethereum/jsonrpc/websocket/subscription/SubscriptionManagerTest.java b/ethereum/jsonrpc/src/test/java/tech/pegasys/pantheon/ethereum/jsonrpc/websocket/subscription/SubscriptionManagerTest.java index c2fdc93d4f..5460db620c 100644 --- a/ethereum/jsonrpc/src/test/java/tech/pegasys/pantheon/ethereum/jsonrpc/websocket/subscription/SubscriptionManagerTest.java +++ b/ethereum/jsonrpc/src/test/java/tech/pegasys/pantheon/ethereum/jsonrpc/websocket/subscription/SubscriptionManagerTest.java @@ -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 = diff --git a/ethereum/p2p/src/main/java/tech/pegasys/pantheon/ethereum/p2p/discovery/internal/Packet.java b/ethereum/p2p/src/main/java/tech/pegasys/pantheon/ethereum/p2p/discovery/internal/Packet.java index 6365235f1b..c7931e6b49 100644 --- a/ethereum/p2p/src/main/java/tech/pegasys/pantheon/ethereum/p2p/discovery/internal/Packet.java +++ b/ethereum/p2p/src/main/java/tech/pegasys/pantheon/ethereum/p2p/discovery/internal/Packet.java @@ -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) { diff --git a/ethereum/p2p/src/main/java/tech/pegasys/pantheon/ethereum/p2p/discovery/internal/PeerTable.java b/ethereum/p2p/src/main/java/tech/pegasys/pantheon/ethereum/p2p/discovery/internal/PeerTable.java index 1f7981331d..33964ff094 100644 --- a/ethereum/p2p/src/main/java/tech/pegasys/pantheon/ethereum/p2p/discovery/internal/PeerTable.java +++ b/ethereum/p2p/src/main/java/tech/pegasys/pantheon/ethereum/p2p/discovery/internal/PeerTable.java @@ -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 res; + final Optional res; try { res = bucket.add(peer); } catch (final IllegalArgumentException ex) { diff --git a/ethereum/p2p/src/main/java/tech/pegasys/pantheon/ethereum/p2p/rlpx/handshake/ecies/ECIESEncryptionEngine.java b/ethereum/p2p/src/main/java/tech/pegasys/pantheon/ethereum/p2p/rlpx/handshake/ecies/ECIESEncryptionEngine.java index 3940a69eb4..d92858afdc 100644 --- a/ethereum/p2p/src/main/java/tech/pegasys/pantheon/ethereum/p2p/rlpx/handshake/ecies/ECIESEncryptionEngine.java +++ b/ethereum/p2p/src/main/java/tech/pegasys/pantheon/ethereum/p2p/rlpx/handshake/ecies/ECIESEncryptionEngine.java @@ -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; diff --git a/ethereum/p2p/src/test/java/tech/pegasys/pantheon/ethereum/p2p/NettyP2PNetworkTest.java b/ethereum/p2p/src/test/java/tech/pegasys/pantheon/ethereum/p2p/NettyP2PNetworkTest.java index 9b031e7664..c09cf64840 100644 --- a/ethereum/p2p/src/test/java/tech/pegasys/pantheon/ethereum/p2p/NettyP2PNetworkTest.java +++ b/ethereum/p2p/src/test/java/tech/pegasys/pantheon/ethereum/p2p/NettyP2PNetworkTest.java @@ -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); diff --git a/ethereum/p2p/src/test/java/tech/pegasys/pantheon/ethereum/p2p/NetworkingServiceLifecycleTest.java b/ethereum/p2p/src/test/java/tech/pegasys/pantheon/ethereum/p2p/NetworkingServiceLifecycleTest.java index ffcb033113..1081cf4414 100644 --- a/ethereum/p2p/src/test/java/tech/pegasys/pantheon/ethereum/p2p/NetworkingServiceLifecycleTest.java +++ b/ethereum/p2p/src/test/java/tech/pegasys/pantheon/ethereum/p2p/NetworkingServiceLifecycleTest.java @@ -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, diff --git a/ethereum/p2p/src/test/java/tech/pegasys/pantheon/ethereum/p2p/discovery/AbstractPeerDiscoveryTest.java b/ethereum/p2p/src/test/java/tech/pegasys/pantheon/ethereum/p2p/discovery/AbstractPeerDiscoveryTest.java index 9c4734bf14..c9d930a46b 100644 --- a/ethereum/p2p/src/test/java/tech/pegasys/pantheon/ethereum/p2p/discovery/AbstractPeerDiscoveryTest.java +++ b/ethereum/p2p/src/test/java/tech/pegasys/pantheon/ethereum/p2p/discovery/AbstractPeerDiscoveryTest.java @@ -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) { diff --git a/ethereum/p2p/src/test/java/tech/pegasys/pantheon/ethereum/p2p/discovery/PeerDiscoveryObserversTest.java b/ethereum/p2p/src/test/java/tech/pegasys/pantheon/ethereum/p2p/discovery/PeerDiscoveryObserversTest.java index 901fc5e719..b783f977ff 100644 --- a/ethereum/p2p/src/test/java/tech/pegasys/pantheon/ethereum/p2p/discovery/PeerDiscoveryObserversTest.java +++ b/ethereum/p2p/src/test/java/tech/pegasys/pantheon/ethereum/p2p/discovery/PeerDiscoveryObserversTest.java @@ -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 events = new ArrayList<>(); queue.forEach(evt -> events.add(evt.toString())); LOG.error("Queue:\n" + String.join("\n", events), e); diff --git a/ethereum/rlp/src/main/java/tech/pegasys/pantheon/ethereum/rlp/AbstractRLPOutput.java b/ethereum/rlp/src/main/java/tech/pegasys/pantheon/ethereum/rlp/AbstractRLPOutput.java index 2fc860af8a..2b71665296 100644 --- a/ethereum/rlp/src/main/java/tech/pegasys/pantheon/ethereum/rlp/AbstractRLPOutput.java +++ b/ethereum/rlp/src/main/java/tech/pegasys/pantheon/ethereum/rlp/AbstractRLPOutput.java @@ -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); diff --git a/ethereum/rlp/src/main/java/tech/pegasys/pantheon/ethereum/rlp/RLP.java b/ethereum/rlp/src/main/java/tech/pegasys/pantheon/ethereum/rlp/RLP.java index b440b434ad..d34ddf64f5 100644 --- a/ethereum/rlp/src/main/java/tech/pegasys/pantheon/ethereum/rlp/RLP.java +++ b/ethereum/rlp/src/main/java/tech/pegasys/pantheon/ethereum/rlp/RLP.java @@ -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; diff --git a/ethereum/trie/src/main/java/tech/pegasys/pantheon/ethereum/trie/CompactEncoding.java b/ethereum/trie/src/main/java/tech/pegasys/pantheon/ethereum/trie/CompactEncoding.java index 6fb7580879..786da36b5f 100644 --- a/ethereum/trie/src/main/java/tech/pegasys/pantheon/ethereum/trie/CompactEncoding.java +++ b/ethereum/trie/src/main/java/tech/pegasys/pantheon/ethereum/trie/CompactEncoding.java @@ -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) { diff --git a/ethereum/trie/src/main/java/tech/pegasys/pantheon/ethereum/trie/StoredNodeFactory.java b/ethereum/trie/src/main/java/tech/pegasys/pantheon/ethereum/trie/StoredNodeFactory.java index ecfa04c94c..5268022fe2 100644 --- a/ethereum/trie/src/main/java/tech/pegasys/pantheon/ethereum/trie/StoredNodeFactory.java +++ b/ethereum/trie/src/main/java/tech/pegasys/pantheon/ethereum/trie/StoredNodeFactory.java @@ -119,7 +119,7 @@ class StoredNodeFactory implements NodeFactory { 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 implements NodeFactory { } } - Optional value; + final Optional value; if (nodeRLPs.nextIsNull()) { nodeRLPs.skipNext(); value = Optional.empty(); @@ -205,7 +205,7 @@ class StoredNodeFactory implements NodeFactory { } private V decodeValue(final RLPInput valueRlp, final Supplier errMessage) { - BytesValue bytes; + final BytesValue bytes; try { bytes = valueRlp.readBytesValue(); } catch (final RLPException ex) { @@ -216,7 +216,7 @@ class StoredNodeFactory implements NodeFactory { } private V deserializeValue(final Supplier errMessage, final BytesValue bytes) { - V value; + final V value; try { value = valueDeserializer.apply(bytes); } catch (final IllegalArgumentException ex) { diff --git a/pantheon/src/main/java/tech/pegasys/pantheon/Runner.java b/pantheon/src/main/java/tech/pegasys/pantheon/Runner.java index d6dea2f948..ec47b5ec38 100644 --- a/pantheon/src/main/java/tech/pegasys/pantheon/Runner.java +++ b/pantheon/src/main/java/tech/pegasys/pantheon/Runner.java @@ -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."); diff --git a/pantheon/src/main/java/tech/pegasys/pantheon/RunnerBuilder.java b/pantheon/src/main/java/tech/pegasys/pantheon/RunnerBuilder.java index 7c325b2639..4fb2bfc222 100644 --- a/pantheon/src/main/java/tech/pegasys/pantheon/RunnerBuilder.java +++ b/pantheon/src/main/java/tech/pegasys/pantheon/RunnerBuilder.java @@ -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, diff --git a/pantheon/src/main/java/tech/pegasys/pantheon/cli/ConfigOptionSearchAndRunHandler.java b/pantheon/src/main/java/tech/pegasys/pantheon/cli/ConfigOptionSearchAndRunHandler.java index f9e241dba0..9f1c7920f4 100644 --- a/pantheon/src/main/java/tech/pegasys/pantheon/cli/ConfigOptionSearchAndRunHandler.java +++ b/pantheon/src/main/java/tech/pegasys/pantheon/cli/ConfigOptionSearchAndRunHandler.java @@ -46,7 +46,7 @@ class ConfigOptionSearchAndRunHandler extends AbstractParseResultHandler { @Override public RpcApi convert(final String name) throws RpcApisConversionException { - String uppercaseName = name.trim().toUpperCase(); + final String uppercaseName = name.trim().toUpperCase(); return Stream.>>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()); } diff --git a/pantheon/src/main/java/tech/pegasys/pantheon/cli/TomlConfigFileDefaultProvider.java b/pantheon/src/main/java/tech/pegasys/pantheon/cli/TomlConfigFileDefaultProvider.java index a641c5062c..cf71d1a55c 100644 --- a/pantheon/src/main/java/tech/pegasys/pantheon/cli/TomlConfigFileDefaultProvider.java +++ b/pantheon/src/main/java/tech/pegasys/pantheon/cli/TomlConfigFileDefaultProvider.java @@ -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); diff --git a/pantheon/src/main/java/tech/pegasys/pantheon/cli/custom/CorsAllowedOriginsProperty.java b/pantheon/src/main/java/tech/pegasys/pantheon/cli/custom/CorsAllowedOriginsProperty.java index ba8c684e9d..f81008c1f6 100644 --- a/pantheon/src/main/java/tech/pegasys/pantheon/cli/custom/CorsAllowedOriginsProperty.java +++ b/pantheon/src/main/java/tech/pegasys/pantheon/cli/custom/CorsAllowedOriginsProperty.java @@ -42,7 +42,7 @@ public class CorsAllowedOriginsProperty { @Override public CorsAllowedOriginsProperty convert(final String value) throws IllegalArgumentException { - List domains; + final List domains; if (value != null && !value.isEmpty()) { domains = new ArrayList<>(Arrays.asList(value.split("\\s*,\\s*"))); } else { diff --git a/pantheon/src/main/java/tech/pegasys/pantheon/util/BlockchainImporter.java b/pantheon/src/main/java/tech/pegasys/pantheon/util/BlockchainImporter.java index 040c0583fd..b3b728e005 100644 --- a/pantheon/src/main/java/tech/pegasys/pantheon/util/BlockchainImporter.java +++ b/pantheon/src/main/java/tech/pegasys/pantheon/util/BlockchainImporter.java @@ -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 blockImporter; + final tech.pegasys.pantheon.ethereum.core.BlockImporter blockImporter; blockImporter = protocolSpec.getBlockImporter(); if (!isSkipBlocks) { diff --git a/pantheon/src/test/java/tech/pegasys/pantheon/cli/PantheonCommandTest.java b/pantheon/src/test/java/tech/pegasys/pantheon/cli/PantheonCommandTest.java index 5f5d41d9b5..33683b9a43 100644 --- a/pantheon/src/test/java/tech/pegasys/pantheon/cli/PantheonCommandTest.java +++ b/pantheon/src/test/java/tech/pegasys/pantheon/cli/PantheonCommandTest.java @@ -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) diff --git a/pantheon/src/test/java/tech/pegasys/pantheon/cli/TomlConfigFileDefaultProviderTest.java b/pantheon/src/test/java/tech/pegasys/pantheon/cli/TomlConfigFileDefaultProviderTest.java index 35ba274fc6..3437b0ce51 100644 --- a/pantheon/src/test/java/tech/pegasys/pantheon/cli/TomlConfigFileDefaultProviderTest.java +++ b/pantheon/src/test/java/tech/pegasys/pantheon/cli/TomlConfigFileDefaultProviderTest.java @@ -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(); diff --git a/quickstart/src/test/java/tech/pegasys/pantheon/tests/quickstart/DockerQuickstartTest.java b/quickstart/src/test/java/tech/pegasys/pantheon/tests/quickstart/DockerQuickstartTest.java index ca4bee32b4..77fa46f431 100644 --- a/quickstart/src/test/java/tech/pegasys/pantheon/tests/quickstart/DockerQuickstartTest.java +++ b/quickstart/src/test/java/tech/pegasys/pantheon/tests/quickstart/DockerQuickstartTest.java @@ -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; } diff --git a/util/src/main/java/tech/pegasys/pantheon/util/uint/UInt256Bytes.java b/util/src/main/java/tech/pegasys/pantheon/util/uint/UInt256Bytes.java index c2a0f941a8..aba8195dfc 100644 --- a/util/src/main/java/tech/pegasys/pantheon/util/uint/UInt256Bytes.java +++ b/util/src/main/java/tech/pegasys/pantheon/util/uint/UInt256Bytes.java @@ -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;