Errorprone 2.3.3 upgrades (#1110)

Biggest change is that UnusedVariable and UnusedMethod went to WARN by
default. Since our build is a no warning build this means we either need
to turn them off or fix them.  I mostly opted for the latter.  Test code
was mostly fixed, unused loggers were deleted, and other shipped code
was mostly suppressed.

Two less noisy fixes to not use `SortedSet` and to use zero based
comparable results instead of -1, 0, and 1.  Also a compiler nit in
errorprone was suppressed, per the description it won't affect us.

Signed-off-by: Adrian Sutton <adrian.sutton@consensys.net>
pull/2/head
Danno Ferrin 6 years ago committed by GitHub
parent b2803c1abe
commit fbb731a8fe
  1. 15
      acceptance-tests/src/test/java/tech/pegasys/pantheon/tests/acceptance/dsl/account/Account.java
  2. 2
      acceptance-tests/src/test/java/tech/pegasys/pantheon/tests/acceptance/dsl/blockchain/Amount.java
  3. 2
      acceptance-tests/src/test/java/tech/pegasys/pantheon/tests/acceptance/dsl/transaction/account/TransferTransaction.java
  4. 2
      build.gradle
  5. 8
      consensus/ibft/src/integration-test/java/tech/pegasys/pantheon/consensus/ibft/tests/RoundChangeTest.java
  6. 3
      consensus/ibft/src/main/java/tech/pegasys/pantheon/consensus/ibft/IbftProtocolSchedule.java
  7. 4
      consensus/ibft/src/main/java/tech/pegasys/pantheon/consensus/ibft/protocol/IbftProtocolManager.java
  8. 2
      consensus/ibft/src/test/java/tech/pegasys/pantheon/consensus/ibft/RoundTimerTest.java
  9. 3
      consensus/ibft/src/test/java/tech/pegasys/pantheon/consensus/ibft/blockcreation/IbftBlockCreatorTest.java
  10. 21
      consensus/ibft/src/test/java/tech/pegasys/pantheon/consensus/ibft/statemachine/IbftBlockHeightManagerTest.java
  11. 28
      consensus/ibft/src/test/java/tech/pegasys/pantheon/consensus/ibft/statemachine/IbftRoundTest.java
  12. 17
      consensus/ibft/src/test/java/tech/pegasys/pantheon/consensus/ibft/statemachine/RoundChangeManagerTest.java
  13. 4
      consensus/ibft/src/test/java/tech/pegasys/pantheon/consensus/ibft/validation/RoundChangeMessageValidatorTest.java
  14. 9
      consensus/ibftlegacy/src/main/java/tech/pegasys/pantheon/consensus/ibftlegacy/IbftProtocolSchedule.java
  15. 3
      consensus/ibftlegacy/src/test/java/tech/pegasys/pantheon/consensus/ibftlegacy/blockcreation/IbftBlockCreatorTest.java
  16. 3
      consensus/ibftlegacy/src/test/java/tech/pegasys/pantheon/consensus/ibftlegacy/headervalidationrules/IbftExtraDataValidationRuleTest.java
  17. 18
      crypto/src/main/java/tech/pegasys/pantheon/crypto/Hash.java
  18. 3
      errorprone-checks/src/main/java/tech/pegasys/errorpronechecks/DoNotCreateSecureRandomDirectly.java
  19. 3
      errorprone-checks/src/main/java/tech/pegasys/errorpronechecks/DoNotInvokeMessageDigestDirectly.java
  20. 3
      errorprone-checks/src/main/java/tech/pegasys/errorpronechecks/DoNotReturnNullOptionals.java
  21. 4
      errorprone-checks/src/main/java/tech/pegasys/errorpronechecks/MethodInputParametersMustBeFinal.java
  22. 3
      ethereum/blockcreation/src/main/java/tech/pegasys/pantheon/ethereum/blockcreation/BlockTransactionSelector.java
  23. 6
      ethereum/core/src/main/java/tech/pegasys/pantheon/ethereum/core/AccountTransactionOrder.java
  24. 4
      ethereum/core/src/main/java/tech/pegasys/pantheon/ethereum/mainnet/EthHashCacheFactory.java
  25. 6
      ethereum/core/src/main/java/tech/pegasys/pantheon/ethereum/privacy/PrivateTransactionProcessor.java
  26. 4
      ethereum/core/src/test/java/tech/pegasys/pantheon/ethereum/mainnet/MainnetTransactionValidatorTest.java
  27. 23
      ethereum/core/src/test/java/tech/pegasys/pantheon/ethereum/transaction/TransactionSimulatorTest.java
  28. 5
      ethereum/core/src/test/java/tech/pegasys/pantheon/ethereum/vm/BlockchainReferenceTestCaseSpec.java
  29. 3
      ethereum/eth/src/main/java/tech/pegasys/pantheon/ethereum/eth/sync/fullsync/FullSyncDownloader.java
  30. 42
      ethereum/eth/src/test/java/tech/pegasys/pantheon/ethereum/eth/manager/EthPeerTest.java
  31. 2
      ethereum/eth/src/test/java/tech/pegasys/pantheon/ethereum/eth/manager/task/GetBlockFromPeerTaskTest.java
  32. 3
      ethereum/eth/src/test/java/tech/pegasys/pantheon/ethereum/eth/sync/fastsync/FastSyncCheckpointHeaderManagerTest.java
  33. 2
      ethereum/eth/src/test/java/tech/pegasys/pantheon/ethereum/eth/sync/fullsync/FullSyncDownloaderTest.java
  34. 3
      ethereum/jsonrpc/src/main/java/tech/pegasys/pantheon/ethereum/jsonrpc/authentication/TomlAuth.java
  35. 5
      ethereum/jsonrpc/src/main/java/tech/pegasys/pantheon/ethereum/jsonrpc/internal/methods/EthGetTransactionCount.java
  36. 1
      ethereum/jsonrpc/src/test/java/tech/pegasys/pantheon/ethereum/jsonrpc/AdminJsonRpcHttpServiceTest.java
  37. 6
      ethereum/jsonrpc/src/test/java/tech/pegasys/pantheon/ethereum/jsonrpc/internal/filter/EthJsonRpcHttpServiceTest.java
  38. 40
      ethereum/jsonrpc/src/test/java/tech/pegasys/pantheon/ethereum/jsonrpc/internal/methods/privacy/EeaGetTransactionReceiptTest.java
  39. 11
      ethereum/jsonrpc/src/test/java/tech/pegasys/pantheon/ethereum/jsonrpc/websocket/methods/WebSocketMethodsFactoryTest.java
  40. 3
      ethereum/p2p/src/test/java/tech/pegasys/pantheon/ethereum/p2p/discovery/internal/RecursivePeerRefreshStateTest.java
  41. 8
      gradle/versions.gradle
  42. 4
      pantheon/src/main/java/tech/pegasys/pantheon/cli/PantheonCommand.java
  43. 3
      pantheon/src/main/java/tech/pegasys/pantheon/cli/StandaloneCommand.java
  44. 3
      pantheon/src/main/java/tech/pegasys/pantheon/cli/rlp/RLPSubCommand.java
  45. 34
      pantheon/src/test/java/tech/pegasys/pantheon/cli/CommandLineUtilsTest.java
  46. 3
      pantheon/src/test/java/tech/pegasys/pantheon/cli/PasswordSubCommandTest.java
  47. 7
      pantheon/src/test/java/tech/pegasys/pantheon/cli/custom/RpcAuthFileValidatorTest.java
  48. 62
      services/kvstore/src/main/java/tech/pegasys/pantheon/services/kvstore/RocksDbKeyValueStorage.java
  49. 4
      services/tasks/src/test/java/tech/pegasys/pantheon/services/tasks/CachingTaskCollectionTest.java
  50. 5
      testutil/src/main/java/tech/pegasys/pantheon/testutil/JsonTestParameters.java
  51. 4
      util/src/test/java/tech/pegasys/pantheon/util/bytes/BytesValueTest.java

@ -75,4 +75,19 @@ public class Account {
return new ExpectAccountBalance(
eth, this, expectedBalance.getValue(), expectedBalance.getUnit());
}
@Override
public String toString() {
return "Account{"
+ "eth="
+ eth
+ ", name='"
+ name
+ '\''
+ ", keyPair="
+ keyPair
+ ", nonce="
+ nonce
+ '}';
}
}

