[MINOR] Add missing finals. (#128)

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

@ -73,9 +73,9 @@ public class IbftDiscardValidatorVoteTest {
final Address parameterAddress = Address.fromHexString("1"); final Address parameterAddress = Address.fromHexString("1");
final JsonRpcRequest request = requestWithParams(parameterAddress); 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); assertThat(response).isEqualToComparingFieldByField(expectedResponse);

@ -92,9 +92,9 @@ public class IbftProposeValidatorVoteTest {
public void addValidator() { public void addValidator() {
final Address parameterAddress = Address.fromHexString("1"); final Address parameterAddress = Address.fromHexString("1");
final JsonRpcRequest request = requestWithParams(parameterAddress, "true"); 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); assertThat(response).isEqualToComparingFieldByField(expectedResponse);
@ -105,9 +105,9 @@ public class IbftProposeValidatorVoteTest {
public void removeValidator() { public void removeValidator() {
final Address parameterAddress = Address.fromHexString("1"); final Address parameterAddress = Address.fromHexString("1");
final JsonRpcRequest request = requestWithParams(parameterAddress, "false"); 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); assertThat(response).isEqualToComparingFieldByField(expectedResponse);

@ -50,7 +50,7 @@ public class IbftNetworkPeersTest {
@Before @Before
public void setup() { public void setup() {
for (int i = 0; i < 4; i++) { 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); publicKeys.add(pubKey);
final PeerInfo peerInfo = mock(PeerInfo.class); final PeerInfo peerInfo = mock(PeerInfo.class);
@ -66,15 +66,15 @@ public class IbftNetworkPeersTest {
public void onlyValidatorsAreSentAMessage() throws PeerNotConnected { public void onlyValidatorsAreSentAMessage() throws PeerNotConnected {
// Only add the first Peer's address to the validators. // Only add the first Peer's address to the validators.
validators.add(Util.publicKeyToAddress(publicKeys.get(0))); validators.add(Util.publicKeyToAddress(publicKeys.get(0)));
ValidatorProvider validatorProvider = mock(ValidatorProvider.class); final ValidatorProvider validatorProvider = mock(ValidatorProvider.class);
when(validatorProvider.getCurrentValidators()).thenReturn(validators); when(validatorProvider.getCurrentValidators()).thenReturn(validators);
IbftNetworkPeers peers = new IbftNetworkPeers(validatorProvider); final IbftNetworkPeers peers = new IbftNetworkPeers(validatorProvider);
for (PeerConnection peer : peerConnections) { for (final PeerConnection peer : peerConnections) {
peers.peerAdded(peer); peers.peerAdded(peer);
} }
MessageData messageToSend = new RawMessage(1, EMPTY_BUFFER); final MessageData messageToSend = new RawMessage(1, EMPTY_BUFFER);
peers.multicastToValidators(messageToSend); peers.multicastToValidators(messageToSend);
verify(peerConnections.get(0), times(1)).sendForProtocol("IBF", messageToSend); verify(peerConnections.get(0), times(1)).sendForProtocol("IBF", messageToSend);
@ -87,15 +87,15 @@ public class IbftNetworkPeersTest {
public void doesntSendToValidatorsWhichAreNotDirectlyConnected() throws PeerNotConnected { public void doesntSendToValidatorsWhichAreNotDirectlyConnected() throws PeerNotConnected {
validators.add(Util.publicKeyToAddress(publicKeys.get(0))); validators.add(Util.publicKeyToAddress(publicKeys.get(0)));
ValidatorProvider validatorProvider = mock(ValidatorProvider.class); final ValidatorProvider validatorProvider = mock(ValidatorProvider.class);
when(validatorProvider.getCurrentValidators()).thenReturn(validators); 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. // 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))); 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); peers.multicastToValidators(messageToSend);
verify(peerConnections.get(0), never()).sendForProtocol(any(), any()); verify(peerConnections.get(0), never()).sendForProtocol(any(), any());

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

@ -255,7 +255,7 @@ public class EthJsonRpcHttpBySpecTest extends AbstractEthJsonRpcHttpServiceTest
final Request request = new Request.Builder().post(requestBody).url(baseUrl).build(); final Request request = new Request.Builder().post(requestBody).url(baseUrl).build();
importBlocks(1, BLOCKS.size()); 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"); final int expectedStatusCode = spec.getInteger("statusCode");
assertThat(resp.code()).isEqualTo(expectedStatusCode); assertThat(resp.code()).isEqualTo(expectedStatusCode);

@ -167,7 +167,7 @@ public class FilterManagerLogFilterTest {
@Test @Test
public void getLogsChangesShouldResetFilterExpireDate() { 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)); doReturn(Optional.of(filter)).when(filterRepository).getFilter(eq("foo"), eq(LogFilter.class));
filterManager.logsChanges("foo"); filterManager.logsChanges("foo");
@ -177,7 +177,7 @@ public class FilterManagerLogFilterTest {
@Test @Test
public void getLogsShouldResetFilterExpireDate() { 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)); doReturn(Optional.of(filter)).when(filterRepository).getFilter(eq("foo"), eq(LogFilter.class));
filterManager.logs("foo"); filterManager.logs("foo");

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

@ -44,7 +44,7 @@ public class TomlConfigFileDefaultProviderTest {
@Test @Test
public void defaultValueIsNullIfNoMatchingKeyFoundOtherwiseTheValue() throws IOException { public void defaultValueIsNullIfNoMatchingKeyFoundOtherwiseTheValue() throws IOException {
final File tempConfigFile = temp.newFile("config.toml"); 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.write("an-option='123'");
fileWriter.flush(); fileWriter.flush();
@ -64,7 +64,8 @@ public class TomlConfigFileDefaultProviderTest {
@Test @Test
public void defaultValueForOptionMustMatchType() throws IOException { public void defaultValueForOptionMustMatchType() throws IOException {
final File tempConfigFile = temp.newFile("config.toml"); 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.write("a-boolean-option=true");
fileWriter.newLine(); 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)"); + "\"\"\", a number, a boolean, a date/time, an array, or a table (line 1, column 19)");
final File tempConfigFile = temp.newFile("config.toml"); 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.write("an-invalid-syntax=======....");
fileWriter.flush(); fileWriter.flush();

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

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

Loading…
Cancel
Save