Errorprone version upgrade (#1096)

Upgrade to ErrorProne 2.4.0

* public constructors on abstract classes are removed
* Javadoc must have meaningfull documentation
* lambdas should not be variables
* Added to the list of confusing inner class names (Entry and Type)
* no assert keyword in tests
* Obsolete JDK classes produce errors now

Signed-off-by: Danno Ferrin <danno.ferrin@gmail.com>
pull/1105/head
Danno Ferrin 5 years ago committed by GitHub
parent b7c6ddf023
commit 256e5c914d
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
  1. 3
      acceptance-tests/dsl/src/main/java/org/hyperledger/besu/tests/acceptance/dsl/condition/clique/CliqueConditions.java
  2. 3
      acceptance-tests/dsl/src/main/java/org/hyperledger/besu/tests/acceptance/dsl/condition/ibft2/Ibft2Conditions.java
  3. 4
      acceptance-tests/dsl/src/main/java/org/hyperledger/besu/tests/acceptance/dsl/transaction/login/LoginRequestFactory.java
  4. 1
      besu/src/main/java/org/hyperledger/besu/Runner.java
  5. 6
      besu/src/main/java/org/hyperledger/besu/cli/options/CLIOptions.java
  6. 8
      besu/src/main/java/org/hyperledger/besu/cli/subcommands/operator/GenerateBlockchainConfig.java
  7. 2
      besu/src/test/java/org/hyperledger/besu/chainimport/JsonBlockImporterTest.java
  8. 2
      besu/src/test/java/org/hyperledger/besu/cli/operator/OperatorSubCommandTest.java
  9. 3
      besu/src/test/java/org/hyperledger/besu/util/StringUtilsTest.java
  10. 4
      consensus/common/src/main/java/org/hyperledger/besu/consensus/common/VoteTally.java
  11. 2
      consensus/common/src/main/java/org/hyperledger/besu/consensus/common/jsonrpc/AbstractGetSignerMetricsMethod.java
  12. 4
      consensus/ibft/src/main/java/org/hyperledger/besu/consensus/ibft/SizeLimitedMap.java
  13. 3
      consensus/ibft/src/main/java/org/hyperledger/besu/consensus/ibft/blockcreation/ProposerSelector.java
  14. 4
      consensus/ibft/src/main/java/org/hyperledger/besu/consensus/ibft/headervalidationrules/IbftValidatorsValidationRule.java
  15. 5
      consensus/ibft/src/main/java/org/hyperledger/besu/consensus/ibft/ibftevent/BlockTimerExpiry.java
  16. 5
      consensus/ibft/src/main/java/org/hyperledger/besu/consensus/ibft/ibftevent/NewChainHead.java
  17. 4
      consensus/ibft/src/test/java/org/hyperledger/besu/consensus/ibft/IbftEventQueueTest.java
  18. 22
      consensus/ibft/src/test/java/org/hyperledger/besu/consensus/ibft/blockcreation/ProposerSelectorTest.java
  19. 4
      consensus/ibftlegacy/src/main/java/org/hyperledger/besu/consensus/ibftlegacy/headervalidationrules/IbftExtraDataValidationRule.java
  20. 10
      crypto/src/test/java/org/hyperledger/besu/crypto/SECP256K1Test.java
  21. 1
      enclave/src/integration-test/java/org/hyperledger/besu/enclave/TlsHelpers.java
  22. 2
      enclave/src/main/java/org/hyperledger/besu/enclave/types/SendRequest.java
  23. 2
      errorprone-checks/src/main/java/org/hyperledger/errorpronechecks/BannedMethod.java
  24. 2
      ethereum/api/src/main/java/org/hyperledger/besu/ethereum/api/jsonrpc/internal/methods/AdminModifyPeer.java
  25. 2
      ethereum/api/src/main/java/org/hyperledger/besu/ethereum/api/jsonrpc/internal/results/TransactionReceiptResult.java
  26. 2
      ethereum/api/src/main/java/org/hyperledger/besu/ethereum/api/jsonrpc/internal/results/privacy/PrivateTransactionResult.java
  27. 6
      ethereum/api/src/main/java/org/hyperledger/besu/ethereum/api/jsonrpc/methods/PrivacyApiGroupJsonRpcMethods.java
  28. 1
      ethereum/api/src/test-support/java/org/hyperledger/besu/ethereum/api/tls/SelfSignedP12Certificate.java
  29. 9
      ethereum/api/src/test/java/org/hyperledger/besu/ethereum/api/jsonrpc/internal/results/tracing/flat/RewardTraceGeneratorTest.java
  30. 6
      ethereum/blockcreation/src/main/java/org/hyperledger/besu/ethereum/blockcreation/AbstractBlockCreator.java
  31. 2
      ethereum/blockcreation/src/main/java/org/hyperledger/besu/ethereum/blockcreation/AbstractBlockScheduler.java
  32. 2
      ethereum/blockcreation/src/main/java/org/hyperledger/besu/ethereum/blockcreation/AbstractMinerExecutor.java
  33. 2
      ethereum/blockcreation/src/main/java/org/hyperledger/besu/ethereum/blockcreation/AbstractMiningCoordinator.java
  34. 6
      ethereum/blockcreation/src/main/java/org/hyperledger/besu/ethereum/blockcreation/BlockTransactionSelector.java
  35. 24
      ethereum/blockcreation/src/test/java/org/hyperledger/besu/ethereum/blockcreation/BlockTransactionSelectorTest.java
  36. 10
      ethereum/core/src/integration-test/java/org/hyperledger/besu/ethereum/vm/TraceTransactionIntegrationTest.java
  37. 8
      ethereum/core/src/main/java/org/hyperledger/besu/ethereum/chain/Blockchain.java
  38. 3
      ethereum/core/src/main/java/org/hyperledger/besu/ethereum/core/AbstractWorldUpdater.java
  39. 2
      ethereum/core/src/main/java/org/hyperledger/besu/ethereum/core/Address.java
  40. 2
      ethereum/core/src/main/java/org/hyperledger/besu/ethereum/core/Difficulty.java
  41. 2
      ethereum/core/src/main/java/org/hyperledger/besu/ethereum/core/Gas.java
  42. 2
      ethereum/core/src/main/java/org/hyperledger/besu/ethereum/core/Synchronizer.java
  43. 2
      ethereum/core/src/main/java/org/hyperledger/besu/ethereum/core/Wei.java
  44. 6
      ethereum/core/src/main/java/org/hyperledger/besu/ethereum/core/WorldUpdater.java
  45. 4
      ethereum/core/src/main/java/org/hyperledger/besu/ethereum/mainnet/AbstractBlockProcessor.java
  46. 2
      ethereum/core/src/main/java/org/hyperledger/besu/ethereum/mainnet/AbstractPrecompiledContract.java
  47. 2
      ethereum/core/src/main/java/org/hyperledger/besu/ethereum/mainnet/EthHasher.java
  48. 2
      ethereum/core/src/main/java/org/hyperledger/besu/ethereum/mainnet/MainnetBlockProcessor.java
  49. 6
      ethereum/core/src/main/java/org/hyperledger/besu/ethereum/mainnet/ProtocolSpec.java
  50. 6
      ethereum/core/src/main/java/org/hyperledger/besu/ethereum/mainnet/ProtocolSpecBuilder.java
  51. 13
      ethereum/core/src/main/java/org/hyperledger/besu/ethereum/privacy/DefaultPrivacyController.java
  52. 5
      ethereum/core/src/main/java/org/hyperledger/besu/ethereum/privacy/PrivateGroupRehydrationBlockProcessor.java
  53. 2
      ethereum/core/src/main/java/org/hyperledger/besu/ethereum/privacy/markertransaction/PrivateMarkerTransactionFactory.java
  54. 5
      ethereum/core/src/main/java/org/hyperledger/besu/ethereum/privacy/storage/migration/PrivateMigrationBlockProcessor.java
  55. 3
      ethereum/core/src/main/java/org/hyperledger/besu/ethereum/proof/WorldStateProofProvider.java
  56. 2
      ethereum/core/src/main/java/org/hyperledger/besu/ethereum/vm/AbstractCallOperation.java
  57. 2
      ethereum/core/src/main/java/org/hyperledger/besu/ethereum/vm/AbstractOperation.java
  58. 6
      ethereum/core/src/main/java/org/hyperledger/besu/ethereum/vm/Code.java
  59. 2
      ethereum/core/src/main/java/org/hyperledger/besu/ethereum/vm/Operation.java
  60. 2
      ethereum/core/src/main/java/org/hyperledger/besu/ethereum/vm/operations/AbstractCreateOperation.java
  61. 6
      ethereum/core/src/test-support/java/org/hyperledger/besu/ethereum/core/BlockDataGenerator.java
  62. 5
      ethereum/core/src/test-support/java/org/hyperledger/besu/ethereum/core/MessageFrameTestFixture.java
  63. 4
      ethereum/core/src/test/java/org/hyperledger/besu/ethereum/mainnet/MainnetBlockProcessorTest.java
  64. 24
      ethereum/core/src/test/java/org/hyperledger/besu/ethereum/privacy/DefaultPrivacyControllerTest.java
  65. 31
      ethereum/core/src/test/java/org/hyperledger/besu/ethereum/privacy/MultiTenancyPrivacyControllerTest.java
  66. 18
      ethereum/eth/src/main/java/org/hyperledger/besu/ethereum/eth/manager/EthPeer.java
  67. 2
      ethereum/eth/src/main/java/org/hyperledger/besu/ethereum/eth/manager/task/AbstractRetryingPeerTask.java
  68. 32
      ethereum/eth/src/main/java/org/hyperledger/besu/ethereum/eth/messages/StatusMessage.java
  69. 2
      ethereum/eth/src/main/java/org/hyperledger/besu/ethereum/eth/peervalidation/AbstractPeerBlockValidator.java
  70. 2
      ethereum/eth/src/main/java/org/hyperledger/besu/ethereum/eth/peervalidation/PeerValidator.java
  71. 2
      ethereum/eth/src/main/java/org/hyperledger/besu/ethereum/eth/sync/SyncTargetManager.java
  72. 4
      ethereum/eth/src/main/java/org/hyperledger/besu/ethereum/eth/transactions/PendingTransactions.java
  73. 8
      ethereum/eth/src/main/java/org/hyperledger/besu/ethereum/eth/transactions/TransactionsForSenderInfo.java
  74. 2
      ethereum/eth/src/test/java/org/hyperledger/besu/ethereum/eth/manager/EthProtocolManagerTest.java
  75. 1
      ethereum/eth/src/test/java/org/hyperledger/besu/ethereum/eth/manager/MockEthTask.java
  76. 2
      ethereum/eth/src/test/java/org/hyperledger/besu/ethereum/eth/manager/ethtaskutils/AbstractMessageTaskTest.java
  77. 4
      ethereum/eth/src/test/java/org/hyperledger/besu/ethereum/eth/manager/ethtaskutils/RetryingMessageTaskTest.java
  78. 2
      ethereum/eth/src/test/java/org/hyperledger/besu/ethereum/eth/sync/tasks/DetermineCommonAncestorTaskTest.java
  79. 3
      ethereum/eth/src/test/java/org/hyperledger/besu/ethereum/eth/sync/worldstate/WorldStateDownloaderTest.java
  80. 2
      ethereum/p2p/src/main/java/org/hyperledger/besu/ethereum/p2p/discovery/PeerDiscoveryAgent.java
  81. 4
      ethereum/p2p/src/main/java/org/hyperledger/besu/ethereum/p2p/discovery/internal/RecursivePeerRefreshState.java
  82. 6
      ethereum/p2p/src/main/java/org/hyperledger/besu/ethereum/p2p/network/P2PNetwork.java
  83. 2
      ethereum/p2p/src/main/java/org/hyperledger/besu/ethereum/p2p/peers/EnodeURL.java
  84. 4
      ethereum/p2p/src/main/java/org/hyperledger/besu/ethereum/p2p/peers/LocalNode.java
  85. 6
      ethereum/p2p/src/main/java/org/hyperledger/besu/ethereum/p2p/peers/Peer.java
  86. 2
      ethereum/p2p/src/main/java/org/hyperledger/besu/ethereum/p2p/permissions/PermissionsUpdateCallback.java
  87. 2
      ethereum/p2p/src/main/java/org/hyperledger/besu/ethereum/p2p/rlpx/connections/AbstractPeerConnection.java
  88. 18
      ethereum/p2p/src/main/java/org/hyperledger/besu/ethereum/p2p/rlpx/connections/PeerConnection.java
  89. 2
      ethereum/p2p/src/main/java/org/hyperledger/besu/ethereum/p2p/rlpx/framing/Framer.java
  90. 2
      ethereum/p2p/src/main/java/org/hyperledger/besu/ethereum/p2p/rlpx/handshake/ecies/InitiatorHandshakeMessageV1.java
  91. 6
      ethereum/p2p/src/main/java/org/hyperledger/besu/ethereum/p2p/rlpx/wire/CapabilityMultiplexer.java
  92. 19
      ethereum/p2p/src/test/java/org/hyperledger/besu/ethereum/p2p/discovery/internal/PeerDiscoveryControllerTest.java
  93. 4
      ethereum/p2p/src/test/java/org/hyperledger/besu/ethereum/p2p/rlpx/connections/MockConnectionInitializer.java
  94. 9
      ethereum/permissioning/src/main/java/org/hyperledger/besu/ethereum/permissioning/PermissioningConfigurationBuilder.java
  95. 6
      ethereum/trie/src/main/java/org/hyperledger/besu/ethereum/trie/Node.java
  96. 10
      ethereum/trie/src/test/java/org/hyperledger/besu/ethereum/trie/TrieIteratorTest.java
  97. 8
      gradle/versions.gradle
  98. 5
      metrics/core/src/main/java/org/hyperledger/besu/metrics/prometheus/PrometheusMetricsSystem.java
  99. 2
      plugin-api/build.gradle
  100. 12
      plugin-api/src/main/java/org/hyperledger/besu/plugin/data/BlockBody.java
  101. Some files were not shown because too many files have changed in this diff Show More

@ -33,7 +33,6 @@ import java.math.BigInteger;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;
import java.util.stream.Collectors;
import com.google.common.collect.ImmutableMap;
@ -126,7 +125,7 @@ public class CliqueConditions {
public Condition build() {
final Map<Address, Boolean> proposalsAsAddress =
this.proposals.entrySet().stream()
.collect(Collectors.toMap(p -> p.getKey().getAddress(), Entry::getValue));
.collect(Collectors.toMap(p -> p.getKey().getAddress(), Map.Entry::getValue));
return new ExpectProposals(clique, proposalsAsAddress);
}
}

@ -27,7 +27,6 @@ import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.stream.Collectors;
import com.google.common.collect.ImmutableMap;
@ -88,7 +87,7 @@ public class Ibft2Conditions {
public Condition build() {
final Map<Address, Boolean> proposalsAsAddress =
this.proposals.entrySet().stream()
.collect(Collectors.toMap(p -> p.getKey().getAddress(), Entry::getValue));
.collect(Collectors.toMap(p -> p.getKey().getAddress(), Map.Entry::getValue));
return new ExpectProposals(ibft, proposalsAsAddress);
}
}

@ -29,7 +29,6 @@ import okhttp3.ResponseBody;
public class LoginRequestFactory {
private static final MediaType JSON = MediaType.parse("application/json; charset=utf-8");
private static final String AUTHENTICATION_REQUEST = "{\"username\":\"%s\",\"password\":\"%s\"}";
private static final String LOGIN_PATH = "/login";
private final String contextRootUrl;
@ -74,7 +73,8 @@ public class LoginRequestFactory {
private Request loginRequest(final String username, final String password) {
final RequestBody requestBody =
RequestBody.create(JSON, String.format(AUTHENTICATION_REQUEST, username, password));
RequestBody.create(
JSON, String.format("{\"username\":\"%s\",\"password\":\"%s\"}", username, password));
return new Request.Builder().post(requestBody).url(loginUri()).build();
}

@ -271,6 +271,7 @@ public class Runner implements AutoCloseable {
try {
pid = Long.toString(ProcessHandle.current().pid());
} catch (Throwable t) {
LOG.error("Error retrieving PID", t);
}
try {
Files.write(

@ -30,6 +30,10 @@ public interface CLIOptions<T> {
*/
T toDomainObject();
/** @return The list of CLI options corresponding to this class. */
/**
* Return The list of CLI options corresponding to this class.
*
* @return The list of CLI options corresponding to this class.
*/
List<String> getCLIOptions();
}

@ -194,7 +194,7 @@ class GenerateBlockchainConfig implements Runnable {
*
* @param publicKey The public key.
* @param privateKey The private key. No file is created if privateKey is NULL.
* @throws IOException
* @throws IOException If the file cannot be written or accessed.
*/
private void writeKeypair(
final SECP256K1.PublicKey publicKey, final SECP256K1.PrivateKey privateKey)
@ -231,7 +231,7 @@ class GenerateBlockchainConfig implements Runnable {
/**
* Parses the root configuration file and related sub elements.
*
* @throws IOException
* @throws IOException If the file cannot be read or accessed.
*/
private void parseConfig() throws IOException {
final String configString =
@ -251,7 +251,7 @@ class GenerateBlockchainConfig implements Runnable {
/**
* Checks if the output directory exists.
*
* @throws IOException
* @throws IOException If the cannot be accessed or created.
*/
private void handleOutputDirectory() throws IOException {
checkNotNull(outputDirectory);
@ -274,7 +274,7 @@ class GenerateBlockchainConfig implements Runnable {
* @param directory The directory to write the file to.
* @param fileName The name of the output file.
* @param genesis The genesis content.
* @throws IOException
* @throws IOException If the genesis file cannot be written or accessed.
*/
private void writeGenesisFile(
final File directory, final String fileName, final ObjectNode genesis) throws IOException {

@ -66,7 +66,7 @@ public abstract class JsonBlockImporterTest {
protected final GenesisConfigFile genesisConfigFile;
protected final boolean isEthash;
public JsonBlockImporterTest(final String consensusEngine) throws IOException {
protected JsonBlockImporterTest(final String consensusEngine) throws IOException {
this.consensusEngine = consensusEngine;
final String genesisData = getFileContents("genesis.json");
this.genesisConfigFile = GenesisConfigFile.fromConfig(genesisData);

@ -229,7 +229,7 @@ public class OperatorSubCommandTest extends CommandTestAbstract {
final File keysDirectory = new File(expectedKeysPath.toUri());
assertThat(keysDirectory).exists();
final File[] nodesKeysFolders = keysDirectory.listFiles();
assert nodesKeysFolders != null;
assertThat(nodesKeysFolders).isNotNull();
if (generate) {
final JsonFactory jsonFactory = new JsonFactory();
final JsonParser jp = jsonFactory.createParser(configFilePath);

@ -20,7 +20,6 @@ import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.stream.Collectors;
import org.junit.Test;
@ -35,7 +34,7 @@ public class StringUtilsTest {
testCases.put(Arrays.asList("item1", "item2"), "item1 and item2");
testCases.put(Arrays.asList("item1", "item2", "item3"), "item1, item2 and item3");
for (Entry<List<String>, String> entry : testCases.entrySet()) {
for (Map.Entry<List<String>, String> entry : testCases.entrySet()) {
String joinedResult =
entry.getKey().stream()
.collect(

@ -21,9 +21,9 @@ import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.NavigableSet;
import java.util.Optional;
import java.util.Set;
import java.util.SortedSet;
import java.util.TreeSet;
import com.google.common.collect.Maps;
@ -31,7 +31,7 @@ import com.google.common.collect.Maps;
/** Tracks the current list of validators and votes to add or drop validators. */
public class VoteTally implements ValidatorProvider {
private final SortedSet<Address> currentValidators;
private final NavigableSet<Address> currentValidators;
private final Map<Address, Set<Address>> addVotesBySubject;
private final Map<Address, Set<Address>> removeVotesBySubject;

@ -41,7 +41,7 @@ public abstract class AbstractGetSignerMetricsMethod {
private final BlockInterface blockInterface;
private final BlockchainQueries blockchainQueries;
public AbstractGetSignerMetricsMethod(
protected AbstractGetSignerMetricsMethod(
final VoteTallyCache voteTallyCache,
final BlockInterface blockInterface,
final BlockchainQueries blockchainQueries) {

@ -15,7 +15,7 @@
package org.hyperledger.besu.consensus.ibft;
import java.util.LinkedHashMap;
import java.util.Map.Entry;
import java.util.Map;
/**
* Map that is limited to a specified size and will evict oldest entries when the size limit is
@ -29,7 +29,7 @@ public class SizeLimitedMap<K, V> extends LinkedHashMap<K, V> {
}
@Override
protected boolean removeEldestEntry(final Entry<K, V> ignored) {
protected boolean removeEldestEntry(final Map.Entry<K, V> ignored) {
return size() > maxEntries;
}
}

@ -29,7 +29,6 @@ import java.util.Collection;
import java.util.List;
import java.util.NavigableSet;
import java.util.Optional;
import java.util.SortedSet;
import java.util.TreeSet;
import org.apache.logging.log4j.LogManager;
@ -111,7 +110,7 @@ public class ProposerSelector {
final Collection<Address> validatorsForRound,
final ConsensusRoundIdentifier roundIdentifier) {
final NavigableSet<Address> validatorSet = new TreeSet<>(validatorsForRound);
final SortedSet<Address> latterValidators = validatorSet.tailSet(prevBlockProposer, false);
final NavigableSet<Address> latterValidators = validatorSet.tailSet(prevBlockProposer, false);
final Address nextProposer;
if (latterValidators.isEmpty()) {
// i.e. prevBlockProposer was at the end of the validator list, so the right validator for

@ -24,7 +24,7 @@ import org.hyperledger.besu.ethereum.mainnet.AttachedBlockHeaderValidationRule;
import org.hyperledger.besu.ethereum.rlp.RLPException;
import java.util.Collection;
import java.util.SortedSet;
import java.util.NavigableSet;
import java.util.TreeSet;
import com.google.common.collect.Iterables;
@ -50,7 +50,7 @@ public class IbftValidatorsValidationRule implements AttachedBlockHeaderValidati
.getVoteTallyAfterBlock(parent);
final IbftExtraData ibftExtraData = IbftExtraData.decode(header);
final SortedSet<Address> sortedReportedValidators =
final NavigableSet<Address> sortedReportedValidators =
new TreeSet<>(ibftExtraData.getValidators());
if (!Iterables.elementsEqual(ibftExtraData.getValidators(), sortedReportedValidators)) {

@ -15,7 +15,6 @@
package org.hyperledger.besu.consensus.ibft.ibftevent;
import org.hyperledger.besu.consensus.ibft.ConsensusRoundIdentifier;
import org.hyperledger.besu.consensus.ibft.ibftevent.IbftEvents.Type;
import java.util.Objects;
@ -35,8 +34,8 @@ public final class BlockTimerExpiry implements IbftEvent {
}
@Override
public Type getType() {
return Type.BLOCK_TIMER_EXPIRY;
public IbftEvents.Type getType() {
return IbftEvents.Type.BLOCK_TIMER_EXPIRY;
}
public ConsensusRoundIdentifier getRoundIndentifier() {

@ -14,7 +14,6 @@
*/
package org.hyperledger.besu.consensus.ibft.ibftevent;
import org.hyperledger.besu.consensus.ibft.ibftevent.IbftEvents.Type;
import org.hyperledger.besu.ethereum.core.BlockHeader;
import java.util.Objects;
@ -35,8 +34,8 @@ public final class NewChainHead implements IbftEvent {
}
@Override
public Type getType() {
return Type.NEW_CHAIN_HEAD;
public IbftEvents.Type getType() {
return IbftEvents.Type.NEW_CHAIN_HEAD;
}
@Override

@ -18,7 +18,7 @@ import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatCode;
import org.hyperledger.besu.consensus.ibft.ibftevent.IbftEvent;
import org.hyperledger.besu.consensus.ibft.ibftevent.IbftEvents.Type;
import org.hyperledger.besu.consensus.ibft.ibftevent.IbftEvents;
import java.util.ArrayList;
import java.util.List;
@ -31,7 +31,7 @@ public class IbftEventQueueTest {
private static class DummyIbftEvent implements IbftEvent {
@Override
public Type getType() {
public IbftEvents.Type getType() {
return null;
}
}

@ -31,11 +31,11 @@ import org.hyperledger.besu.ethereum.core.AddressHelpers;
import org.hyperledger.besu.ethereum.core.BlockHeader;
import org.hyperledger.besu.ethereum.core.BlockHeaderTestFixture;
import java.util.ArrayList;
import java.util.Collection;
import java.util.LinkedList;
import java.util.List;
import java.util.Optional;
import com.google.common.collect.Lists;
import org.junit.Test;
public class ProposerSelectorTest {
@ -69,9 +69,9 @@ public class ProposerSelectorTest {
* @param countHigher The number of validators which have a lower address than localAddr
* @return A sorted list of validators which matches parameters (including the localAddr).
*/
private LinkedList<Address> createValidatorList(
private List<Address> createValidatorList(
final Address localAddr, final int countLower, final int countHigher) {
final LinkedList<Address> result = Lists.newLinkedList();
final List<Address> result = new ArrayList<>();
// Note: Order of this list is irrelevant, is sorted by value later.
result.add(localAddr);
@ -93,7 +93,7 @@ public class ProposerSelectorTest {
final long PREV_BLOCK_NUMBER = 2;
final Address localAddr = AddressHelpers.ofValue(10); // arbitrarily selected
final LinkedList<Address> validatorList = createValidatorList(localAddr, 0, 4);
final List<Address> validatorList = createValidatorList(localAddr, 0, 4);
final Blockchain blockchain =
createMockedBlockChainWithHeadOf(PREV_BLOCK_NUMBER, localAddr, validatorList);
@ -112,7 +112,7 @@ public class ProposerSelectorTest {
final long PREV_BLOCK_NUMBER = 2;
final Address localAddr = AddressHelpers.ofValue(10); // arbitrarily selected
final LinkedList<Address> validatorList = createValidatorList(localAddr, 4, 0);
final List<Address> validatorList = createValidatorList(localAddr, 4, 0);
final Blockchain blockchain =
createMockedBlockChainWithHeadOf(PREV_BLOCK_NUMBER, localAddr, validatorList);
@ -132,7 +132,7 @@ public class ProposerSelectorTest {
final ConsensusRoundIdentifier roundId = new ConsensusRoundIdentifier(PREV_BLOCK_NUMBER + 1, 0);
final Address localAddr = AddressHelpers.ofValue(10); // arbitrarily selected
final LinkedList<Address> validatorList = createValidatorList(localAddr, 4, 0);
final List<Address> validatorList = createValidatorList(localAddr, 4, 0);
final Blockchain blockchain =
createMockedBlockChainWithHeadOf(PREV_BLOCK_NUMBER, localAddr, validatorList);
@ -150,7 +150,7 @@ public class ProposerSelectorTest {
final Address localAddr = AddressHelpers.ofValue(10); // arbitrarily selected
final LinkedList<Address> validatorList = createValidatorList(localAddr, 4, 0);
final List<Address> validatorList = createValidatorList(localAddr, 4, 0);
final Blockchain blockchain =
createMockedBlockChainWithHeadOf(PREV_BLOCK_NUMBER, localAddr, validatorList);
@ -174,7 +174,7 @@ public class ProposerSelectorTest {
// LocalAddr will be in index 2 - the next proposer will also be in 2 (as prev proposer is
// removed)
final LinkedList<Address> validatorList = createValidatorList(localAddr, 2, 2);
final List<Address> validatorList = createValidatorList(localAddr, 2, 2);
validatorList.remove(localAddr);
// Note the signer of the Previous block was not included.
@ -196,7 +196,7 @@ public class ProposerSelectorTest {
// LocalAddr will be in index 2 - the next proposer will also be in 2 (as prev proposer is
// removed)
final LinkedList<Address> validatorList = createValidatorList(localAddr, 2, 2);
final List<Address> validatorList = createValidatorList(localAddr, 2, 2);
validatorList.remove(localAddr);
final Blockchain blockchain =
@ -217,7 +217,7 @@ public class ProposerSelectorTest {
// LocalAddr will be in index 2 - the next proposer will also be in 2 (as prev proposer is
// removed)
final LinkedList<Address> validatorList = createValidatorList(localAddr, 4, 0);
final List<Address> validatorList = createValidatorList(localAddr, 4, 0);
validatorList.remove(localAddr);
// Note the signer of the Previous block was not included.

@ -27,7 +27,7 @@ import org.hyperledger.besu.ethereum.rlp.RLPException;
import java.util.Collection;
import java.util.List;
import java.util.SortedSet;
import java.util.NavigableSet;
import java.util.TreeSet;
import com.google.common.collect.Iterables;
@ -77,7 +77,7 @@ public class IbftExtraDataValidationRule implements AttachedBlockHeaderValidatio
}
}
final SortedSet<Address> sortedReportedValidators =
final NavigableSet<Address> sortedReportedValidators =
new TreeSet<>(ibftExtraData.getValidators());
if (!Iterables.elementsEqual(ibftExtraData.getValidators(), sortedReportedValidators)) {

@ -22,8 +22,9 @@ import static org.hyperledger.besu.crypto.Hash.keccak256;
import java.io.File;
import java.math.BigInteger;
import java.nio.file.Files;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import org.apache.tuweni.bytes.Bytes;
import org.apache.tuweni.bytes.Bytes32;
@ -37,8 +38,9 @@ public class SECP256K1Test {
@BeforeClass
public static void setTestSuiteStartTime() {
final SimpleDateFormat fmt = new SimpleDateFormat("yyyyMMdd-HHmmss");
suiteStartTime = fmt.format(new Date());
suiteStartTime =
LocalDateTime.now(ZoneId.systemDefault())
.format(DateTimeFormatter.ofPattern("yyyyMMdd-HHmmss"));
suiteName(SECP256K1Test.class);
}

@ -67,6 +67,7 @@ public class TlsHelpers {
Files.writeString(knownClientsPath, fingerprintsToAdd.toString());
}
@SuppressWarnings("JdkObsolete") // java.util.Enumeration is baked into the Keystore API
public static List<X509Certificate> getCertsFromPkcs12(final TlsCertificateDefinition certDef)
throws KeyStoreException, NoSuchAlgorithmException, CertificateException {
final List<X509Certificate> results = Lists.newArrayList();

@ -20,7 +20,7 @@ public abstract class SendRequest {
private final byte[] payload;
private final String from;
public SendRequest(final String payload, final String from) {
protected SendRequest(final String payload, final String from) {
this.payload = payload.getBytes(UTF_8);
this.from = from;
}

@ -51,7 +51,7 @@ public class BannedMethod extends BugChecker implements MethodInvocationTreeMatc
final MethodInvocationTree tree, final VisitorState state) {
for (final Map.Entry<Matcher<ExpressionTree>, String> entry : BANNED_METHOD_LIST.entrySet()) {
if (entry.getKey().matches(tree, state)) {
return buildDescriptionFromChecker(tree, this).setMessage(entry.getValue()).build();
return buildDescription(tree).setMessage(entry.getValue()).build();
}
}
return NO_MATCH;

@ -26,7 +26,7 @@ public abstract class AdminModifyPeer implements JsonRpcMethod {
protected final P2PNetwork peerNetwork;
public AdminModifyPeer(final P2PNetwork peerNetwork) {
protected AdminModifyPeer(final P2PNetwork peerNetwork) {
this.peerNetwork = peerNetwork;
}

@ -61,7 +61,7 @@ public abstract class TransactionReceiptResult {
protected final TransactionReceipt receipt;
public TransactionReceiptResult(final TransactionReceiptWithMetadata receiptWithMetadata) {
protected TransactionReceiptResult(final TransactionReceiptWithMetadata receiptWithMetadata) {
receipt = receiptWithMetadata.getReceipt();

@ -37,7 +37,7 @@ public abstract class PrivateTransactionResult {
private final String privateFrom;
private final String restriction;
public PrivateTransactionResult(final PrivateTransaction tx) {
protected PrivateTransactionResult(final PrivateTransaction tx) {
this.from = tx.getSender().toString();
this.gas = Quantity.create(tx.getGasLimit());
this.gasPrice = Quantity.create(tx.getGasPrice());

@ -38,7 +38,6 @@ import org.hyperledger.besu.ethereum.privacy.markertransaction.RandomSigningPriv
import java.math.BigInteger;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Optional;
import java.util.stream.Collectors;
@ -51,7 +50,7 @@ public abstract class PrivacyApiGroupJsonRpcMethods extends ApiGroupJsonRpcMetho
private final PrivateNonceProvider privateNonceProvider;
private final PrivacyQueries privacyQueries;
public PrivacyApiGroupJsonRpcMethods(
protected PrivacyApiGroupJsonRpcMethods(
final BlockchainQueries blockchainQueries,
final ProtocolSchedule protocolSchedule,
final TransactionPool transactionPool,
@ -98,7 +97,8 @@ public abstract class PrivacyApiGroupJsonRpcMethods extends ApiGroupJsonRpcMetho
return create(privacyController, enclavePublicProvider).entrySet().stream()
.collect(
Collectors.toMap(
Entry::getKey, entry -> createPrivacyMethod(privacyParameters, entry.getValue())));
Map.Entry::getKey,
entry -> createPrivacyMethod(privacyParameters, entry.getValue())));
}
protected abstract Map<String, JsonRpcMethod> create(

@ -139,6 +139,7 @@ public final class SelfSignedP12Certificate {
return keyPairGenerator.generateKeyPair();
}
@SuppressWarnings("JdkObsolete") // JcaX509v3CertificateBuilder requires java.util.Date.
private static Certificate generateSelfSignedCertificate(final KeyPair keyPair)
throws CertIOException, GeneralSecurityException, OperatorCreationException {
final X500Name issuer = new X500Name(distinguishedName);

@ -26,6 +26,7 @@ import org.hyperledger.besu.ethereum.core.BlockDataGenerator;
import org.hyperledger.besu.ethereum.core.BlockHeader;
import org.hyperledger.besu.ethereum.core.Wei;
import org.hyperledger.besu.ethereum.core.fees.TransactionGasBudgetCalculator;
import org.hyperledger.besu.ethereum.mainnet.AbstractBlockProcessor;
import org.hyperledger.besu.ethereum.mainnet.ClassicBlockProcessor;
import org.hyperledger.besu.ethereum.mainnet.MainnetBlockProcessor;
import org.hyperledger.besu.ethereum.mainnet.MiningBeneficiaryCalculator;
@ -81,8 +82,8 @@ public class RewardTraceGeneratorTest {
@Test
public void assertThatTraceGeneratorReturnValidRewardsForMainnetBlockProcessor() {
final MainnetBlockProcessor.TransactionReceiptFactory transactionReceiptFactory =
mock(MainnetBlockProcessor.TransactionReceiptFactory.class);
final AbstractBlockProcessor.TransactionReceiptFactory transactionReceiptFactory =
mock(AbstractBlockProcessor.TransactionReceiptFactory.class);
final MainnetBlockProcessor blockProcessor =
new MainnetBlockProcessor(
transactionProcessor,
@ -140,8 +141,8 @@ public class RewardTraceGeneratorTest {
@Test
public void assertThatTraceGeneratorReturnValidRewardsForClassicBlockProcessor() {
final ClassicBlockProcessor.TransactionReceiptFactory transactionReceiptFactory =
mock(ClassicBlockProcessor.TransactionReceiptFactory.class);
final AbstractBlockProcessor.TransactionReceiptFactory transactionReceiptFactory =
mock(AbstractBlockProcessor.TransactionReceiptFactory.class);
final ClassicBlockProcessor blockProcessor =
new ClassicBlockProcessor(
transactionProcessor,

@ -34,9 +34,9 @@ import org.hyperledger.besu.ethereum.core.WorldUpdater;
import org.hyperledger.besu.ethereum.core.fees.EIP1559;
import org.hyperledger.besu.ethereum.core.fees.FeeMarket;
import org.hyperledger.besu.ethereum.eth.transactions.PendingTransactions;
import org.hyperledger.besu.ethereum.mainnet.AbstractBlockProcessor;
import org.hyperledger.besu.ethereum.mainnet.BodyValidation;
import org.hyperledger.besu.ethereum.mainnet.DifficultyCalculator;
import org.hyperledger.besu.ethereum.mainnet.MainnetBlockProcessor;
import org.hyperledger.besu.ethereum.mainnet.ProtocolSchedule;
import org.hyperledger.besu.ethereum.mainnet.ProtocolSpec;
import org.hyperledger.besu.ethereum.mainnet.ScheduleBasedBlockHeaderFunctions;
@ -81,7 +81,7 @@ public abstract class AbstractBlockCreator implements AsyncBlockCreator {
private final AtomicBoolean isCancelled = new AtomicBoolean(false);
public AbstractBlockCreator(
protected AbstractBlockCreator(
final Address coinbase,
final ExtraDataCalculator extraDataCalculator,
final PendingTransactions pendingTransactions,
@ -207,7 +207,7 @@ public abstract class AbstractBlockCreator implements AsyncBlockCreator {
throws RuntimeException {
final TransactionProcessor transactionProcessor = protocolSpec.getTransactionProcessor();
final MainnetBlockProcessor.TransactionReceiptFactory transactionReceiptFactory =
final AbstractBlockProcessor.TransactionReceiptFactory transactionReceiptFactory =
protocolSpec.getTransactionReceiptFactory();
final BlockTransactionSelector selector =

@ -22,7 +22,7 @@ public abstract class AbstractBlockScheduler {
protected final Clock clock;
public AbstractBlockScheduler(final Clock clock) {
protected AbstractBlockScheduler(final Clock clock) {
this.clock = clock;
}

@ -54,7 +54,7 @@ public abstract class AbstractMinerExecutor<M extends BlockMiner<? extends Abstr
private final AtomicBoolean stopped = new AtomicBoolean(false);
public AbstractMinerExecutor(
protected AbstractMinerExecutor(
final ProtocolContext protocolContext,
final ProtocolSchedule protocolSchedule,
final PendingTransactions pendingTransactions,

@ -53,7 +53,7 @@ public abstract class AbstractMiningCoordinator<
private boolean isEnabled = false;
protected Optional<M> currentRunningMiner = Optional.empty();
public AbstractMiningCoordinator(
protected AbstractMiningCoordinator(
final Blockchain blockchain,
final AbstractMinerExecutor<M> executor,
final SyncState syncState) {

@ -28,7 +28,7 @@ import org.hyperledger.besu.ethereum.core.fees.FeeMarket;
import org.hyperledger.besu.ethereum.core.fees.TransactionPriceCalculator;
import org.hyperledger.besu.ethereum.eth.transactions.PendingTransactions;
import org.hyperledger.besu.ethereum.eth.transactions.PendingTransactions.TransactionSelectionResult;
import org.hyperledger.besu.ethereum.mainnet.MainnetBlockProcessor;
import org.hyperledger.besu.ethereum.mainnet.AbstractBlockProcessor;
import org.hyperledger.besu.ethereum.mainnet.TransactionProcessor;
import org.hyperledger.besu.ethereum.mainnet.TransactionValidationParams;
import org.hyperledger.besu.ethereum.mainnet.TransactionValidator;
@ -112,7 +112,7 @@ public class BlockTransactionSelector {
private final Blockchain blockchain;
private final MutableWorldState worldState;
private final PendingTransactions pendingTransactions;
private final MainnetBlockProcessor.TransactionReceiptFactory transactionReceiptFactory;
private final AbstractBlockProcessor.TransactionReceiptFactory transactionReceiptFactory;
private final Address miningBeneficiary;
private final TransactionPriceCalculator transactionPriceCalculator;
private final Optional<EIP1559> eip1559;
@ -126,7 +126,7 @@ public class BlockTransactionSelector {
final MutableWorldState worldState,
final PendingTransactions pendingTransactions,
final ProcessableBlockHeader processableBlockHeader,
final MainnetBlockProcessor.TransactionReceiptFactory transactionReceiptFactory,
final AbstractBlockProcessor.TransactionReceiptFactory transactionReceiptFactory,
final Wei minTransactionGasPrice,
final Double minBlockOccupancyRatio,
final Supplier<Boolean> isCancelled,

@ -57,7 +57,6 @@ import java.time.Instant;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import java.util.function.Supplier;
import com.google.common.collect.Lists;
import org.apache.tuweni.bytes.Bytes;
@ -81,9 +80,12 @@ public class BlockTransactionSelectorTest {
Optional.empty(),
TransactionPoolConfiguration.DEFAULT_PRICE_BUMP);
private final MutableWorldState worldState = InMemoryStorageProvider.createInMemoryWorldState();
private final Supplier<Boolean> isCancelled = () -> false;
private final TransactionProcessor transactionProcessor = mock(TransactionProcessor.class);
private Boolean isCancelled() {
return false;
}
private ProcessableBlockHeader createBlockWithGasLimit(final long gasLimit) {
return BlockHeaderBuilder.create()
.parentHash(Hash.EMPTY)
@ -117,7 +119,7 @@ public class BlockTransactionSelectorTest {
this::createReceipt,
Wei.ZERO,
0.8,
isCancelled,
this::isCancelled,
miningBeneficiary,
TransactionPriceCalculator.frontier(),
Optional.empty());
@ -156,7 +158,7 @@ public class BlockTransactionSelectorTest {
this::createReceipt,
Wei.ZERO,
0.8,
isCancelled,
this::isCancelled,
miningBeneficiary,
TransactionPriceCalculator.frontier(),
Optional.empty());
@ -213,7 +215,7 @@ public class BlockTransactionSelectorTest {
this::createReceipt,
Wei.ZERO,
0.8,
isCancelled,
this::isCancelled,
miningBeneficiary,
TransactionPriceCalculator.frontier(),
Optional.empty());
@ -257,7 +259,7 @@ public class BlockTransactionSelectorTest {
this::createReceipt,
Wei.ZERO,
0.8,
isCancelled,
this::isCancelled,
miningBeneficiary,
TransactionPriceCalculator.frontier(),
Optional.empty());
@ -292,7 +294,7 @@ public class BlockTransactionSelectorTest {
this::createReceipt,
Wei.of(6),
0.8,
isCancelled,
this::isCancelled,
miningBeneficiary,
TransactionPriceCalculator.frontier(),
Optional.empty());
@ -328,7 +330,7 @@ public class BlockTransactionSelectorTest {
this::createReceipt,
Wei.ZERO,
0.8,
isCancelled,
this::isCancelled,
miningBeneficiary,
TransactionPriceCalculator.frontier(),
Optional.empty());
@ -385,7 +387,7 @@ public class BlockTransactionSelectorTest {
this::createReceipt,
Wei.ZERO,
0.8,
isCancelled,
this::isCancelled,
miningBeneficiary,
TransactionPriceCalculator.frontier(),
Optional.empty());
@ -446,7 +448,7 @@ public class BlockTransactionSelectorTest {
this::createReceipt,
Wei.ZERO,
0.8,
isCancelled,
this::isCancelled,
miningBeneficiary,
TransactionPriceCalculator.frontier(),
Optional.empty());
@ -529,7 +531,7 @@ public class BlockTransactionSelectorTest {
this::createReceipt,
Wei.ZERO,
0.8,
isCancelled,
this::isCancelled,
miningBeneficiary,
TransactionPriceCalculator.frontier(),
Optional.empty());

@ -37,7 +37,7 @@ import org.hyperledger.besu.ethereum.rlp.BytesValueRLPInput;
import org.hyperledger.besu.ethereum.worldstate.WorldStateArchive;
import java.util.List;
import java.util.Map.Entry;
import java.util.Map;
import java.util.stream.Stream;
import org.apache.tuweni.bytes.Bytes;
@ -247,17 +247,17 @@ public class TraceTransactionIntegrationTest {
@SuppressWarnings("unchecked")
@SafeVarargs
private final void assertStorageContainsExactly(
final TraceFrame frame, final Entry<String, String>... memoryEntriesAsHex) {
private void assertStorageContainsExactly(
final TraceFrame frame, final Map.Entry<String, String>... memoryEntriesAsHex) {
assertThat(frame.getMemory()).isPresent();
final Entry<UInt256, UInt256>[] memoryEntries =
final Map.Entry<UInt256, UInt256>[] memoryEntries =
Stream.of(memoryEntriesAsHex)
.map(
entry ->
entry(
UInt256.fromHexString(entry.getKey()),
UInt256.fromHexString(entry.getValue())))
.toArray(Entry[]::new);
.toArray(Map.Entry[]::new);
assertThat(frame.getStorage().get()).containsExactly(memoryEntries);
}
}

@ -50,7 +50,11 @@ public interface Blockchain {
*/
Hash getChainHeadHash();
/** @return the header for the current chain head */
/**
* Returns the header for the current chain head.
*
* @return the header for the current chain head
*/
default BlockHeader getChainHeadHeader() {
return getBlockHeader(getChainHeadHash())
.orElseThrow(() -> new IllegalStateException("Missing chain head header."));
@ -171,6 +175,8 @@ public interface Blockchain {
Optional<Transaction> getTransactionByHash(Hash transactionHash);
/**
* Returns the transaction location associated with the corresponding hash.
*
* @param transactionHash A transaction hash.
* @return The transaction location associated with the corresponding hash.
*/

@ -24,7 +24,6 @@ import java.util.Map;
import java.util.NavigableMap;
import java.util.Optional;
import java.util.Set;
import java.util.SortedMap;
import java.util.TreeMap;
import javax.annotation.Nullable;
@ -184,7 +183,7 @@ public abstract class AbstractWorldUpdater<W extends WorldView, A extends Accoun
// Only contains updated storage entries, but may contains entry with a value of 0 to signify
// deletion.
private final SortedMap<UInt256, UInt256> updatedStorage;
private final NavigableMap<UInt256, UInt256> updatedStorage;
private boolean storageWasCleared = false;
private boolean transactionBoundary = false;

@ -91,6 +91,8 @@ public class Address extends DelegatingBytes implements org.hyperledger.besu.plu
}
/**
* Extracts an address from a ECDSARECOVER result hash.
*
* @param hash A hash that has been obtained through hashing the return of the <code>ECDSARECOVER
* </code> function from Appendix F (Signing Transactions) of the Ethereum Yellow Paper.
* @return The ethereum address from the provided hash.

@ -31,7 +31,7 @@ public final class Difficulty extends BaseUInt256Value<Difficulty> implements Qu
public static final Difficulty MAX_VALUE = wrap(Bytes32.ZERO.not());
protected Difficulty(final UInt256 value) {
Difficulty(final UInt256 value) {
super(value, Difficulty::new);
}

@ -33,7 +33,7 @@ public final class Gas {
private static final BigInteger MAX_VALUE_BIGINT = BigInteger.valueOf(Long.MAX_VALUE);
protected Gas(final long value) {
Gas(final long value) {
this.value = value;
}

@ -32,6 +32,8 @@ public interface Synchronizer {
void awaitStop() throws InterruptedException;
/**
* Current status of a sync, if syncing.
*
* @return the status, based on SyncingResult When actively synchronizing blocks, alternatively
* empty
*/

@ -27,7 +27,7 @@ public final class Wei extends BaseUInt256Value<Wei> implements Quantity {
public static final Wei ZERO = of(0);
protected Wei(final UInt256 value) {
Wei(final UInt256 value) {
super(value, Wei::new);
}

@ -112,6 +112,10 @@ public interface WorldUpdater extends MutableWorldView {
*/
void commit();
/** @return The parent WorldUpdater if this wraps another one, empty otherwise */
/**
* The parent updater (if it exists).
*
* @return The parent WorldUpdater if this wraps another one, empty otherwise
*/
public Optional<WorldUpdater> parentUpdater();
}

@ -82,7 +82,7 @@ public abstract class AbstractBlockProcessor implements BlockProcessor {
private final TransactionProcessor transactionProcessor;
private final MainnetBlockProcessor.TransactionReceiptFactory transactionReceiptFactory;
private final AbstractBlockProcessor.TransactionReceiptFactory transactionReceiptFactory;
final Wei blockReward;
@ -92,7 +92,7 @@ public abstract class AbstractBlockProcessor implements BlockProcessor {
private final TransactionGasBudgetCalculator gasBudgetCalculator;
public AbstractBlockProcessor(
protected AbstractBlockProcessor(
final TransactionProcessor transactionProcessor,
final TransactionReceiptFactory transactionReceiptFactory,
final Wei blockReward,

@ -27,7 +27,7 @@ public abstract class AbstractPrecompiledContract implements PrecompiledContract
private final String name;
public AbstractPrecompiledContract(final String name, final GasCalculator gasCalculator) {
protected AbstractPrecompiledContract(final String name, final GasCalculator gasCalculator) {
this.name = name;
this.gasCalculator = gasCalculator;
}

@ -17,6 +17,8 @@ package org.hyperledger.besu.ethereum.mainnet;
public interface EthHasher {
/**
* Hash of a particular block and nonce.
*
* @param buffer At least 64 bytes long buffer to store EthHash result in
* @param nonce Block Nonce
* @param number Block Number

@ -33,7 +33,7 @@ public class MainnetBlockProcessor extends AbstractBlockProcessor {
public MainnetBlockProcessor(
final TransactionProcessor transactionProcessor,
final MainnetBlockProcessor.TransactionReceiptFactory transactionReceiptFactory,
final AbstractBlockProcessor.TransactionReceiptFactory transactionReceiptFactory,
final Wei blockReward,
final MiningBeneficiaryCalculator miningBeneficiaryCalculator,
final boolean skipZeroBlockRewards,

@ -54,7 +54,7 @@ public class ProtocolSpec {
private final BlockHeaderFunctions blockHeaderFunctions;
private final MainnetBlockProcessor.TransactionReceiptFactory transactionReceiptFactory;
private final AbstractBlockProcessor.TransactionReceiptFactory transactionReceiptFactory;
private final DifficultyCalculator difficultyCalculator;
@ -113,7 +113,7 @@ public class ProtocolSpec {
final BlockImporter blockImporter,
final BlockValidator blockValidator,
final BlockHeaderFunctions blockHeaderFunctions,
final MainnetBlockProcessor.TransactionReceiptFactory transactionReceiptFactory,
final AbstractBlockProcessor.TransactionReceiptFactory transactionReceiptFactory,
final DifficultyCalculator difficultyCalculator,
final Wei blockReward,
final MiningBeneficiaryCalculator miningBeneficiaryCalculator,
@ -251,7 +251,7 @@ public class ProtocolSpec {
*
* @return the transaction receipt factory
*/
public MainnetBlockProcessor.TransactionReceiptFactory getTransactionReceiptFactory() {
public AbstractBlockProcessor.TransactionReceiptFactory getTransactionReceiptFactory() {
return transactionReceiptFactory;
}

@ -43,7 +43,7 @@ public class ProtocolSpecBuilder {
private Wei blockReward;
private boolean skipZeroBlockRewards;
private BlockHeaderFunctions blockHeaderFunctions;
private MainnetBlockProcessor.TransactionReceiptFactory transactionReceiptFactory;
private AbstractBlockProcessor.TransactionReceiptFactory transactionReceiptFactory;
private DifficultyCalculator difficultyCalculator;
private Function<GasCalculator, EVM> evmBuilder;
private Function<GasCalculator, TransactionValidator> transactionValidatorBuilder;
@ -91,7 +91,7 @@ public class ProtocolSpecBuilder {
}
public ProtocolSpecBuilder transactionReceiptFactory(
final MainnetBlockProcessor.TransactionReceiptFactory transactionReceiptFactory) {
final AbstractBlockProcessor.TransactionReceiptFactory transactionReceiptFactory) {
this.transactionReceiptFactory = transactionReceiptFactory;
return this;
}
@ -370,7 +370,7 @@ public class ProtocolSpecBuilder {
public interface BlockProcessorBuilder {
BlockProcessor apply(
TransactionProcessor transactionProcessor,
MainnetBlockProcessor.TransactionReceiptFactory transactionReceiptFactory,
AbstractBlockProcessor.TransactionReceiptFactory transactionReceiptFactory,
Wei blockReward,
MiningBeneficiaryCalculator miningBeneficiaryCalculator,
boolean skipZeroBlockRewards,

@ -21,7 +21,6 @@ import static org.hyperledger.besu.ethereum.privacy.group.OnChainGroupManagement
import org.hyperledger.besu.enclave.Enclave;
import org.hyperledger.besu.enclave.types.PrivacyGroup;
import org.hyperledger.besu.enclave.types.PrivacyGroup.Type;
import org.hyperledger.besu.enclave.types.ReceiveResponse;
import org.hyperledger.besu.enclave.types.SendResponse;
import org.hyperledger.besu.ethereum.chain.Blockchain;
@ -197,7 +196,7 @@ public class DefaultPrivacyController implements PrivacyController {
final List<PrivacyGroup> legacyGroups =
matchingGroups.stream()
.filter(group -> group.getType() == Type.LEGACY)
.filter(group -> group.getType() == PrivacyGroup.Type.LEGACY)
.collect(Collectors.toList());
if (legacyGroups.size() == 0) {
@ -299,7 +298,11 @@ public class DefaultPrivacyController implements PrivacyController {
if (rlpInput.nextSize() > 0) {
return Optional.of(
new PrivacyGroup(
privacyGroupId.toBase64String(), Type.ONCHAIN, "", "", decodeList(rlpInput.raw())));
privacyGroupId.toBase64String(),
PrivacyGroup.Type.ONCHAIN,
"",
"",
decodeList(rlpInput.raw())));
} else {
return Optional.empty();
}
@ -446,7 +449,7 @@ public class DefaultPrivacyController implements PrivacyController {
if (maybePrivacyGroup.isPresent() || isGroupAdditionTransaction(privateTransaction)) {
if (isGroupAdditionTransaction(privateTransaction)
|| maybePrivacyGroup.get().getType() == Type.ONCHAIN) {
|| maybePrivacyGroup.get().getType() == PrivacyGroup.Type.ONCHAIN) {
// onchain privacy group
final Optional<PrivateTransactionProcessor.Result> result =
privateTransactionSimulator.process(
@ -460,7 +463,7 @@ public class DefaultPrivacyController implements PrivacyController {
rlpOutput.encoded().toBase64String(),
privateTransaction.getPrivateFrom().toBase64String(),
onChainPrivateFor);
} else if (maybePrivacyGroup.get().getType() == Type.PANTHEON) {
} else if (maybePrivacyGroup.get().getType() == PrivacyGroup.Type.PANTHEON) {
// offchain privacy group
privateTransaction.writeTo(rlpOutput);
return enclave.send(

@ -30,7 +30,6 @@ import org.hyperledger.besu.ethereum.core.TransactionReceipt;
import org.hyperledger.besu.ethereum.core.Wei;
import org.hyperledger.besu.ethereum.core.WorldUpdater;
import org.hyperledger.besu.ethereum.mainnet.AbstractBlockProcessor;
import org.hyperledger.besu.ethereum.mainnet.MainnetBlockProcessor;
import org.hyperledger.besu.ethereum.mainnet.MiningBeneficiaryCalculator;
import org.hyperledger.besu.ethereum.mainnet.TransactionProcessor;
import org.hyperledger.besu.ethereum.mainnet.TransactionValidationParams;
@ -60,7 +59,7 @@ public class PrivateGroupRehydrationBlockProcessor {
private final TransactionProcessor transactionProcessor;
private final PrivateTransactionProcessor privateTransactionProcessor;
private final MainnetBlockProcessor.TransactionReceiptFactory transactionReceiptFactory;
private final AbstractBlockProcessor.TransactionReceiptFactory transactionReceiptFactory;
final Wei blockReward;
private final boolean skipZeroBlockRewards;
private final MiningBeneficiaryCalculator miningBeneficiaryCalculator;
@ -68,7 +67,7 @@ public class PrivateGroupRehydrationBlockProcessor {
public PrivateGroupRehydrationBlockProcessor(
final TransactionProcessor transactionProcessor,
final PrivateTransactionProcessor privateTransactionProcessor,
final MainnetBlockProcessor.TransactionReceiptFactory transactionReceiptFactory,
final AbstractBlockProcessor.TransactionReceiptFactory transactionReceiptFactory,
final Wei blockReward,
final MiningBeneficiaryCalculator miningBeneficiaryCalculator,
final boolean skipZeroBlockRewards) {

@ -25,7 +25,7 @@ public abstract class PrivateMarkerTransactionFactory {
private final Address privacyPrecompileAddress;
public PrivateMarkerTransactionFactory(final Address privacyPrecompileAddress) {
protected PrivateMarkerTransactionFactory(final Address privacyPrecompileAddress) {
this.privacyPrecompileAddress = privacyPrecompileAddress;
}

@ -25,7 +25,6 @@ import org.hyperledger.besu.ethereum.core.TransactionReceipt;
import org.hyperledger.besu.ethereum.core.Wei;
import org.hyperledger.besu.ethereum.core.WorldUpdater;
import org.hyperledger.besu.ethereum.mainnet.AbstractBlockProcessor;
import org.hyperledger.besu.ethereum.mainnet.MainnetBlockProcessor;
import org.hyperledger.besu.ethereum.mainnet.MiningBeneficiaryCalculator;
import org.hyperledger.besu.ethereum.mainnet.ProtocolSpec;
import org.hyperledger.besu.ethereum.mainnet.TransactionProcessor;
@ -45,14 +44,14 @@ public class PrivateMigrationBlockProcessor {
static final int MAX_GENERATION = 6;
private final TransactionProcessor transactionProcessor;
private final MainnetBlockProcessor.TransactionReceiptFactory transactionReceiptFactory;
private final AbstractBlockProcessor.TransactionReceiptFactory transactionReceiptFactory;
final Wei blockReward;
private final boolean skipZeroBlockRewards;
private final MiningBeneficiaryCalculator miningBeneficiaryCalculator;
public PrivateMigrationBlockProcessor(
final TransactionProcessor transactionProcessor,
final MainnetBlockProcessor.TransactionReceiptFactory transactionReceiptFactory,
final AbstractBlockProcessor.TransactionReceiptFactory transactionReceiptFactory,
final Wei blockReward,
final MiningBeneficiaryCalculator miningBeneficiaryCalculator,
final boolean skipZeroBlockRewards) {

@ -24,6 +24,7 @@ import org.hyperledger.besu.ethereum.worldstate.StateTrieAccountValue;
import org.hyperledger.besu.ethereum.worldstate.WorldStateStorage;
import java.util.List;
import java.util.NavigableMap;
import java.util.Optional;
import java.util.SortedMap;
import java.util.TreeMap;
@ -69,7 +70,7 @@ public class WorldStateProofProvider {
final StateTrieAccountValue account, final List<UInt256> accountStorageKeys) {
final MerklePatriciaTrie<Bytes32, Bytes> storageTrie =
newAccountStorageTrie(account.getStorageRoot());
final SortedMap<UInt256, Proof<Bytes>> storageProofs = new TreeMap<>();
final NavigableMap<UInt256, Proof<Bytes>> storageProofs = new TreeMap<>();
accountStorageKeys.forEach(
key -> storageProofs.put(key, storageTrie.getValueWithProof(Hash.hash(key.toBytes()))));
return storageProofs;

@ -31,7 +31,7 @@ import org.apache.tuweni.units.bigints.UInt256;
*/
public abstract class AbstractCallOperation extends AbstractOperation {
public AbstractCallOperation(
protected AbstractCallOperation(
final int opcode,
final String name,
final int stackItemsConsumed,

@ -27,7 +27,7 @@ public abstract class AbstractOperation implements Operation {
private final int opSize;
private final GasCalculator gasCalculator;
public AbstractOperation(
protected AbstractOperation(
final int opcode,
final String name,
final int stackItemsConsumed,

@ -69,7 +69,11 @@ public class Code {
return bytes.hashCode();
}
/** @return The number of bytes in the code. */
/**
* Size of the Code, in bytes
*
* @return The number of bytes in the code.
*/
public int getSize() {
return bytes.size();
}

@ -23,6 +23,8 @@ import java.util.Optional;
public interface Operation extends ExceptionalHaltPredicate {
/**
* Gas cost of this operation, in context of the provided frame.
*
* @param frame The frame for execution of this operation.
* @return The gas cost associated with executing this operation given the current {@link
* MessageFrame}.

@ -35,7 +35,7 @@ import org.apache.tuweni.units.bigints.UInt256;
public abstract class AbstractCreateOperation extends AbstractOperation {
public AbstractCreateOperation(
AbstractCreateOperation(
final int opcode,
final String name,
final int stackItemsConsumed,

@ -434,10 +434,10 @@ public class BlockDataGenerator {
* Creates a UInt256 with a value that fits within maxByteSize
*
* @param maxByteSize The byte size to cap this value to
* @return
* @return the maximum size
*/
private UInt256 uint256(final int maxByteSize) {
assert maxByteSize <= 32;
checkArgument(maxByteSize <= 32);
return UInt256.fromBytes(Bytes32.wrap(bytes(32, 32 - maxByteSize)));
}
@ -472,7 +472,7 @@ public class BlockDataGenerator {
* @param size The size of the byte array to return
* @param zerofill The number of lower-order bytes to fill with zero (creating a smaller big
* endian integer value)
* @return
* @return the array of bytes.
*/
private byte[] bytes(final int size, final int zerofill) {
final byte[] bytes = new byte[size];

@ -20,7 +20,6 @@ import org.hyperledger.besu.ethereum.chain.Blockchain;
import org.hyperledger.besu.ethereum.vm.BlockHashLookup;
import org.hyperledger.besu.ethereum.vm.Code;
import org.hyperledger.besu.ethereum.vm.MessageFrame;
import org.hyperledger.besu.ethereum.vm.MessageFrame.Type;
import org.hyperledger.besu.ethereum.vm.operations.ReturnStack;
import java.util.ArrayDeque;
@ -37,7 +36,7 @@ public class MessageFrameTestFixture {
public static final Address DEFAUT_ADDRESS = AddressHelpers.ofValue(244259721);
private final int maxStackSize = DEFAULT_MAX_STACK_SIZE;
private Type type = Type.MESSAGE_CALL;
private MessageFrame.Type type = MessageFrame.Type.MESSAGE_CALL;
private Deque<MessageFrame> messageFrameStack = new ArrayDeque<>();
private Optional<Blockchain> blockchain = Optional.empty();
private Optional<WorldUpdater> worldState = Optional.empty();
@ -58,7 +57,7 @@ public class MessageFrameTestFixture {
private ReturnStack returnStack = new ReturnStack();
private ExecutionContextTestFixture executionContextTestFixture;
public MessageFrameTestFixture type(final Type type) {
public MessageFrameTestFixture type(final MessageFrame.Type type) {
this.type = type;
return this;
}

@ -34,8 +34,8 @@ import org.junit.Test;
public class MainnetBlockProcessorTest {
private final TransactionProcessor transactionProcessor = mock(TransactionProcessor.class);
private final MainnetBlockProcessor.TransactionReceiptFactory transactionReceiptFactory =
mock(MainnetBlockProcessor.TransactionReceiptFactory.class);
private final AbstractBlockProcessor.TransactionReceiptFactory transactionReceiptFactory =
mock(AbstractBlockProcessor.TransactionReceiptFactory.class);
@Test
public void noAccountCreatedWhenBlockRewardIsZeroAndSkipped() {

@ -36,7 +36,6 @@ import org.hyperledger.besu.crypto.SECP256K1.KeyPair;
import org.hyperledger.besu.enclave.Enclave;
import org.hyperledger.besu.enclave.EnclaveServerException;
import org.hyperledger.besu.enclave.types.PrivacyGroup;
import org.hyperledger.besu.enclave.types.PrivacyGroup.Type;
import org.hyperledger.besu.enclave.types.ReceiveResponse;
import org.hyperledger.besu.enclave.types.SendResponse;
import org.hyperledger.besu.ethereum.chain.Blockchain;
@ -89,9 +88,9 @@ public class DefaultPrivacyControllerTest {
private static final String MOCK_TRANSACTION_SIMULATOR_RESULT_OUTPUT_BYTES_PREFIX =
"0x00000000000000000000000000000000000000000000000000000000000000200000000000000000000000000000000000000000000000000000000000000002";
private static final PrivacyGroup PANTHEON_PRIVACY_GROUP =
new PrivacyGroup("", Type.PANTHEON, "", "", emptyList());
new PrivacyGroup("", PrivacyGroup.Type.PANTHEON, "", "", emptyList());
private static final PrivacyGroup ON_CHAIN_PRIVACY_GROUP =
new PrivacyGroup("", Type.ONCHAIN, "", "", Arrays.asList(ENCLAVE_PUBLIC_KEY));
new PrivacyGroup("", PrivacyGroup.Type.ONCHAIN, "", "", Arrays.asList(ENCLAVE_PUBLIC_KEY));
private PrivacyController privacyController;
private PrivacyController brokenPrivacyController;
@ -229,7 +228,8 @@ public class DefaultPrivacyControllerTest {
final List<String> privacyGroupAddresses = newArrayList(ENCLAVE_PUBLIC_KEY, ENCLAVE_KEY2);
final PrivacyGroup privacyGroup =
new PrivacyGroup(PRIVACY_GROUP_ID, Type.ONCHAIN, "", "", privacyGroupAddresses);
new PrivacyGroup(
PRIVACY_GROUP_ID, PrivacyGroup.Type.ONCHAIN, "", "", privacyGroupAddresses);
final PrivacyGroupHeadBlockMap privacyGroupHeadBlockMap =
new PrivacyGroupHeadBlockMap(
@ -310,7 +310,7 @@ public class DefaultPrivacyControllerTest {
final PrivacyGroup enclavePrivacyGroupResponse =
new PrivacyGroup(
PRIVACY_GROUP_ID,
Type.PANTHEON,
PrivacyGroup.Type.PANTHEON,
PRIVACY_GROUP_NAME,
PRIVACY_GROUP_DESCRIPTION,
PRIVACY_GROUP_ADDRESSES);
@ -349,7 +349,7 @@ public class DefaultPrivacyControllerTest {
final PrivacyGroup privacyGroup =
new PrivacyGroup(
PRIVACY_GROUP_ID,
Type.PANTHEON,
PrivacyGroup.Type.PANTHEON,
PRIVACY_GROUP_NAME,
PRIVACY_GROUP_DESCRIPTION,
PRIVACY_GROUP_ADDRESSES);
@ -369,7 +369,11 @@ public class DefaultPrivacyControllerTest {
final PrivacyGroup[] returnedGroups =
new PrivacyGroup[] {
new PrivacyGroup(
PRIVACY_GROUP_ID, Type.LEGACY, "Group1_Name", "Group1_Desc", emptyList()),
PRIVACY_GROUP_ID,
PrivacyGroup.Type.LEGACY,
"Group1_Name",
"Group1_Desc",
emptyList()),
};
when(enclave.findPrivacyGroup(any())).thenReturn(returnedGroups);
@ -408,8 +412,10 @@ public class DefaultPrivacyControllerTest {
final Address address = Address.fromHexString("55");
final PrivacyGroup[] returnedGroups =
new PrivacyGroup[] {
new PrivacyGroup("Group1", Type.LEGACY, "Group1_Name", "Group1_Desc", emptyList()),
new PrivacyGroup("Group2", Type.LEGACY, "Group2_Name", "Group2_Desc", emptyList()),
new PrivacyGroup(
"Group1", PrivacyGroup.Type.LEGACY, "Group1_Name", "Group1_Desc", emptyList()),
new PrivacyGroup(
"Group2", PrivacyGroup.Type.LEGACY, "Group2_Name", "Group2_Desc", emptyList()),
};
when(enclave.findPrivacyGroup(any())).thenReturn(returnedGroups);

@ -24,7 +24,6 @@ import static org.mockito.Mockito.when;
import org.hyperledger.besu.enclave.Enclave;
import org.hyperledger.besu.enclave.types.PrivacyGroup;
import org.hyperledger.besu.enclave.types.PrivacyGroup.Type;
import org.hyperledger.besu.enclave.types.ReceiveResponse;
import org.hyperledger.besu.ethereum.core.Address;
import org.hyperledger.besu.ethereum.core.Hash;
@ -55,9 +54,10 @@ public class MultiTenancyPrivacyControllerTest {
private static final String ENCLAVE_KEY = "Ko2bVqD";
private static final ArrayList<Log> LOGS = new ArrayList<>();
private static final PrivacyGroup PANTHEON_PRIVACY_GROUP =
new PrivacyGroup("", Type.PANTHEON, "", "", Collections.emptyList());
new PrivacyGroup("", PrivacyGroup.Type.PANTHEON, "", "", Collections.emptyList());
private static final PrivacyGroup PANTHEON_GROUP_WITH_ENCLAVE_KEY_1 =
new PrivacyGroup(PRIVACY_GROUP_ID, Type.PANTHEON, "", "", List.of(ENCLAVE_PUBLIC_KEY1));
new PrivacyGroup(
PRIVACY_GROUP_ID, PrivacyGroup.Type.PANTHEON, "", "", List.of(ENCLAVE_PUBLIC_KEY1));
@Mock private PrivacyController privacyController;
@Mock private Enclave enclave;
@ -103,7 +103,7 @@ public class MultiTenancyPrivacyControllerTest {
final PrivacyGroup privacyGroupWithEnclavePublicKey =
new PrivacyGroup(
PRIVACY_GROUP_ID,
Type.PANTHEON,
PrivacyGroup.Type.PANTHEON,
"",
"",
List.of(ENCLAVE_PUBLIC_KEY1, ENCLAVE_PUBLIC_KEY2));
@ -133,11 +133,12 @@ public class MultiTenancyPrivacyControllerTest {
assertThatThrownBy(
() ->
multiTenancyPrivacyController.sendTransaction(
transaction, ENCLAVE_PUBLIC_KEY1, null))
transaction, ENCLAVE_PUBLIC_KEY1, Optional.empty()))
.isInstanceOf(MultiTenancyValidationException.class)
.hasMessage("Transaction privateFrom must match enclave public key");
verify(privacyController, never()).sendTransaction(transaction, ENCLAVE_PUBLIC_KEY1, null);
verify(privacyController, never())
.sendTransaction(transaction, ENCLAVE_PUBLIC_KEY1, Optional.empty());
}
@Test
@ -169,7 +170,8 @@ public class MultiTenancyPrivacyControllerTest {
.build();
final PrivacyGroup privacyGroupWithoutEnclavePublicKey =
new PrivacyGroup(PRIVACY_GROUP_ID, Type.PANTHEON, "", "", List.of(ENCLAVE_PUBLIC_KEY2));
new PrivacyGroup(
PRIVACY_GROUP_ID, PrivacyGroup.Type.PANTHEON, "", "", List.of(ENCLAVE_PUBLIC_KEY2));
when(enclave.retrievePrivacyGroup(PRIVACY_GROUP_ID))
.thenReturn(privacyGroupWithoutEnclavePublicKey);
@ -205,7 +207,8 @@ public class MultiTenancyPrivacyControllerTest {
public void createPrivacyGroupDelegatesToPrivacyController() {
final List<String> addresses = List.of(ENCLAVE_PUBLIC_KEY1, ENCLAVE_PUBLIC_KEY2);
final PrivacyGroup delegatePrivacyGroup =
new PrivacyGroup(PRIVACY_GROUP_ID, Type.PANTHEON, "name", "description", addresses);
new PrivacyGroup(
PRIVACY_GROUP_ID, PrivacyGroup.Type.PANTHEON, "name", "description", addresses);
when(privacyController.createPrivacyGroup(
addresses, "name", "description", ENCLAVE_PUBLIC_KEY1))
@ -224,7 +227,7 @@ public class MultiTenancyPrivacyControllerTest {
final PrivacyGroup privacyGroupWithEnclavePublicKey =
new PrivacyGroup(
PRIVACY_GROUP_ID,
Type.PANTHEON,
PrivacyGroup.Type.PANTHEON,
"",
"",
List.of(ENCLAVE_PUBLIC_KEY1, ENCLAVE_PUBLIC_KEY2));
@ -243,7 +246,8 @@ public class MultiTenancyPrivacyControllerTest {
public void
deletePrivacyGroupFailsWithValidationExceptionWhenPrivacyGroupDoesNotContainEnclavePublicKey() {
final PrivacyGroup privacyGroupWithoutEnclavePublicKey =
new PrivacyGroup(PRIVACY_GROUP_ID, Type.PANTHEON, "", "", List.of(ENCLAVE_PUBLIC_KEY2));
new PrivacyGroup(
PRIVACY_GROUP_ID, PrivacyGroup.Type.PANTHEON, "", "", List.of(ENCLAVE_PUBLIC_KEY2));
when(enclave.retrievePrivacyGroup(PRIVACY_GROUP_ID))
.thenReturn(privacyGroupWithoutEnclavePublicKey);
@ -261,7 +265,7 @@ public class MultiTenancyPrivacyControllerTest {
final PrivacyGroup privacyGroup =
new PrivacyGroup(
PRIVACY_GROUP_ID,
Type.PANTHEON,
PrivacyGroup.Type.PANTHEON,
"",
"",
List.of(ENCLAVE_PUBLIC_KEY1, ENCLAVE_PUBLIC_KEY2));
@ -317,7 +321,7 @@ public class MultiTenancyPrivacyControllerTest {
final PrivacyGroup privacyGroupWithEnclavePublicKey =
new PrivacyGroup(
PRIVACY_GROUP_ID,
Type.PANTHEON,
PrivacyGroup.Type.PANTHEON,
"",
"",
List.of(ENCLAVE_PUBLIC_KEY1, ENCLAVE_PUBLIC_KEY2));
@ -338,7 +342,8 @@ public class MultiTenancyPrivacyControllerTest {
public void
determineBesuNonceFailsWithValidationExceptionWhenEnclavePublicKeyNotInPrivacyGroup() {
final PrivacyGroup privacyGroupWithoutEnclavePublicKey =
new PrivacyGroup(PRIVACY_GROUP_ID, Type.PANTHEON, "", "", List.of(ENCLAVE_PUBLIC_KEY2));
new PrivacyGroup(
PRIVACY_GROUP_ID, PrivacyGroup.Type.PANTHEON, "", "", List.of(ENCLAVE_PUBLIC_KEY2));
when(enclave.retrievePrivacyGroup(PRIVACY_GROUP_ID))
.thenReturn(privacyGroupWithoutEnclavePublicKey);

@ -340,7 +340,11 @@ public class EthPeer {
return statusHasBeenReceivedFromPeer.get();
}
/** @return true if we have sent a status message to this peer. */
/**
* Return true if we have sent a status message to this peer.
*
* @return true if we have sent a status message to this peer.
*/
public boolean statusHasBeenSentToPeer() {
return statusHasBeenSentToPeer.get();
}
@ -349,12 +353,20 @@ public class EthPeer {
return knownBlocks.contains(hash);
}
/** @return This peer's current chain state. */
/**
* Return This peer's current chain state.
*
* @return This peer's current chain state.
*/
public ChainState chainState() {
return chainHeadState;
}
/** @return A read-only snapshot of this peer's current {@code chainState} } */
/**
* Return A read-only snapshot of this peer's current {@code chainState} }
*
* @return A read-only snapshot of this peer's current {@code chainState} }
*/
public ChainHeadEstimate chainStateSnapshot() {
return chainHeadState.getSnapshot();
}

@ -55,7 +55,7 @@ public abstract class AbstractRetryingPeerTask<T> extends AbstractEthTask<T> {
* @param isEmptyResponse Test if the response received was empty.
* @param metricsSystem The metrics system used to measure task.
*/
public AbstractRetryingPeerTask(
protected AbstractRetryingPeerTask(
final EthContext ethContext,
final int maxRetries,
final Predicate<T> isEmptyResponse,

@ -83,34 +83,56 @@ public final class StatusMessage extends AbstractMessageData {
return EthPV62.STATUS;
}
/** @return The eth protocol version the associated node is running. */
/**
* Return The eth protocol version the associated node is running.
*
* @return The eth protocol version the associated node is running.
*/
public int protocolVersion() {
return status().protocolVersion;
}
/** @return The id of the network the associated node is participating in. */
/**
* Return The id of the network the associated node is participating in.
*
* @return The id of the network the associated node is participating in.
*/
public BigInteger networkId() {
return status().networkId;
}
/** @return The total difficulty of the head of the associated node's local blockchain. */
/**
* Return The total difficulty of the head of the associated node's local blockchain.
*
* @return The total difficulty of the head of the associated node's local blockchain.
*/
public Difficulty totalDifficulty() {
return status().totalDifficulty;
}
/** @return The hash of the head of the associated node's local blockchian. */
/**
* Return The hash of the head of the associated node's local blockchian.
*
* @return The hash of the head of the associated node's local blockchian.
*/
public Hash bestHash() {
return status().bestHash;
}
/**
* Return The hash of the genesis block of the network the associated node is participating in.
*
* @return The hash of the genesis block of the network the associated node is participating in.
*/
public Bytes32 genesisHash() {
return status().genesisHash;
}
/** @return The fork id of the network the associated node is participating in. */
/**
* Return The fork id of the network the associated node is participating in.
*
* @return The fork id of the network the associated node is participating in.
*/
public ForkId forkId() {
return status().forkId;
}

@ -56,7 +56,7 @@ abstract class AbstractPeerBlockValidator implements PeerValidator {
this.chainHeightEstimationBuffer = chainHeightEstimationBuffer;
}
public AbstractPeerBlockValidator(
protected AbstractPeerBlockValidator(
final ProtocolSchedule protocolSchedule,
final MetricsSystem metricsSystem,
final long blockNumber) {

@ -50,6 +50,8 @@ public interface PeerValidator {
CompletableFuture<Boolean> validatePeer(final EthContext ethContext, final EthPeer ethPeer);
/**
* Reason the peer will disconnect when the validator fail.
*
* @param ethPeer The peer to be disconnected.
* @return The reason for disconnecting.
*/

@ -42,7 +42,7 @@ public abstract class SyncTargetManager {
private final EthContext ethContext;
private final MetricsSystem metricsSystem;
public SyncTargetManager(
protected SyncTargetManager(
final SynchronizerConfiguration config,
final ProtocolSchedule protocolSchedule,
final ProtocolContext protocolContext,

@ -42,11 +42,11 @@ import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.NavigableSet;
import java.util.Optional;
import java.util.OptionalLong;
import java.util.Queue;
import java.util.Set;
import java.util.SortedSet;
import java.util.TreeSet;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicLong;
@ -69,7 +69,7 @@ public class PendingTransactions {
private final Queue<Hash> newPooledHashes;
private final Map<Hash, TransactionInfo> pendingTransactions = new ConcurrentHashMap<>();
private final SortedSet<TransactionInfo> prioritizedTransactions =
private final NavigableSet<TransactionInfo> prioritizedTransactions =
new TreeSet<>(
comparing(TransactionInfo::isReceivedFromLocalSource)
.thenComparing(TransactionInfo::getSequence)

@ -15,16 +15,18 @@
package org.hyperledger.besu.ethereum.eth.transactions;
import org.hyperledger.besu.ethereum.eth.transactions.PendingTransactions.TransactionInfo;
import java.util.Iterator;
import java.util.NavigableMap;
import java.util.OptionalLong;
import java.util.PriorityQueue;
import java.util.Queue;
import java.util.SortedMap;
import java.util.TreeMap;
import java.util.stream.LongStream;
class TransactionsForSenderInfo {
private final SortedMap<Long, PendingTransactions.TransactionInfo> transactionsInfos;
private final NavigableMap<Long, PendingTransactions.TransactionInfo> transactionsInfos;
private final Queue<Long> gaps = new PriorityQueue<>();
TransactionsForSenderInfo() {
@ -56,7 +58,7 @@ class TransactionsForSenderInfo {
}
}
SortedMap<Long, PendingTransactions.TransactionInfo> getTransactionsInfos() {
NavigableMap<Long, TransactionInfo> getTransactionsInfos() {
return transactionsInfos;
}

@ -111,7 +111,7 @@ public final class EthProtocolManagerTest {
transactionPool = blockchainSetupUtil.getTransactionPool();
protocolSchedule = blockchainSetupUtil.getProtocolSchedule();
protocolContext = blockchainSetupUtil.getProtocolContext();
assert (blockchainSetupUtil.getMaxBlockNumber() >= 20L);
assertThat(blockchainSetupUtil.getMaxBlockNumber()).isGreaterThanOrEqualTo(20L);
}
@Test

@ -39,6 +39,7 @@ public class MockEthTask extends AbstractEthTask<Object> {
try {
countdown.await();
} catch (final InterruptedException ignore) {
// ignore
}
}

@ -74,7 +74,7 @@ public abstract class AbstractMessageTaskTest<T, R> {
protocolSchedule = blockchainSetupUtil.getProtocolSchedule();
protocolContext = blockchainSetupUtil.getProtocolContext();
assert (blockchainSetupUtil.getMaxBlockNumber() >= 20L);
assertThat(blockchainSetupUtil.getMaxBlockNumber()).isGreaterThanOrEqualTo(20L);
}
@Before

@ -31,13 +31,13 @@ import org.junit.Test;
/**
* Tests ethTasks that request data from the network, and retry until all of the data is received.
*
* @param <T>
* @param <T> The type of data being requested from the network
*/
public abstract class RetryingMessageTaskTest<T> extends AbstractMessageTaskTest<T, T> {
protected final int maxRetries;
public RetryingMessageTaskTest() {
protected RetryingMessageTaskTest() {
this.maxRetries = 3;
}

@ -272,7 +272,7 @@ public class DetermineCommonAncestorTaskTest {
* remoteBlockCount} - 1.
* @param blocksInCommon The number of blocks shared between local and remote. If a common
* ancestor exists, its block number will be: {@code blocksInCommon} - 1
* @return
* @return the test blockchain
*/
private Blockchain setupLocalAndRemoteChains(
final int localBlockCount, final int remoteBlockCount, final int blocksInCommon) {

@ -73,7 +73,6 @@ import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Objects;
import java.util.Set;
import java.util.concurrent.CompletableFuture;
@ -556,7 +555,7 @@ public class WorldStateDownloaderTest {
assertThat(allTrieNodes.size()).isGreaterThan(0); // Sanity check
final Updater localStorageUpdater = localStorage.updater();
boolean storeNode = true;
for (final Entry<Bytes32, Bytes> entry : allTrieNodes.entrySet()) {
for (final Map.Entry<Bytes32, Bytes> entry : allTrieNodes.entrySet()) {
final Bytes32 hash = entry.getKey();
final Bytes data = entry.getValue();
if (storeNode) {

@ -83,7 +83,7 @@ public abstract class PeerDiscoveryAgent {
private boolean isActive = false;
protected final Subscribers<PeerBondedObserver> peerBondedObservers = Subscribers.create();
public PeerDiscoveryAgent(
protected PeerDiscoveryAgent(
final NodeKey nodeKey,
final DiscoveryConfiguration config,
final PeerPermissions peerPermissions,

@ -19,9 +19,9 @@ import org.hyperledger.besu.ethereum.p2p.discovery.PeerDiscoveryStatus;
import java.util.List;
import java.util.Map;
import java.util.NavigableMap;
import java.util.Objects;
import java.util.Optional;
import java.util.SortedMap;
import java.util.TreeMap;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean;
@ -47,7 +47,7 @@ public class RecursivePeerRefreshState {
private final int maxRounds;
private int currentRound;
private final SortedMap<Bytes, MetadataPeer> oneTrueMap = new TreeMap<>();
private final NavigableMap<Bytes, MetadataPeer> oneTrueMap = new TreeMap<>();
private final TimerUtil timerUtil;
private final int timeoutPeriodInSeconds;

@ -133,7 +133,11 @@ public interface P2PNetwork extends Closeable {
*/
boolean isP2pEnabled();
/** @return Return true if peer discovery is enabled. */
/**
* Is discovery enabled?
*
* @return Return true if peer discovery is enabled.
*/
boolean isDiscoveryEnabled();
/**

@ -173,7 +173,7 @@ public class EnodeURL {
/**
* Returns the discovery port only if it differs from the listening port
*
* @return
* @return The port, as an optional.
*/
private OptionalInt getDiscPortQueryParam() {
final int listeningPort = getListeningPortOrZero();

@ -38,12 +38,16 @@ public interface LocalNode {
}
/**
* Information of this node as a peer.
*
* @return the {@link PeerInfo} associated with the local node.
* @throws NodeNotReadyException If the local node is not ready, throws an exception.
*/
PeerInfo getPeerInfo() throws NodeNotReadyException;
/**
* This node as a Peer.
*
* @return a {@link Peer} representing the local node.
* @throws NodeNotReadyException If the local node is not ready, throws an exception.
*/

@ -20,7 +20,11 @@ import org.apache.tuweni.bytes.Bytes;
public interface Peer extends PeerId {
/** @return The enode representing the location of this peer. */
/**
* ENode URL of this peer.
*
* @return The enode representing the location of this peer.
*/
EnodeURL getEnodeURL();
/**

@ -22,6 +22,8 @@ import java.util.Optional;
public interface PermissionsUpdateCallback {
/**
* onUpdate callback.
*
* @param permissionsRestricted True if permissions were narrowed in any way, meaning that
* previously permitted peers may no longer be permitted. False indicates that permissions
* were made less restrictive, meaning peers that were previously restricted may now be

@ -54,7 +54,7 @@ public abstract class AbstractPeerConnection implements PeerConnection {
protected final PeerConnectionEventDispatcher connectionEventDispatcher;
private final LabelledMetric<Counter> outboundMessagesCounter;
public AbstractPeerConnection(
protected AbstractPeerConnection(
final Peer peer,
final PeerInfo peerInfo,
final InetSocketAddress localAddress,

@ -37,7 +37,11 @@ public interface PeerConnection {
*/
void send(Capability capability, MessageData message) throws PeerNotConnected;
/** @return a list of shared capabilities between this node and the connected peer */
/**
* Agreed capabilities between us and the peer.
*
* @return a list of shared capabilities between this node and the connected peer
*/
Set<Capability> getAgreedCapabilities();
/**
@ -68,7 +72,11 @@ public interface PeerConnection {
send(capability(protocol), message);
}
/** @return A representation of the remote peer this node is connected to. */
/**
* Data about the peer on the other side of this connection.
*
* @return A representation of the remote peer this node is connected to.
*/
Peer getPeer();
/**
@ -93,7 +101,11 @@ public interface PeerConnection {
*/
void disconnect(DisconnectReason reason);
/** @return True if the peer is disconnected */
/**
* Has this connection been disconnected.
*
* @return True if the peer is disconnected
*/
boolean isDisconnected();
InetSocketAddress getLocalAddress();

@ -28,6 +28,7 @@ import java.util.Arrays;
import com.google.common.annotations.VisibleForTesting;
import com.google.common.base.Preconditions;
import com.google.errorprone.annotations.FormatMethod;
import io.netty.buffer.ByteBuf;
import org.apache.tuweni.bytes.Bytes;
import org.apache.tuweni.bytes.MutableBytes;
@ -358,6 +359,7 @@ public class Framer {
return pad == 0 ? 0 : 16 - pad;
}
@FormatMethod
private static FramingException error(final String s, final Object... params) {
return new FramingException(String.format(s, params));
}

@ -62,7 +62,7 @@ public final class InitiatorHandshakeMessageV1 implements InitiatorHandshakeMess
private final Bytes32 nonce;
private final boolean token;
protected InitiatorHandshakeMessageV1(
InitiatorHandshakeMessageV1(
final SECP256K1.PublicKey pubKey,
final SECP256K1.Signature signature,
final SECP256K1.PublicKey ephPubKey,

@ -22,7 +22,6 @@ import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import com.google.common.collect.ImmutableMap;
@ -77,7 +76,7 @@ public class CapabilityMultiplexer {
* @return The interpreted message.
*/
public ProtocolMessage demultiplex(final MessageData receivedMessage) {
final Entry<Range<Integer>, Capability> agreedCap =
final Map.Entry<Range<Integer>, Capability> agreedCap =
agreedCaps.getEntry(receivedMessage.getCode());
if (agreedCap == null) {
@ -143,7 +142,8 @@ public class CapabilityMultiplexer {
private static ImmutableMap<Capability, Integer> calculateCapabilityOffsets(
final ImmutableRangeMap<Integer, Capability> agreedCaps) {
final ImmutableMap.Builder<Capability, Integer> capToOffset = ImmutableMap.builder();
for (final Entry<Range<Integer>, Capability> entry : agreedCaps.asMapOfRanges().entrySet()) {
for (final Map.Entry<Range<Integer>, Capability> entry :
agreedCaps.asMapOfRanges().entrySet()) {
capToOffset.put(entry.getValue(), entry.getKey().lowerEndpoint());
}
return capToOffset.build();

@ -69,8 +69,6 @@ import org.mockito.ArgumentCaptor;
public class PeerDiscoveryControllerTest {
private static final byte MOST_SIGNFICANT_BIT_MASK = -128;
private static final RetryDelayFunction LONG_DELAY_FUNCTION = (prev) -> 999999999L;
private static final RetryDelayFunction SHORT_DELAY_FUNCTION = (prev) -> Math.max(100, prev * 2);
private static final PeerRequirement PEER_REQUIREMENT = () -> true;
private static final long TABLE_REFRESH_INTERVAL_MS = TimeUnit.HOURS.toMillis(1);
private PeerDiscoveryController controller;
@ -80,6 +78,14 @@ public class PeerDiscoveryControllerTest {
private final AtomicInteger counter = new AtomicInteger(1);
private final PeerDiscoveryTestHelper helper = new PeerDiscoveryTestHelper();
private static Long longDelayFunction(final Long prev) {
return 999999999L;
}
private static Long shortDelayFunction(final Long prev) {
return Math.max(100, prev * 2);
}
@Before
public void initializeMocks() {
final List<NodeKey> nodeKeys = PeerDiscoveryTestHelper.generateNodeKeys(1);
@ -110,7 +116,7 @@ public class PeerDiscoveryControllerTest {
.timerUtil(timer)
.outboundMessageHandler(outboundMessageHandler)
.build();
controller.setRetryDelayFunction(SHORT_DELAY_FUNCTION);
controller.setRetryDelayFunction(PeerDiscoveryControllerTest::shortDelayFunction);
// Mock the creation of the PING packet, so that we can control the hash,
// which gets validated when receiving the PONG.
@ -387,7 +393,7 @@ public class PeerDiscoveryControllerTest {
final OutboundMessageHandler outboundMessageHandler = mock(OutboundMessageHandler.class);
controller =
getControllerBuilder().peers(peers).outboundMessageHandler(outboundMessageHandler).build();
controller.setRetryDelayFunction(LONG_DELAY_FUNCTION);
controller.setRetryDelayFunction(PeerDiscoveryControllerTest::longDelayFunction);
// Mock the creation of the PING packet, so that we can control the hash, which gets validated
// when
@ -984,7 +990,7 @@ public class PeerDiscoveryControllerTest {
.peers(bootstrapPeers)
.outboundMessageHandler(outboundMessageHandler)
.build();
controller.setRetryDelayFunction(LONG_DELAY_FUNCTION);
controller.setRetryDelayFunction(PeerDiscoveryControllerTest::longDelayFunction);
// Mock the creation of PING packets to control hash PONG packets.
final List<NodeKey> nodeKeys = PeerDiscoveryTestHelper.generateNodeKeys(1);
@ -1322,7 +1328,8 @@ public class PeerDiscoveryControllerTest {
private PeerDiscoveryController startPeerDiscoveryController(
final DiscoveryPeer... bootstrapPeers) {
return startPeerDiscoveryController(LONG_DELAY_FUNCTION, bootstrapPeers);
return startPeerDiscoveryController(
PeerDiscoveryControllerTest::longDelayFunction, bootstrapPeers);
}
private PeerDiscoveryController startPeerDiscoveryController(

@ -21,7 +21,6 @@ import org.hyperledger.besu.util.Subscribers;
import java.net.InetSocketAddress;
import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.atomic.AtomicInteger;
@ -43,7 +42,8 @@ public class MockConnectionInitializer implements ConnectionInitializer {
}
public void completePendingFutures() {
for (Entry<Peer, CompletableFuture<PeerConnection>> conn : incompleteConnections.entrySet()) {
for (Map.Entry<Peer, CompletableFuture<PeerConnection>> conn :
incompleteConnections.entrySet()) {
conn.getValue().complete(MockPeerConnection.create(conn.getKey()));
}
incompleteConnections.clear();

@ -139,10 +139,11 @@ public class PermissioningConfigurationBuilder {
* This method allows support for both keys for now. Whitelist TOML keys will be removed in future
* (breaking change)
*
* @param tomlParseResult
* @param primaryKey
* @param alternateKey
* @return
* @param tomlParseResult result of a prior toml parse
* @param primaryKey key to fetch
* @param alternateKey alternate key to fetch
* @return In order: the array of the primaryKey if it exists, or the array of the alternateKey if
* it exists, or null.
*/
private static TomlArray getAllowlistArray(
final TomlParseResult tomlParseResult, final String primaryKey, final String alternateKey) {

@ -54,7 +54,11 @@ public interface Node<V> {
/** Marks the node as needing to be persisted */
void markDirty();
/** @return True if the node needs to be persisted. */
/**
* Is this node not persisted and needs to be?
*
* @return True if the node needs to be persisted.
*/
boolean isDirty();
String print();

@ -32,7 +32,6 @@ import java.nio.charset.StandardCharsets;
import java.util.NavigableSet;
import java.util.Random;
import java.util.TreeSet;
import java.util.function.Function;
import org.apache.tuweni.bytes.Bytes;
import org.apache.tuweni.bytes.Bytes32;
@ -52,11 +51,14 @@ public class TrieIteratorTest {
@SuppressWarnings("unchecked")
private final LeafHandler<String> leafHandler = mock(LeafHandler.class);
private final Function<String, Bytes> valueSerializer =
value -> Bytes.wrap(value.getBytes(StandardCharsets.UTF_8));
private final DefaultNodeFactory<String> nodeFactory = new DefaultNodeFactory<>(valueSerializer);
private final DefaultNodeFactory<String> nodeFactory =
new DefaultNodeFactory<>(this::valueSerializer);
private final TrieIterator<String> iterator = new TrieIterator<>(leafHandler);
private Bytes valueSerializer(final String value) {
return Bytes.wrap(value.getBytes(StandardCharsets.UTF_8));
}
@Test
public void shouldCallLeafHandlerWhenRootNodeIsALeaf() {
final Node<String> leaf = nodeFactory.createLeaf(bytesToPath(KEY_HASH1), "Leaf");

@ -26,10 +26,10 @@ dependencyManagement {
dependency 'com.google.dagger:dagger:2.28'
dependency 'com.google.dagger:dagger-compiler:2.28'
dependency 'com.google.errorprone:error_prone_annotation:2.3.3'
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_test_helpers:2.3.3'
dependency 'com.google.errorprone:error_prone_annotation:2.4.0'
dependency 'com.google.errorprone:error_prone_check_api:2.4.0'
dependency 'com.google.errorprone:error_prone_core:2.4.0'
dependency 'com.google.errorprone:error_prone_test_helpers:2.4.0'
dependency 'com.google.guava:guava:29.0-jre'

@ -39,7 +39,6 @@ import com.google.common.collect.ImmutableSet;
import io.prometheus.client.Collector;
import io.prometheus.client.Collector.MetricFamilySamples;
import io.prometheus.client.Collector.MetricFamilySamples.Sample;
import io.prometheus.client.Collector.Type;
import io.prometheus.client.CollectorRegistry;
import io.prometheus.client.Counter;
import io.prometheus.client.Summary;
@ -193,10 +192,10 @@ public class PrometheusMetricsSystem implements ObservableMetricsSystem {
private Observation createObservationFromSample(
final MetricCategory category, final Sample sample, final MetricFamilySamples familySamples) {
if (familySamples.type == Type.HISTOGRAM) {
if (familySamples.type == Collector.Type.HISTOGRAM) {
return convertHistogramSampleNamesToLabels(category, sample, familySamples);
}
if (familySamples.type == Type.SUMMARY) {
if (familySamples.type == Collector.Type.SUMMARY) {
return convertSummarySampleNamesToLabels(category, sample, familySamples);
}
return new Observation(

@ -64,7 +64,7 @@ Calculated : ${currentHash}
tasks.register('checkAPIChanges', FileStateChecker) {
description = "Checks that the API for the Plugin-API project does not change without deliberate thought"
files = sourceSets.main.allJava.files
knownHash = 'd2HD6T1USSbVL9OftLuNlmJO25d1WscqrxCIimdhtgM='
knownHash = 'MeOi1ZfvY4m6bft1KkCT6W51vS3MMnStUeIM4eVmv8o='
}
check.dependsOn('checkAPIChanges')

@ -25,9 +25,17 @@ import java.util.List;
* href="https://ethereum.github.io/yellowpaper/paper.pdf">Ethereum Yellow Paper</a>.
*/
public interface BlockBody {
/** @return The list of transactions of the block. */
/**
* Returns the list of transactions of the block.
*
* @return The list of transactions of the block.
*/
public List<? extends Transaction> getTransactions();
/** @return The list of ommers of the block. */
/**
* Returns the list of ommers of the block.
*
* @return The list of ommers of the block.
*/
public List<? extends BlockHeader> getOmmers();
}

Some files were not shown because too many files have changed in this diff Show More

Loading…
Cancel
Save