@ -46,7 +46,7 @@ public class Amount {
public Amount subtract(final Amount subtracting) {
final Unit denominator;
if (unit.getWeiFactor().compareTo(subtracting.unit.getWeiFactor()) == -1) {
if (unit.getWeiFactor().compareTo(subtracting.unit.getWeiFactor()) < 0) {
denominator = unit;
} else {
denominator = subtracting.unit;

@ -95,7 +95,7 @@ public class TransferTransaction implements Transaction<Hash> {
final BigInteger price =
Convert.toWei(unconverted.getValue(), unconverted.getUnit()).toBigInteger();
if (MINIMUM_GAS_PRICE.compareTo(price) == 1) {
if (MINIMUM_GAS_PRICE.compareTo(price) > 0) {
throw new IllegalArgumentException(
String.format(
"Gas price: %s WEI, is below the accepted minimum: %s WEI",

@ -20,7 +20,7 @@ plugins {
id 'com.github.hierynomus.license' version '0.15.0'
id 'io.spring.dependency-management' version '1.0.7.RELEASE'
id 'me.champeau.gradle.jmh' version '0.4.8' apply false
id 'net.ltgt.errorprone' version '0.6.1'
id 'net.ltgt.errorprone' version '0.7.1'
id 'net.researchgate.release' version '2.7.0'
}

@ -258,7 +258,7 @@ public class RoundChangeTest {
new ConsensusRoundIdentifier(1, 2),
context.createBlockForProposalFromChainHead(2, ARBITRARY_BLOCKTIME));
List<SignedData<RoundChangePayload>> roundChangeMessages = Lists.newArrayList();
final List<SignedData<RoundChangePayload>> roundChangeMessages = Lists.newArrayList();
// Create a roundChange containing a PreparedCertificate
roundChangeMessages.add(
peers
@ -311,9 +311,9 @@ public class RoundChangeTest {
public void illegallyConstructedRoundChangeMessageIsDiscarded() {
final ConsensusRoundIdentifier targetRound = new ConsensusRoundIdentifier(1, 4);
final RoundChange rc1 = peers.getNonProposing(0).injectRoundChange(targetRound, empty());
final RoundChange rc2 = peers.getNonProposing(1).injectRoundChange(targetRound, empty());
final RoundChange rc3 = peers.getNonProposing(2).injectRoundChange(targetRound, empty());
peers.getNonProposing(0).injectRoundChange(targetRound, empty());
peers.getNonProposing(1).injectRoundChange(targetRound, empty());
peers.getNonProposing(2).injectRoundChange(targetRound, empty());
// create illegal RoundChangeMessage
final PreparedRoundArtifacts illegalPreparedRoundArtifacts =

@ -16,7 +16,6 @@ import static tech.pegasys.pantheon.consensus.ibft.IbftBlockHeaderValidationRule
import tech.pegasys.pantheon.config.GenesisConfigOptions;
import tech.pegasys.pantheon.config.IbftConfigOptions;
import tech.pegasys.pantheon.consensus.common.EpochManager;
import tech.pegasys.pantheon.ethereum.MainnetBlockValidator;
import tech.pegasys.pantheon.ethereum.core.PrivacyParameters;
import tech.pegasys.pantheon.ethereum.core.Wei;
@ -35,9 +34,7 @@ public class IbftProtocolSchedule {
public static ProtocolSchedule<IbftContext> create(final GenesisConfigOptions config) {
final IbftConfigOptions ibftConfig = config.getIbftLegacyConfigOptions();
final long epochLength = ibftConfig.getEpochLength();
final long blockPeriod = ibftConfig.getBlockPeriodSeconds();
final EpochManager epochManager = new EpochManager(epochLength);
return new ProtocolScheduleBuilder<>(
config,

@ -25,13 +25,9 @@ import tech.pegasys.pantheon.ethereum.p2p.wire.messages.DisconnectMessage.Discon
import java.util.Arrays;
import java.util.List;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
public class IbftProtocolManager implements ProtocolManager {
private final IbftEventQueue ibftEventQueue;
private final Logger LOG = LogManager.getLogger();
private final PeerConnectionTracker peers;
/**

@ -17,9 +17,9 @@ import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyLong;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import static org.mockito.internal.verification.VerificationModeFactory.times;
import tech.pegasys.pantheon.consensus.ibft.ibftevent.RoundExpiry;

@ -20,7 +20,6 @@ import static tech.pegasys.pantheon.consensus.ibft.IbftContextBuilder.setupConte
import static tech.pegasys.pantheon.ethereum.core.InMemoryStorageProvider.createInMemoryWorldStateArchive;
import tech.pegasys.pantheon.config.GenesisConfigFile;
import tech.pegasys.pantheon.consensus.common.VoteTally;
import tech.pegasys.pantheon.consensus.ibft.IbftBlockHashing;
import tech.pegasys.pantheon.consensus.ibft.IbftBlockHeaderValidationRulesetFactory;
import tech.pegasys.pantheon.consensus.ibft.IbftContext;
@ -69,8 +68,6 @@ public class IbftBlockCreatorTest {
initialValidatorList.add(AddressHelpers.ofValue(i));
}
final VoteTally voteTally = new VoteTally(initialValidatorList);
final ProtocolSchedule<IbftContext> protocolSchedule =
IbftProtocolSchedule.create(
GenesisConfigFile.fromConfig("{\"config\": {\"spuriousDragonBlock\":0}}")

@ -95,7 +95,6 @@ public class IbftBlockHeightManagerTest {
@Captor private ArgumentCaptor<Optional<PreparedRoundArtifacts>> preparedRoundArtifactsCaptor;
private final List<KeyPair> validatorKeys = Lists.newArrayList();
private final List<Address> validators = Lists.newArrayList();
private final List<MessageFactory> validatorMessageFactory = Lists.newArrayList();
@ -105,7 +104,7 @@ public class IbftBlockHeightManagerTest {
private void buildCreatedBlock() {
IbftExtraData extraData =
final IbftExtraData extraData =
new IbftExtraData(
BytesValue.wrap(new byte[32]), emptyList(), Optional.empty(), 0, validators);
@ -118,7 +117,6 @@ public class IbftBlockHeightManagerTest {
public void setup() {
for (int i = 0; i < 3; i++) {
final KeyPair key = KeyPair.generate();
validatorKeys.add(key);
validators.add(Util.publicKeyToAddress(key.getPublicKey()));
validatorMessageFactory.add(new MessageFactory(key));
}
@ -146,7 +144,7 @@ public class IbftBlockHeightManagerTest {
when(roundFactory.createNewRound(any(), anyInt()))
.thenAnswer(
invocation -> {
final int round = (int) invocation.getArgument(1);
final int round = invocation.getArgument(1);
final ConsensusRoundIdentifier roundId = new ConsensusRoundIdentifier(1, round);
final RoundState createdRoundState =
new RoundState(roundId, finalState.getQuorum(), messageValidator);
@ -183,14 +181,13 @@ public class IbftBlockHeightManagerTest {
public void startsABlockTimerOnStartIfLocalNodeIsTheProoserForRound() {
when(finalState.isLocalNodeProposerForRound(any())).thenReturn(true);
final IbftBlockHeightManager manager =
new IbftBlockHeightManager(
headerTestFixture.buildHeader(),
finalState,
roundChangeManager,
roundFactory,
clock,
messageValidatorFactory);
new IbftBlockHeightManager(
headerTestFixture.buildHeader(),
finalState,
roundChangeManager,
roundFactory,
clock,
messageValidatorFactory);
verify(blockTimer, times(1)).startTimer(any(), any());
}

@ -32,9 +32,7 @@ import tech.pegasys.pantheon.consensus.ibft.RoundTimer;
import tech.pegasys.pantheon.consensus.ibft.blockcreation.IbftBlockCreator;
import tech.pegasys.pantheon.consensus.ibft.network.IbftMessageTransmitter;
import tech.pegasys.pantheon.consensus.ibft.payload.MessageFactory;
import tech.pegasys.pantheon.consensus.ibft.payload.ProposalPayload;
import tech.pegasys.pantheon.consensus.ibft.payload.RoundChangeCertificate;
import tech.pegasys.pantheon.consensus.ibft.payload.SignedData;
import tech.pegasys.pantheon.consensus.ibft.validation.MessageValidator;
import tech.pegasys.pantheon.crypto.SECP256K1;
import tech.pegasys.pantheon.crypto.SECP256K1.KeyPair;
@ -82,7 +80,6 @@ public class IbftRoundTest {
@Mock private MessageValidator messageValidator;
@Mock private RoundTimer roundTimer;
@Captor private ArgumentCaptor<SignedData<ProposalPayload>> payloadArgCaptor;
@Captor private ArgumentCaptor<Block> blockCaptor;
private Block proposedBlock;
@ -120,17 +117,16 @@ public class IbftRoundTest {
@Test
public void onConstructionRoundTimerIsStarted() {
final RoundState roundState = new RoundState(roundIdentifier, 3, messageValidator);
final IbftRound round =
new IbftRound(
roundState,
blockCreator,
protocolContext,
blockImporter,
subscribers,
localNodeKeys,
messageFactory,
transmitter,
roundTimer);
new IbftRound(
roundState,
blockCreator,
protocolContext,
blockImporter,
subscribers,
localNodeKeys,
messageFactory,
transmitter,
roundTimer);
verify(roundTimer, times(1)).startTimer(roundIdentifier);
}
@ -233,11 +229,11 @@ public class IbftRoundTest {
messageFactory.createCommit(roundIdentifier, proposedBlock.getHash(), remoteCommitSeal));
// Should import block when both commit seals are available.
ArgumentCaptor<Block> capturedBlock = ArgumentCaptor.forClass(Block.class);
final ArgumentCaptor<Block> capturedBlock = ArgumentCaptor.forClass(Block.class);
verify(blockImporter, times(1)).importBlock(any(), capturedBlock.capture(), any());
// Ensure imported block contains both commit seals.
IbftExtraData importedExtraData =
final IbftExtraData importedExtraData =
IbftExtraData.decode(capturedBlock.getValue().getHeader().getExtraData());
assertThat(importedExtraData.getSeals()).containsOnly(remoteCommitSeal, localCommitSeal);
}

@ -32,13 +32,9 @@ import tech.pegasys.pantheon.consensus.ibft.validation.SignedDataValidator;
import tech.pegasys.pantheon.crypto.SECP256K1.KeyPair;
import tech.pegasys.pantheon.ethereum.BlockValidator;
import tech.pegasys.pantheon.ethereum.BlockValidator.BlockProcessingOutputs;
import tech.pegasys.pantheon.ethereum.ProtocolContext;
import tech.pegasys.pantheon.ethereum.chain.MutableBlockchain;
import tech.pegasys.pantheon.ethereum.core.Address;
import tech.pegasys.pantheon.ethereum.core.Block;
import tech.pegasys.pantheon.ethereum.core.BlockHeader;
import tech.pegasys.pantheon.ethereum.core.Util;
import tech.pegasys.pantheon.ethereum.worldstate.WorldStateArchive;
import java.util.Collections;
import java.util.List;
@ -63,7 +59,7 @@ public class RoundChangeManagerTest {
private final ConsensusRoundIdentifier ri2 = new ConsensusRoundIdentifier(2, 2);
private final ConsensusRoundIdentifier ri3 = new ConsensusRoundIdentifier(2, 3);
private final List<Address> validators = Lists.newArrayList();
private ProposalBlockConsistencyValidator proposalConsistencyValidator =
private final ProposalBlockConsistencyValidator proposalConsistencyValidator =
mock(ProposalBlockConsistencyValidator.class);
@Before
@ -73,18 +69,13 @@ public class RoundChangeManagerTest {
validators.add(Util.publicKeyToAddress(validator1Key.getPublicKey()));
validators.add(Util.publicKeyToAddress(validator2Key.getPublicKey()));
final ProtocolContext<IbftContext> protocolContext =
new ProtocolContext<>(
mock(MutableBlockchain.class), mock(WorldStateArchive.class), mock(IbftContext.class));
@SuppressWarnings("unchecked")
BlockValidator<IbftContext> blockValidator =
final BlockValidator<IbftContext> blockValidator =
(BlockValidator<IbftContext>) mock(BlockValidator.class);
when(blockValidator.validateAndProcessBlock(any(), any(), any(), any()))
.thenReturn(Optional.of(new BlockProcessingOutputs(null, null)));
BlockHeader parentHeader = mock(BlockHeader.class);
RoundChangePayloadValidator.MessageValidatorForHeightFactory messageValidatorFactory =
final RoundChangePayloadValidator.MessageValidatorForHeightFactory messageValidatorFactory =
mock(RoundChangePayloadValidator.MessageValidatorForHeightFactory.class);
when(messageValidatorFactory.createAt(ri1))
@ -119,7 +110,7 @@ public class RoundChangeManagerTest {
private RoundChange makeRoundChangeMessage(
final KeyPair key, final ConsensusRoundIdentifier round) {
MessageFactory messageFactory = new MessageFactory(key);
final MessageFactory messageFactory = new MessageFactory(key);
return messageFactory.createRoundChange(round, Optional.empty());
}

@ -12,18 +12,15 @@
*/
package tech.pegasys.pantheon.consensus.ibft.validation;
import static java.util.Collections.emptyList;
import static java.util.Optional.empty;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import tech.pegasys.pantheon.consensus.ibft.ConsensusRoundIdentifier;
import tech.pegasys.pantheon.consensus.ibft.TestHelpers;
import tech.pegasys.pantheon.consensus.ibft.messagewrappers.RoundChange;
import tech.pegasys.pantheon.consensus.ibft.payload.MessageFactory;
import tech.pegasys.pantheon.crypto.SECP256K1.KeyPair;
import tech.pegasys.pantheon.ethereum.core.Block;
import org.junit.Test;
@ -34,7 +31,6 @@ public class RoundChangeMessageValidatorTest {
private final KeyPair keyPair = KeyPair.generate();
private final MessageFactory messageFactory = new MessageFactory(keyPair);
private final ConsensusRoundIdentifier roundIdentifier = new ConsensusRoundIdentifier(1, 1);
private final Block block = TestHelpers.createProposalBlock(emptyList(), roundIdentifier);
private ProposalBlockConsistencyValidator proposalBlockConsistencyValidator =
mock(ProposalBlockConsistencyValidator.class);

@ -16,7 +16,6 @@ import static tech.pegasys.pantheon.consensus.ibftlegacy.IbftBlockHeaderValidati
import tech.pegasys.pantheon.config.GenesisConfigOptions;
import tech.pegasys.pantheon.config.IbftConfigOptions;
import tech.pegasys.pantheon.consensus.common.EpochManager;
import tech.pegasys.pantheon.consensus.ibft.IbftContext;
import tech.pegasys.pantheon.ethereum.MainnetBlockValidator;
import tech.pegasys.pantheon.ethereum.core.PrivacyParameters;
@ -36,22 +35,18 @@ public class IbftProtocolSchedule {
public static ProtocolSchedule<IbftContext> create(final GenesisConfigOptions config) {
final IbftConfigOptions ibftConfig = config.getIbftLegacyConfigOptions();
final long epochLength = ibftConfig.getEpochLength();
final long blockPeriod = ibftConfig.getBlockPeriodSeconds();
final EpochManager epochManager = new EpochManager(epochLength);
return new ProtocolScheduleBuilder<>(
config,
DEFAULT_CHAIN_ID,
builder -> applyIbftChanges(blockPeriod, epochManager, builder),
builder -> applyIbftChanges(blockPeriod, builder),
PrivacyParameters.noPrivacy())
.createProtocolSchedule();
}
private static ProtocolSpecBuilder<IbftContext> applyIbftChanges(
final long secondsBetweenBlocks,
final EpochManager epochManager,
final ProtocolSpecBuilder<Void> builder) {
final long secondsBetweenBlocks, final ProtocolSpecBuilder<Void> builder) {
return builder
.<IbftContext>changeConsensusContextType(
difficultyCalculator -> ibftBlockHeaderValidator(secondsBetweenBlocks),

@ -20,7 +20,6 @@ import static tech.pegasys.pantheon.consensus.ibft.IbftContextBuilder.setupConte
import static tech.pegasys.pantheon.ethereum.core.InMemoryStorageProvider.createInMemoryWorldStateArchive;
import tech.pegasys.pantheon.config.GenesisConfigFile;
import tech.pegasys.pantheon.consensus.common.VoteTally;
import tech.pegasys.pantheon.consensus.ibft.IbftContext;
import tech.pegasys.pantheon.consensus.ibftlegacy.IbftBlockHeaderValidationRulesetFactory;
import tech.pegasys.pantheon.consensus.ibftlegacy.IbftExtraData;
@ -75,8 +74,6 @@ public class IbftBlockCreatorTest {
Address.fromHexString(String.format("%020d", 4)),
localAddr);
final VoteTally voteTally = new VoteTally(initialValidatorList);
final ProtocolSchedule<IbftContext> protocolSchedule =
IbftProtocolSchedule.create(
GenesisConfigFile.fromConfig("{\"config\": {\"spuriousDragonBlock\":0}}")

@ -17,7 +17,6 @@ import static java.util.Collections.singletonList;
import static org.assertj.core.api.Assertions.assertThat;
import static tech.pegasys.pantheon.consensus.ibft.IbftContextBuilder.setupContextWithValidators;
import tech.pegasys.pantheon.consensus.common.VoteTally;
import tech.pegasys.pantheon.consensus.ibft.IbftContext;
import tech.pegasys.pantheon.consensus.ibftlegacy.IbftBlockHashing;
import tech.pegasys.pantheon.consensus.ibftlegacy.IbftExtraData;
@ -186,7 +185,6 @@ public class IbftExtraDataValidationRuleTest {
Lists.newArrayList(
AddressHelpers.calculateAddressWithRespectTo(proposerAddress, 1), proposerAddress);
final VoteTally voteTally = new VoteTally(validators);
final ProtocolContext<IbftContext> context =
new ProtocolContext<>(null, null, setupContextWithValidators(validators));
@ -312,7 +310,6 @@ public class IbftExtraDataValidationRuleTest {
}
Collections.sort(validators);
final VoteTally voteTally = new VoteTally(validators);
BlockHeader header = createProposedBlockHeader(proposerKeyPair, validators);
final IbftExtraData commitedExtraData =
createExtraDataWithCommitSeals(header, committerKeys.subList(0, committerCount));

@ -34,24 +34,6 @@ public abstract class Hash {
private static final String SHA256_ALG = "SHA-256";
private static final String RIPEMD160 = "RIPEMD160";
/**
* Helper method to generate a digest using the provided algorithm.
*
* @param input The input bytes to produce the digest for.
* @param alg The name of the digest algorithm to use.
* @return A digest.
*/
private static byte[] digestUsingAlgorithm(final byte[] input, final String alg) {
final MessageDigest digest;
try {
digest = BouncyCastleMessageDigestFactory.create(alg);
digest.update(input);
return digest.digest();
} catch (final NoSuchAlgorithmException e) {
throw new RuntimeException(e);
}
}
/**
* Helper method to generate a digest using the provided algorithm.
*

@ -12,7 +12,6 @@
*/
package tech.pegasys.errorpronechecks;
import static com.google.errorprone.BugPattern.Category.JDK;
import static com.google.errorprone.BugPattern.SeverityLevel.WARNING;
import com.google.auto.service.AutoService;
@ -31,11 +30,11 @@ import com.sun.tools.javac.code.Symbol;
@BugPattern(
name = "DoNotCreateSecureRandomDirectly",
summary = "Do not create SecureRandom directly.",
category = JDK,
severity = WARNING)
public class DoNotCreateSecureRandomDirectly extends BugChecker
implements MethodInvocationTreeMatcher, NewClassTreeMatcher {
@SuppressWarnings("TreeToString")
@Override
public Description matchMethodInvocation(
final MethodInvocationTree tree, final VisitorState state) {

@ -12,7 +12,6 @@
*/
package tech.pegasys.errorpronechecks;
import static com.google.errorprone.BugPattern.Category.JDK;
import static com.google.errorprone.BugPattern.SeverityLevel.WARNING;
import com.google.auto.service.AutoService;
@ -27,11 +26,11 @@ import com.sun.source.tree.MethodInvocationTree;
@BugPattern(
name = "DoNotInvokeMessageDigestDirectly",
summary = "Do not invoke MessageDigest.getInstance directly.",
category = JDK,
severity = WARNING)
public class DoNotInvokeMessageDigestDirectly extends BugChecker
implements MethodInvocationTreeMatcher {
@SuppressWarnings("TreeToString")
@Override
public Description matchMethodInvocation(
final MethodInvocationTree tree, final VisitorState state) {

@ -12,7 +12,6 @@
*/
package tech.pegasys.errorpronechecks;
import static com.google.errorprone.BugPattern.Category.JDK;
import static com.google.errorprone.BugPattern.SeverityLevel.SUGGESTION;
import static com.google.errorprone.matchers.Matchers.contains;
import static com.sun.source.tree.Tree.Kind.NULL_LITERAL;
@ -37,7 +36,6 @@ import com.sun.source.tree.Tree;
@BugPattern(
name = "DoNotReturnNullOptionals",
summary = "Do not return null optionals.",
category = JDK,
severity = SUGGESTION)
public class DoNotReturnNullOptionals extends BugChecker implements MethodTreeMatcher {
@ -55,6 +53,7 @@ public class DoNotReturnNullOptionals extends BugChecker implements MethodTreeMa
private static final Matcher<Tree> RETURN_NULL = new ReturnNullMatcher();
private static final Matcher<Tree> CONTAINS_RETURN_NULL = contains(RETURN_NULL);
@SuppressWarnings("TreeToString")
@Override
public Description matchMethod(final MethodTree tree, final VisitorState state) {
if ((tree.getReturnType() == null)

@ -12,7 +12,6 @@
*/
package tech.pegasys.errorpronechecks;
import static com.google.errorprone.BugPattern.Category.JDK;
import static com.google.errorprone.BugPattern.SeverityLevel.WARNING;
import javax.lang.model.element.Modifier;
@ -33,7 +32,6 @@ import com.sun.source.tree.VariableTree;
@BugPattern(
name = "MethodInputParametersMustBeFinal",
summary = "Method input parameters must be final.",
category = JDK,
severity = WARNING)
public class MethodInputParametersMustBeFinal extends BugChecker
implements MethodTreeMatcher, ClassTreeMatcher {
@ -82,6 +80,7 @@ public class MethodInputParametersMustBeFinal extends BugChecker
return !mods.getFlags().contains(Modifier.ABSTRACT);
}
@SuppressWarnings("TreeToString")
private boolean isInterface(final ModifiersTree mods) {
return mods.toString().contains("interface");
}
@ -102,6 +101,7 @@ public class MethodInputParametersMustBeFinal extends BugChecker
return isAbstraction && isEnum(tree);
}
@SuppressWarnings("TreeToString")
private boolean isEnum(final ClassTree tree) {
return tree.toString().contains("enum");
}

@ -31,8 +31,6 @@ import java.util.concurrent.CancellationException;
import java.util.function.Supplier;
import com.google.common.collect.Lists;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
/**
* Responsible for extracting transactions from PendingTransactions and determining if the
@ -56,7 +54,6 @@ import org.apache.logging.log4j.Logger;
*/
public class BlockTransactionSelector {
private static final Logger LOG = LogManager.getLogger();
private final Wei minTransactionGasPrice;
private static final double MIN_BLOCK_OCCUPANCY_RATIO = 0.8;

@ -15,7 +15,7 @@ package tech.pegasys.pantheon.ethereum.core;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.SortedSet;
import java.util.NavigableSet;
import java.util.TreeSet;
import java.util.stream.Stream;
@ -23,8 +23,8 @@ public class AccountTransactionOrder {
private static final Comparator<Transaction> SORT_BY_NONCE =
Comparator.comparing(Transaction::getNonce);
private final SortedSet<Transaction> transactionsForSender = new TreeSet<>(SORT_BY_NONCE);
private final SortedSet<Transaction> deferredTransactions = new TreeSet<>(SORT_BY_NONCE);
private final NavigableSet<Transaction> transactionsForSender = new TreeSet<>(SORT_BY_NONCE);
private final NavigableSet<Transaction> deferredTransactions = new TreeSet<>(SORT_BY_NONCE);
public AccountTransactionOrder(final Stream<Transaction> senderTransactions) {
senderTransactions.forEach(this.transactionsForSender::add);

@ -17,13 +17,9 @@ import java.util.concurrent.ExecutionException;
import com.google.common.cache.Cache;
import com.google.common.cache.CacheBuilder;
import com.google.common.primitives.Ints;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
public class EthHashCacheFactory {
private static final Logger LOG = LogManager.getLogger();
public static class EthHashDescriptor {
private final long datasetSize;
private final int[] cache;

@ -44,8 +44,10 @@ public class PrivateTransactionProcessor {
private static final Logger LOG = LogManager.getLogger();
@SuppressWarnings("unused")
private final GasCalculator gasCalculator;
@SuppressWarnings("unused")
private final TransactionValidator transactionValidator;
private final AbstractMessageProcessor contractCreationProcessor;
@ -123,6 +125,7 @@ public class PrivateTransactionProcessor {
}
}
@SuppressWarnings("unused")
private final boolean clearEmptyAccounts;
public PrivateTransactionProcessor(
@ -138,6 +141,7 @@ public class PrivateTransactionProcessor {
this.clearEmptyAccounts = clearEmptyAccounts;
}
@SuppressWarnings("unused")
public Result processTransaction(
final Blockchain blockchain,
final WorldUpdater publicWorldState,
@ -239,6 +243,7 @@ public class PrivateTransactionProcessor {
}
}
@SuppressWarnings("unused")
private static void clearEmptyAccounts(final WorldUpdater worldState) {
worldState.getTouchedAccounts().stream()
.filter(Account::isEmpty)
@ -262,6 +267,7 @@ public class PrivateTransactionProcessor {
}
}
@SuppressWarnings("unused")
private static Gas refunded(
final Transaction transaction, final Gas gasRemaining, final Gas gasRefund) {
// Integer truncation takes care of the the floor calculation needed after the divide.

@ -145,10 +145,6 @@ public class MainnetTransactionValidatorTest {
return account(basicTransaction.getUpfrontCost(), nonce);
}
private Account accountWithBalance(final Wei balance) {
return account(balance, basicTransaction.getNonce());
}
private Account account(final Wei balance, final long nonce) {
final Account account = mock(Account.class);
when(account.getBalance()).thenReturn(balance);

@ -100,8 +100,7 @@ public class TransactionSimulatorTest {
.payload(callParameter.getPayload())
.signature(FAKE_SIGNATURE)
.build();
mockProcessorStatusForTransaction(
1L, expectedTransaction, Status.SUCCESSFUL, callParameter.getPayload());
mockProcessorStatusForTransaction(1L, expectedTransaction, Status.SUCCESSFUL);
final Optional<TransactionSimulatorResult> result =
transactionSimulator.process(callParameter, 1L);
@ -128,7 +127,7 @@ public class TransactionSimulatorTest {
.payload(BytesValue.EMPTY)
.signature(FAKE_SIGNATURE)
.build();
mockProcessorStatusForTransaction(1L, expectedTransaction, Status.SUCCESSFUL, BytesValue.of());
mockProcessorStatusForTransaction(1L, expectedTransaction, Status.SUCCESSFUL);
transactionSimulator.process(callParameter, 1L);
@ -153,7 +152,7 @@ public class TransactionSimulatorTest {
.payload(BytesValue.EMPTY)
.signature(FAKE_SIGNATURE)
.build();
mockProcessorStatusForTransaction(1L, expectedTransaction, Status.SUCCESSFUL, BytesValue.of());
mockProcessorStatusForTransaction(1L, expectedTransaction, Status.SUCCESSFUL);
transactionSimulator.process(callParameter, 1L);
@ -178,7 +177,7 @@ public class TransactionSimulatorTest {
.payload(callParameter.getPayload())
.signature(FAKE_SIGNATURE)
.build();
mockProcessorStatusForTransaction(1L, expectedTransaction, Status.FAILED, null);
mockProcessorStatusForTransaction(1L, expectedTransaction, Status.FAILED);
final Optional<TransactionSimulatorResult> result =
transactionSimulator.process(callParameter, 1L);
@ -215,8 +214,7 @@ public class TransactionSimulatorTest {
.payload(callParameter.getPayload())
.signature(FAKE_SIGNATURE)
.build();
mockProcessorStatusForTransaction(
1L, expectedTransaction, Status.SUCCESSFUL, callParameter.getPayload());
mockProcessorStatusForTransaction(1L, expectedTransaction, Status.SUCCESSFUL);
final Optional<TransactionSimulatorResult> result =
transactionSimulator.process(callParameter, DEFAULT_BLOCK_HEADER_HASH);
@ -243,7 +241,7 @@ public class TransactionSimulatorTest {
.payload(BytesValue.EMPTY)
.signature(FAKE_SIGNATURE)
.build();
mockProcessorStatusForTransaction(1L, expectedTransaction, Status.SUCCESSFUL, BytesValue.of());
mockProcessorStatusForTransaction(1L, expectedTransaction, Status.SUCCESSFUL);
transactionSimulator.process(callParameter, DEFAULT_BLOCK_HEADER_HASH);
@ -268,7 +266,7 @@ public class TransactionSimulatorTest {
.payload(BytesValue.EMPTY)
.signature(FAKE_SIGNATURE)
.build();
mockProcessorStatusForTransaction(1L, expectedTransaction, Status.SUCCESSFUL, BytesValue.of());
mockProcessorStatusForTransaction(1L, expectedTransaction, Status.SUCCESSFUL);
transactionSimulator.process(callParameter, DEFAULT_BLOCK_HEADER_HASH);
@ -293,7 +291,7 @@ public class TransactionSimulatorTest {
.payload(callParameter.getPayload())
.signature(FAKE_SIGNATURE)
.build();
mockProcessorStatusForTransaction(1L, expectedTransaction, Status.FAILED, null);
mockProcessorStatusForTransaction(1L, expectedTransaction, Status.FAILED);
final Optional<TransactionSimulatorResult> result =
transactionSimulator.process(callParameter, DEFAULT_BLOCK_HEADER_HASH);
@ -329,10 +327,7 @@ public class TransactionSimulatorTest {
}
private void mockProcessorStatusForTransaction(
final long blockNumber,
final Transaction transaction,
final Result.Status status,
final BytesValue output) {
final long blockNumber, final Transaction transaction, final Status status) {
when(protocolSchedule.getByBlockNumber(eq(blockNumber))).thenReturn(protocolSpec);
when(protocolSpec.getTransactionProcessor()).thenReturn(transactionProcessor);
when(protocolSpec.getMiningBeneficiaryCalculator()).thenReturn(BlockHeader::getCoinbase);

@ -49,8 +49,6 @@ public class BlockchainReferenceTestCaseSpec {
private final BlockHeaderMock genesisBlockHeader;
private final BytesValue genesisRLP;
private final Hash lastBlockHash;
private final WorldStateArchive worldStateArchive;
@ -87,14 +85,13 @@ public class BlockchainReferenceTestCaseSpec {
@JsonProperty("network") final String network,
@JsonProperty("blocks") final CandidateBlock[] candidateBlocks,
@JsonProperty("genesisBlockHeader") final BlockHeaderMock genesisBlockHeader,
@JsonProperty("genesisRLP") final String genesisRLP,
@SuppressWarnings("unused") @JsonProperty("genesisRLP") final String genesisRLP,
@JsonProperty("pre") final Map<String, WorldStateMock.AccountMock> accounts,
@JsonProperty("lastblockhash") final String lastBlockHash,
@JsonProperty("sealEngine") final String sealEngine) {
this.network = network;
this.candidateBlocks = candidateBlocks;
this.genesisBlockHeader = genesisBlockHeader;
this.genesisRLP = genesisRLP == null ? null : BytesValue.fromHexString(genesisRLP);
this.lastBlockHash = Hash.fromHexString(lastBlockHash);
this.worldStateArchive = buildWorldStateArchive(accounts);
this.blockchain = buildBlockchain(genesisBlockHeader);

@ -31,11 +31,8 @@ import java.util.List;
import java.util.concurrent.CompletableFuture;
import com.google.common.annotations.VisibleForTesting;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
public class FullSyncDownloader<C> {
private static final Logger LOG = LogManager.getLogger();
private final ChainDownloader<C> chainDownloader;
private final SynchronizerConfiguration config;
private final ProtocolSchedule<C> protocolSchedule;

@ -149,31 +149,29 @@ public class EthPeerTest {
// Set up stream for headers
final AtomicInteger headersMessageCount = new AtomicInteger(0);
final AtomicInteger headersClosedCount = new AtomicInteger(0);
final ResponseStream headersStream =
peer.getHeadersByHash(gen.hash(), 5, 0, false)
.then(
(closed, msg, p) -> {
if (closed) {
headersClosedCount.incrementAndGet();
} else {
headersMessageCount.incrementAndGet();
assertThat(msg.getCode()).isEqualTo(headersMessage.getData().getCode());
}
});
peer.getHeadersByHash(gen.hash(), 5, 0, false)
.then(
(closed, msg, p) -> {
if (closed) {
headersClosedCount.incrementAndGet();
} else {
headersMessageCount.incrementAndGet();
assertThat(msg.getCode()).isEqualTo(headersMessage.getData().getCode());
}
});
// Set up stream for bodies
final AtomicInteger bodiesMessageCount = new AtomicInteger(0);
final AtomicInteger bodiesClosedCount = new AtomicInteger(0);
final ResponseStream bodiesStream =
peer.getBodies(asList(gen.hash(), gen.hash()))
.then(
(closed, msg, p) -> {
if (closed) {
bodiesClosedCount.incrementAndGet();
} else {
bodiesMessageCount.incrementAndGet();
assertThat(msg.getCode()).isEqualTo(bodiesMessage.getData().getCode());
}
});
peer.getBodies(asList(gen.hash(), gen.hash()))
.then(
(closed, msg, p) -> {
if (closed) {
bodiesClosedCount.incrementAndGet();
} else {
bodiesMessageCount.incrementAndGet();
assertThat(msg.getCode()).isEqualTo(bodiesMessage.getData().getCode());
}
});
// Dispatch some messages and check expectations
peer.dispatch(headersMessage);

@ -29,7 +29,6 @@ import tech.pegasys.pantheon.util.ExceptionUtils;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicReference;
import org.junit.Test;
@ -99,7 +98,6 @@ public class GetBlockFromPeerTaskTest
final Block requestedData = generateDataToBeRequested();
// Execute task and wait for response
final AtomicBoolean done = new AtomicBoolean(false);
final EthTask<PeerTaskResult<Block>> task = createTask(requestedData);
final CompletableFuture<PeerTaskResult<Block>> future = task.run();
respondingEthPeer.respondWhile(responder, () -> !future.isDone());

@ -20,7 +20,6 @@ import static org.mockito.Mockito.spy;
import tech.pegasys.pantheon.ethereum.ProtocolContext;
import tech.pegasys.pantheon.ethereum.chain.Blockchain;
import tech.pegasys.pantheon.ethereum.chain.MutableBlockchain;
import tech.pegasys.pantheon.ethereum.core.BlockDataGenerator;
import tech.pegasys.pantheon.ethereum.core.BlockHeader;
import tech.pegasys.pantheon.ethereum.eth.manager.EthContext;
import tech.pegasys.pantheon.ethereum.eth.manager.EthProtocolManager;
@ -49,7 +48,6 @@ public class FastSyncCheckpointHeaderManagerTest {
protected ProtocolContext<Void> protocolContext;
private SyncState syncState;
private BlockDataGenerator gen;
private BlockchainSetupUtil<Void> localBlockchainSetup;
protected MutableBlockchain localBlockchain;
private BlockchainSetupUtil<Void> otherBlockchainSetup;
@ -61,7 +59,6 @@ public class FastSyncCheckpointHeaderManagerTest {
@Before
public void setupTest() {
gen = new BlockDataGenerator();
localBlockchainSetup = BlockchainSetupUtil.forTesting();
localBlockchain = spy(localBlockchainSetup.getBlockchain());
otherBlockchainSetup = BlockchainSetupUtil.forTesting();

@ -16,8 +16,8 @@ import static org.assertj.core.api.Assertions.assertThat;
import static org.awaitility.Awaitility.await;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.spy;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.internal.verification.VerificationModeFactory.times;
import static tech.pegasys.pantheon.ethereum.core.InMemoryStorageProvider.createInMemoryBlockchain;
import tech.pegasys.pantheon.ethereum.ProtocolContext;

@ -26,13 +26,10 @@ import io.vertx.ext.auth.User;
import net.consensys.cava.toml.Toml;
import net.consensys.cava.toml.TomlParseResult;
import net.consensys.cava.toml.TomlTable;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.security.crypto.bcrypt.BCrypt;
public class TomlAuth implements AuthProvider {
private static final Logger LOG = LogManager.getLogger();
private final Vertx vertx;
private final TomlAuthOptions options;

@ -14,16 +14,13 @@ package tech.pegasys.pantheon.ethereum.jsonrpc.internal.methods;
import tech.pegasys.pantheon.ethereum.core.Address;
import tech.pegasys.pantheon.ethereum.core.PendingTransactions;
import tech.pegasys.pantheon.ethereum.core.Transaction;
import tech.pegasys.pantheon.ethereum.jsonrpc.internal.JsonRpcRequest;
import tech.pegasys.pantheon.ethereum.jsonrpc.internal.parameters.BlockParameter;
import tech.pegasys.pantheon.ethereum.jsonrpc.internal.parameters.JsonRpcParameter;
import tech.pegasys.pantheon.ethereum.jsonrpc.internal.queries.BlockchainQueries;
import tech.pegasys.pantheon.ethereum.jsonrpc.internal.results.Quantity;
import java.util.Optional;
import java.util.OptionalLong;
import java.util.concurrent.atomic.AtomicReference;
public class EthGetTransactionCount extends AbstractBlockParameterMethod {
@ -50,8 +47,6 @@ public class EthGetTransactionCount extends AbstractBlockParameterMethod {
@Override
protected Object pendingResult(final JsonRpcRequest request) {
final Address address = parameters().required(request.getParams(), 0, Address.class);
final AtomicReference<Optional<Transaction>> pendingTransaction =
new AtomicReference<>(Optional.empty());
final OptionalLong pendingNonce = pendingTransactions.getNextNonceForSender(address);
if (pendingNonce.isPresent()) {
return Quantity.create(pendingNonce.getAsLong());

@ -53,7 +53,6 @@ public class AdminJsonRpcHttpServiceTest extends JsonRpcHttpServiceTest {
new PeerInfo(4, CLIENT_VERSION, caps, 60303, BytesValue.fromHexString("0003"));
final InetSocketAddress addr30301 = new InetSocketAddress("localhost", 30301);
final InetSocketAddress addr30302 = new InetSocketAddress("localhost", 30302);
final InetSocketAddress addr30303 = new InetSocketAddress("localhost", 30303);
final InetSocketAddress addr60301 = new InetSocketAddress("localhost", 60301);
final InetSocketAddress addr60302 = new InetSocketAddress("localhost", 60302);
final InetSocketAddress addr60303 = new InetSocketAddress("localhost", 60303);

@ -32,8 +32,8 @@ import org.junit.Test;
public class EthJsonRpcHttpServiceTest extends AbstractEthJsonRpcHttpServiceTest {
private Hash recordPendingTransaction(final int blockNumber, final int transactionIndex) {
final Block block = BLOCKS.get(1);
final Transaction transaction = block.getBody().getTransactions().get(0);
final Block block = BLOCKS.get(blockNumber);
final Transaction transaction = block.getBody().getTransactions().get(transactionIndex);
filterManager.recordPendingTransactionEvent(transaction);
return transaction.hash();
}
@ -82,7 +82,7 @@ public class EthJsonRpcHttpServiceTest extends AbstractEthJsonRpcHttpServiceTest
final ResponseBody body = ethNewPendingTransactionFilter(1).body();
final String result = getResult(body);
body.close();
final Hash transactionHash = recordPendingTransaction(1, 1);
final Hash transactionHash = recordPendingTransaction(1, 0);
final Response resp = ethGetFilterChanges(2, result);
assertThat(resp.code()).isEqualTo(200);

@ -108,38 +108,34 @@ public class EeaGetTransactionReceiptTest {
privateTransaction.getSender(),
privateTransaction.getChainId().getAsInt());
private final Hash hash =
Hash.fromHexString("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa");
private final Hash blockHash =
Hash.fromHexString("bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb");
private final JsonRpcParameter parameters = new JsonRpcParameter();
private final BlockchainQueries blockchainQueries = mock(BlockchainQueries.class);
private final Blockchain blockchain = mock(Blockchain.class);
private final Enclave enclave = mock(Enclave.class);
private PrivacyParameters privacyParameters = mock(PrivacyParameters.class);
private final PrivacyParameters privacyParameters = mock(PrivacyParameters.class);
@Test
public void createsPrivateTransactionReceipt() throws IOException {
Hash mockHash = mock(Hash.class);
BytesValue mockBytesValue = mock(BytesValue.class);
Block chainBlock = mock(Block.class);
long mockLong = 10;
BlockBody blockBody = mock(BlockBody.class);
Transaction mockTx = mock(Transaction.class);
BlockHeader mockBlockHeader = mock(BlockHeader.class);
Log mockLog = mock(Log.class);
Address mockAddress = mock(Address.class);
final Hash mockHash = mock(Hash.class);
final BytesValue mockBytesValue = mock(BytesValue.class);
final Block chainBlock = mock(Block.class);
final long mockLong = 10;
final BlockBody blockBody = mock(BlockBody.class);
final Transaction mockTx = mock(Transaction.class);
final BlockHeader mockBlockHeader = mock(BlockHeader.class);
final Log mockLog = mock(Log.class);
final Address mockAddress = mock(Address.class);
when(mockLog.getLogger()).thenReturn(mockAddress);
LogTopic mockLogTopic = mock(LogTopic.class);
List<LogTopic> listLogTopic = Arrays.asList(mockLogTopic);
final LogTopic mockLogTopic = mock(LogTopic.class);
final List<LogTopic> listLogTopic = Arrays.asList(mockLogTopic);
when(mockLog.getTopics()).thenReturn(listLogTopic);
when(mockLog.getData()).thenReturn(mockBytesValue);
List<Log> mockLogList = Arrays.asList(mockLog);
PrivateTransactionStorage privateTransactionStorage = mock(PrivateTransactionStorage.class);
final List<Log> mockLogList = Arrays.asList(mockLog);
final PrivateTransactionStorage privateTransactionStorage =
mock(PrivateTransactionStorage.class);
doReturn(privateTransactionStorage).when(privacyParameters).getPrivateTransactionStorage();
when(privateTransactionStorage.getEvents(any(Bytes32.class)))
@ -149,7 +145,7 @@ public class EeaGetTransactionReceiptTest {
final EeaGetTransactionReceipt eeaGetTransactionReceipt =
new EeaGetTransactionReceipt(blockchainQueries, enclave, parameters, privacyParameters);
Object[] params = new Object[] {transaction.hash(), "EnclavePublicKey"};
final Object[] params = new Object[] {transaction.hash(), "EnclavePublicKey"};
final JsonRpcRequest request = new JsonRpcRequest("1", "eea_getTransactionReceipt", params);
when(blockchainQueries.getBlockchain()).thenReturn(blockchain);
@ -163,7 +159,7 @@ public class EeaGetTransactionReceiptTest {
.encodeToString(bvrlp.encoded().extractArray())
.getBytes(UTF_8)));
List<Transaction> mockListTx = Arrays.asList(mockTx, transaction);
final List<Transaction> mockListTx = Arrays.asList(mockTx, transaction);
when(blockchain.getChainHeadBlock()).thenReturn(chainBlock);
when(chainBlock.getHash()).thenReturn(mockHash);
when(blockchainQueries.getBlockchain().getChainHeadBlockNumber()).thenReturn(mockLong);

@ -37,7 +37,7 @@ public class WebSocketMethodsFactoryTest {
@Before
public void before() {
jsonRpcMethods.put("eth_unsubscribe", jsonRpcMethod("eth_unsubscribe"));
jsonRpcMethods.put("eth_unsubscribe", jsonRpcMethod());
factory = new WebSocketMethodsFactory(subscriptionManager, jsonRpcMethods);
}
@ -65,8 +65,8 @@ public class WebSocketMethodsFactoryTest {
@Test
public void factoryIncludesJsonRpcMethodsWhenCreatingWebsocketMethods() {
final JsonRpcMethod jsonRpcMethod1 = jsonRpcMethod("method1");
final JsonRpcMethod jsonRpcMethod2 = jsonRpcMethod("method2");
final JsonRpcMethod jsonRpcMethod1 = jsonRpcMethod();
final JsonRpcMethod jsonRpcMethod2 = jsonRpcMethod();
final Map<String, JsonRpcMethod> jsonRpcMethodsMap = new HashMap<>();
jsonRpcMethodsMap.put("method1", jsonRpcMethod1);
@ -78,8 +78,7 @@ public class WebSocketMethodsFactoryTest {
assertThat(methods).containsKeys("method1", "method2");
}
private JsonRpcMethod jsonRpcMethod(final String name) {
final JsonRpcMethod jsonRpcMethod = mock(JsonRpcMethod.class);
return jsonRpcMethod;
private JsonRpcMethod jsonRpcMethod() {
return mock(JsonRpcMethod.class);
}
}

@ -48,9 +48,6 @@ public class RecursivePeerRefreshStateTest {
private final BondingAgent bondingAgent = mock(BondingAgent.class);
private final FindNeighbourDispatcher neighborFinder = mock(FindNeighbourDispatcher.class);
private final MockTimerUtil timerUtil = new MockTimerUtil();
private final String selfEnodeString =
"enode://5f8a80d14311c39f35f516fa664deaaaa13e85b2f7493f37f6144d86991ec012937307647bd3b9a82abe2974e1407241d54947bbb39763a4cac9f77166ad92a0@192.168.0.10:1111";
private final EnodeURL selfEnode = new EnodeURL(selfEnodeString);
private final DiscoveryPeer localPeer = new DiscoveryPeer(createId(9), "127.0.0.9", 9, 9);
private final DiscoveryPeer peer1 = new DiscoveryPeer(createId(1), "127.0.0.1", 1, 1);

@ -20,10 +20,10 @@ dependencyManagement {
dependency 'com.google.auto.service:auto-service:1.0-rc4'
dependency 'com.google.errorprone:javac:9+181-r4173-1'
dependency 'com.google.errorprone:error_prone_check_api:2.3.2'
dependency 'com.google.errorprone:error_prone_core:2.3.2'
dependency 'com.google.errorprone:error_prone_annotation:2.3.2'
dependency 'com.google.errorprone:error_prone_test_helpers:2.3.2'
dependency 'com.google.errorprone:error_prone_check_api:2.3.3'
dependency 'com.google.errorprone:error_prone_core:2.3.3'
dependency 'com.google.errorprone:error_prone_annotation:2.3.3'
dependency 'com.google.errorprone:error_prone_test_helpers:2.3.3'
dependency 'com.google.guava:guava:27.1-jre'

@ -193,7 +193,7 @@ public class PantheonCommand implements DefaultCommandValues, Runnable {
void setBootnodes(final List<String> values) {
try {
bootNodes = values.stream().map((s) -> new EnodeURL(s).toURI()).collect(Collectors.toList());
} catch (IllegalArgumentException e) {
} catch (final IllegalArgumentException e) {
throw new ParameterException(commandLine, e.getMessage());
}
}
@ -327,8 +327,6 @@ public class PantheonCommand implements DefaultCommandValues, Runnable {
"Comma separated list of APIs to enable on JSON-RPC WebSocket service (default: ${DEFAULT-VALUE})")
private final Collection<RpcApi> rpcWsApis = DEFAULT_JSON_RPC_APIS;
private Long rpcWsRefreshDelay;
@Option(
names = {"--rpc-ws-authentication-enabled"},
description =

@ -21,6 +21,9 @@ import picocli.CommandLine;
class StandaloneCommand implements DefaultCommandValues {
// While this variable is never read it is needed for the PicoCLI to create
// the config file option that is read elsewhere.
@SuppressWarnings("UnusedVariable")
@CommandLine.Option(
names = {CONFIG_FILE_OPTION_NAME},
paramLabel = MANDATORY_FILE_FORMAT_HELP,

@ -31,8 +31,6 @@ import java.nio.file.Path;
import java.util.Scanner;
import com.fasterxml.jackson.databind.exc.MismatchedInputException;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import picocli.CommandLine.Command;
import picocli.CommandLine.ExecutionException;
import picocli.CommandLine.Model.CommandSpec;
@ -49,7 +47,6 @@ import picocli.CommandLine.Spec;
public class RLPSubCommand implements Runnable {
public static final String COMMAND_NAME = "rlp";
private static final Logger LOG = LogManager.getLogger();
private final PrintStream out;
private final InputStream in;

@ -53,13 +53,13 @@ public class CommandLineUtilsTest {
final Boolean optionEnabled = true;
@Option(names = {"--option2"})
private final Integer option2 = 2;
final Integer option2 = 2;
@Option(names = {"--option3"})
private final Integer option3 = 3;
final Integer option3 = 3;
@Option(names = {"--option4"})
private final Integer option4 = 4;
final Integer option4 = 4;
}
private static class TestCommandWithDeps extends AbstractTestCommand {
@ -96,7 +96,7 @@ public class CommandLineUtilsTest {
@Test
public void optionsAreNotExpected() {
AbstractTestCommand testCommand = new TestCommandWithDeps(mockLogger);
final AbstractTestCommand testCommand = new TestCommandWithDeps(mockLogger);
testCommand.commandLine.parseWithHandlers(
new RunLast(),
defaultExceptionHandler(),
@ -109,11 +109,16 @@ public class CommandLineUtilsTest {
"--option4",
"40");
verifyOptionsConstraintLoggerCall(mockLogger, "--option2 and --option3", "--option-enabled");
assertThat(testCommand.optionEnabled).isFalse();
assertThat(testCommand.option2).isEqualTo(20);
assertThat(testCommand.option3).isEqualTo(30);
assertThat(testCommand.option4).isEqualTo(40);
}
@Test
public void optionIsNotExpected() {
AbstractTestCommand testCommand = new TestCommandWithDeps(mockLogger);
final AbstractTestCommand testCommand = new TestCommandWithDeps(mockLogger);
testCommand.commandLine.parseWithHandlers(
new RunLast(),
defaultExceptionHandler(),
@ -124,11 +129,16 @@ public class CommandLineUtilsTest {
"--option4",
"40");
verifyOptionsConstraintLoggerCall(mockLogger, "--option2", "--option-enabled");
assertThat(testCommand.optionEnabled).isFalse();
assertThat(testCommand.option2).isEqualTo(20);
assertThat(testCommand.option3).isEqualTo(3);
assertThat(testCommand.option4).isEqualTo(40);
}
@Test
public void optionsAreExpected() {
AbstractTestCommand testCommand = new TestCommandWithDeps(mockLogger);
final AbstractTestCommand testCommand = new TestCommandWithDeps(mockLogger);
testCommand.commandLine.parseWithHandlers(
new RunLast(),
defaultExceptionHandler(),
@ -139,11 +149,15 @@ public class CommandLineUtilsTest {
"--option4",
"40");
verifyNoMoreInteractions(mockLogger);
assertThat(testCommand.optionEnabled).isTrue();
assertThat(testCommand.option2).isEqualTo(20);
assertThat(testCommand.option3).isEqualTo(30);
assertThat(testCommand.option4).isEqualTo(40);
}
@Test
public void noDependencies() {
AbstractTestCommand testCommand = new TestCommandWithoutDeps(mockLogger);
final AbstractTestCommand testCommand = new TestCommandWithoutDeps(mockLogger);
testCommand.commandLine.parseWithHandlers(
new RunLast(),
defaultExceptionHandler(),
@ -156,6 +170,10 @@ public class CommandLineUtilsTest {
"--option4",
"40");
verifyNoMoreInteractions(mockLogger);
assertThat(testCommand.optionEnabled).isFalse();
assertThat(testCommand.option2).isEqualTo(20);
assertThat(testCommand.option3).isEqualTo(30);
assertThat(testCommand.option4).isEqualTo(40);
}
/**
@ -170,7 +188,7 @@ public class CommandLineUtilsTest {
private void verifyOptionsConstraintLoggerCall(
final Logger logger, final String dependentOptions, final String mainOption) {
ArgumentCaptor<String> stringArgumentCaptor = ArgumentCaptor.forClass(String.class);
final ArgumentCaptor<String> stringArgumentCaptor = ArgumentCaptor.forClass(String.class);
verify(logger)
.warn(

@ -21,7 +21,7 @@ public class PasswordSubCommandTest extends CommandTestAbstract {
@Test
public void passwordSubCommandExistAnbHaveSubCommands() {
CommandSpec spec = parseCommand();
final CommandSpec spec = parseCommand();
assertThat(spec.subcommands()).containsKeys("password");
assertThat(spec.subcommands().get("password").getSubcommands()).containsKeys("hash");
assertThat(commandOutput.toString()).isEmpty();
@ -30,7 +30,6 @@ public class PasswordSubCommandTest extends CommandTestAbstract {
@Test
public void passwordSubCommandExists() {
CommandSpec spec = parseCommand();
parseCommand("password");
assertThat(commandOutput.toString()).contains("This command provides password related actions");

@ -16,7 +16,6 @@ import static org.assertj.core.api.Assertions.assertThatCode;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import com.google.common.io.Resources;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
@ -27,7 +26,6 @@ import picocli.CommandLine.ParameterException;
@RunWith(MockitoJUnitRunner.StrictStubs.class)
public class RpcAuthFileValidatorTest {
private RpcAuthFileValidator rpcAuthFileValidator;
private static final String CORRECT_TOML = "auth_correct.toml";
private static final String DUPLICATE_USER_TOML = "auth_duplicate_user.toml";
private static final String INVALID_TOML = "auth_invalid.toml";
@ -35,11 +33,6 @@ public class RpcAuthFileValidatorTest {
private static final String NO_PASSWORD_TOML = "auth_no_password.toml";
@Mock CommandLine commandLine;
@Before
public void setUp() {
rpcAuthFileValidator = new RpcAuthFileValidator();
}
@Test
public void shouldPassWhenCorrectTOML() {
assertThatCode(

@ -21,20 +21,13 @@ import tech.pegasys.pantheon.util.bytes.BytesValue;
import java.io.Closeable;
import java.nio.file.Path;
import java.util.Iterator;
import java.util.NoSuchElementException;
import java.util.Optional;
import java.util.Spliterator;
import java.util.Spliterators;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.stream.Stream;
import java.util.stream.StreamSupport;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.rocksdb.Options;
import org.rocksdb.RocksDBException;
import org.rocksdb.RocksIterator;
import org.rocksdb.TransactionDB;
import org.rocksdb.TransactionDBOptions;
import org.rocksdb.WriteOptions;
@ -138,61 +131,6 @@ public class RocksDbKeyValueStorage implements KeyValueStorage, Closeable {
}
}
/**
* Iterates over rocksDB key-value entries. Reads from a db snapshot implicitly taken when the
* RocksIterator passed to the constructor was created.
*
* <p>Implements {@link AutoCloseable} and can be used with try-with-resources construct. When
* transformed to a stream (see {@link #toStream}), iterator is automatically closed when the
* stream is closed.
*/
private static class RocksDbEntryIterator implements Iterator<Entry>, AutoCloseable {
private final RocksIterator rocksIt;
private volatile boolean closed = false;
RocksDbEntryIterator(final RocksIterator rocksIt) {
this.rocksIt = rocksIt;
}
@Override
public boolean hasNext() {
return rocksIt.isValid();
}
@Override
public Entry next() {
if (closed) {
throw new IllegalStateException("Attempt to read from a closed RocksDbEntryIterator.");
}
try {
rocksIt.status();
} catch (final RocksDBException e) {
LOG.error("RocksDbEntryIterator encountered a problem while iterating.", e);
}
if (!hasNext()) {
throw new NoSuchElementException();
}
final Entry entry =
Entry.create(BytesValue.wrap(rocksIt.key()), BytesValue.wrap(rocksIt.value()));
rocksIt.next();
return entry;
}
Stream<Entry> toStream() {
final Spliterator<Entry> split =
Spliterators.spliteratorUnknownSize(
this, Spliterator.IMMUTABLE | Spliterator.DISTINCT | Spliterator.NONNULL);
return StreamSupport.stream(split, false).onClose(this::close);
}
@Override
public void close() {
rocksIt.close();
closed = true;
}
}
private class RocksDbTransaction extends AbstractTransaction {
private final org.rocksdb.Transaction innerTx;
private final WriteOptions options;

@ -203,8 +203,4 @@ public class CachingTaskCollectionTest {
}
return tasks;
}
private interface TaskCollectionSupplier {
TaskCollection<BytesValue> get() throws Exception;
}
}

@ -94,6 +94,7 @@ public class JsonTestParameters<S, T> {
// Note that we don't really use this field as of now, but as this is the actual type of the final
// spec used by tests, it feels "right" to have it passed explicitly at construction and having it
// around could prove useful later.
@SuppressWarnings({"FieldCanBeLocal", "unused"})
private final Class<T> testCaseSpec;
private final Set<String> fileExcludes = new HashSet<>();
@ -101,7 +102,6 @@ public class JsonTestParameters<S, T> {
private final List<Predicate<String>> testIncludes = new ArrayList<>();
private final List<Predicate<String>> testBlackList = new ArrayList<>();
private boolean blackListedAll;
private JsonTestParameters(final Class<S> jsonFileMappedType, final Class<T> testCaseSpec) {
this.jsonFileMappedType = jsonFileMappedType;
@ -122,6 +122,7 @@ public class JsonTestParameters<S, T> {
return new JsonTestParameters<>(jsonFileMappedType, testCaseSpec);
}
@SuppressWarnings("unused")
public JsonTestParameters<S, T> excludeFiles(final String... filenames) {
fileExcludes.addAll(Arrays.asList(filenames));
return this;
@ -134,6 +135,7 @@ public class JsonTestParameters<S, T> {
}
}
@SuppressWarnings({"unused"})
public JsonTestParameters<S, T> includeTests(final String... patterns) {
addPatterns(patterns, testIncludes);
return this;
@ -146,7 +148,6 @@ public class JsonTestParameters<S, T> {
public JsonTestParameters<S, T> blacklistAll() {
testBlackList.add(t -> true);
blackListedAll = true;
return this;
}

@ -32,10 +32,6 @@ public class BytesValueTest {
@Rule public ExpectedException thrown = ExpectedException.none();
private static BytesValue h(final String hex) {
return fromHexString(hex);
}
/** Checks that modifying a wrapped array modifies the value itself. */
@Test
public void wrapReflectsUpdates() {

Loading…
Cancel
Save