Merge branch 'main' into zkbesu

Signed-off-by: Daniel Lehrner <daniel.lehrner@consensys.net>
This commit is contained in:
Daniel Lehrner
2024-12-04 15:28:16 +01:00
118 changed files with 1319 additions and 882 deletions

View File

@@ -5,6 +5,7 @@
### Breaking Changes ### Breaking Changes
- Removed Retesteth rpc service and commands [#7833](https://github.com/hyperledger/besu/pull/7783) - Removed Retesteth rpc service and commands [#7833](https://github.com/hyperledger/besu/pull/7783)
- TLS for P2P (early access feature) has been removed [#7942](https://github.com/hyperledger/besu/pull/7942) - TLS for P2P (early access feature) has been removed [#7942](https://github.com/hyperledger/besu/pull/7942)
- In the plugin API, `BesuContext` has been renamed to `ServiceManager` to better reflect its function, plugins must be updated to work with this version
- With the upgrade of the Prometheus Java Metrics library, there are the following changes: - With the upgrade of the Prometheus Java Metrics library, there are the following changes:
- Gauge names are not allowed to end with `total`, therefore the metric `besu_blockchain_difficulty_total` is losing the `_total` suffix - Gauge names are not allowed to end with `total`, therefore the metric `besu_blockchain_difficulty_total` is losing the `_total` suffix
- The `_created` timestamps are not returned by default, you can set the env var `BESU_OPTS="-Dio.prometheus.exporter.includeCreatedTimestamps=true"` to enable them - The `_created` timestamps are not returned by default, you can set the env var `BESU_OPTS="-Dio.prometheus.exporter.includeCreatedTimestamps=true"` to enable them

View File

@@ -458,7 +458,8 @@ public class ThreadBesuNodeRunner implements BesuNodeRunner {
final BesuControllerBuilder builder, final BesuControllerBuilder builder,
final MetricsSystem metricsSystem, final MetricsSystem metricsSystem,
final KeyValueStorageProvider storageProvider, final KeyValueStorageProvider storageProvider,
final MiningConfiguration miningConfiguration) { final MiningConfiguration miningConfiguration,
final ApiConfiguration apiConfiguration) {
builder builder
.synchronizerConfiguration(synchronizerConfiguration) .synchronizerConfiguration(synchronizerConfiguration)
@@ -473,6 +474,7 @@ public class ThreadBesuNodeRunner implements BesuNodeRunner {
.maxRemotelyInitiatedPeers(15) .maxRemotelyInitiatedPeers(15)
.miningParameters(miningConfiguration) .miningParameters(miningConfiguration)
.randomPeerPriority(false) .randomPeerPriority(false)
.apiConfiguration(apiConfiguration)
.besuComponent(null); .besuComponent(null);
return builder.build(); return builder.build();
} }

View File

@@ -672,12 +672,7 @@ public class RunnerBuilder {
final Synchronizer synchronizer = besuController.getSynchronizer(); final Synchronizer synchronizer = besuController.getSynchronizer();
final TransactionSimulator transactionSimulator = final TransactionSimulator transactionSimulator = besuController.getTransactionSimulator();
new TransactionSimulator(
context.getBlockchain(),
context.getWorldStateArchive(),
protocolSchedule,
apiConfiguration.getGasCap());
final Bytes localNodeId = nodeKey.getPublicKey().getEncodedBytes(); final Bytes localNodeId = nodeKey.getPublicKey().getEncodedBytes();
final Optional<NodePermissioningController> nodePermissioningController = final Optional<NodePermissioningController> nodePermissioningController =
@@ -840,7 +835,8 @@ public class RunnerBuilder {
natService, natService,
besuPluginContext.getNamedPlugins(), besuPluginContext.getNamedPlugins(),
dataDir, dataDir,
rpcEndpointServiceImpl); rpcEndpointServiceImpl,
transactionSimulator);
jsonRpcHttpService = jsonRpcHttpService =
Optional.of( Optional.of(
@@ -885,7 +881,8 @@ public class RunnerBuilder {
natService, natService,
besuPluginContext.getNamedPlugins(), besuPluginContext.getNamedPlugins(),
dataDir, dataDir,
rpcEndpointServiceImpl); rpcEndpointServiceImpl,
transactionSimulator);
final Optional<AuthenticationService> authToUse = final Optional<AuthenticationService> authToUse =
engineJsonRpcConfiguration.get().isAuthenticationEnabled() engineJsonRpcConfiguration.get().isAuthenticationEnabled()
@@ -932,7 +929,7 @@ public class RunnerBuilder {
graphQlContextMap.putIfAbsent(GraphQLContextType.SYNCHRONIZER, synchronizer); graphQlContextMap.putIfAbsent(GraphQLContextType.SYNCHRONIZER, synchronizer);
graphQlContextMap.putIfAbsent( graphQlContextMap.putIfAbsent(
GraphQLContextType.CHAIN_ID, protocolSchedule.getChainId().map(UInt256::valueOf)); GraphQLContextType.CHAIN_ID, protocolSchedule.getChainId().map(UInt256::valueOf));
graphQlContextMap.putIfAbsent(GraphQLContextType.GAS_CAP, apiConfiguration.getGasCap()); graphQlContextMap.putIfAbsent(GraphQLContextType.TRANSACTION_SIMULATOR, transactionSimulator);
final GraphQL graphQL; final GraphQL graphQL;
try { try {
graphQL = GraphQLProvider.buildGraphQL(fetchers); graphQL = GraphQLProvider.buildGraphQL(fetchers);
@@ -980,7 +977,8 @@ public class RunnerBuilder {
natService, natService,
besuPluginContext.getNamedPlugins(), besuPluginContext.getNamedPlugins(),
dataDir, dataDir,
rpcEndpointServiceImpl); rpcEndpointServiceImpl,
transactionSimulator);
createLogsSubscriptionService( createLogsSubscriptionService(
context.getBlockchain(), subscriptionManager, privacyParameters, blockchainQueries); context.getBlockchain(), subscriptionManager, privacyParameters, blockchainQueries);
@@ -1060,7 +1058,8 @@ public class RunnerBuilder {
natService, natService,
besuPluginContext.getNamedPlugins(), besuPluginContext.getNamedPlugins(),
dataDir, dataDir,
rpcEndpointServiceImpl); rpcEndpointServiceImpl,
transactionSimulator);
jsonRpcIpcService = jsonRpcIpcService =
Optional.of( Optional.of(
@@ -1099,7 +1098,8 @@ public class RunnerBuilder {
natService, natService,
besuPluginContext.getNamedPlugins(), besuPluginContext.getNamedPlugins(),
dataDir, dataDir,
rpcEndpointServiceImpl); rpcEndpointServiceImpl,
transactionSimulator);
} else { } else {
inProcessRpcMethods = Map.of(); inProcessRpcMethods = Map.of();
} }
@@ -1261,7 +1261,8 @@ public class RunnerBuilder {
final NatService natService, final NatService natService,
final Map<String, BesuPlugin> namedPlugins, final Map<String, BesuPlugin> namedPlugins,
final Path dataDir, final Path dataDir,
final RpcEndpointServiceImpl rpcEndpointServiceImpl) { final RpcEndpointServiceImpl rpcEndpointServiceImpl,
final TransactionSimulator transactionSimulator) {
// sync vertx for engine consensus API, to process requests in FIFO order; // sync vertx for engine consensus API, to process requests in FIFO order;
final Vertx consensusEngineServer = Vertx.vertx(new VertxOptions().setWorkerPoolSize(1)); final Vertx consensusEngineServer = Vertx.vertx(new VertxOptions().setWorkerPoolSize(1));
@@ -1298,7 +1299,8 @@ public class RunnerBuilder {
besuController.getProtocolManager().ethContext().getEthPeers(), besuController.getProtocolManager().ethContext().getEthPeers(),
consensusEngineServer, consensusEngineServer,
apiConfiguration, apiConfiguration,
enodeDnsConfiguration); enodeDnsConfiguration,
transactionSimulator);
methods.putAll(besuController.getAdditionalJsonRpcMethods(jsonRpcApis)); methods.putAll(besuController.getAdditionalJsonRpcMethods(jsonRpcApis));
final var pluginMethods = final var pluginMethods =

View File

@@ -134,7 +134,6 @@ import org.hyperledger.besu.ethereum.storage.StorageProvider;
import org.hyperledger.besu.ethereum.storage.keyvalue.KeyValueSegmentIdentifier; import org.hyperledger.besu.ethereum.storage.keyvalue.KeyValueSegmentIdentifier;
import org.hyperledger.besu.ethereum.storage.keyvalue.KeyValueStorageProvider; import org.hyperledger.besu.ethereum.storage.keyvalue.KeyValueStorageProvider;
import org.hyperledger.besu.ethereum.storage.keyvalue.KeyValueStorageProviderBuilder; import org.hyperledger.besu.ethereum.storage.keyvalue.KeyValueStorageProviderBuilder;
import org.hyperledger.besu.ethereum.transaction.TransactionSimulator;
import org.hyperledger.besu.ethereum.worldstate.DataStorageConfiguration; import org.hyperledger.besu.ethereum.worldstate.DataStorageConfiguration;
import org.hyperledger.besu.ethereum.worldstate.DiffBasedSubStorageConfiguration; import org.hyperledger.besu.ethereum.worldstate.DiffBasedSubStorageConfiguration;
import org.hyperledger.besu.ethereum.worldstate.ImmutableDataStorageConfiguration; import org.hyperledger.besu.ethereum.worldstate.ImmutableDataStorageConfiguration;
@@ -339,6 +338,8 @@ public class BesuCommand implements DefaultCommandValues, Runnable {
Suppliers.memoize(this::readGenesisConfigOptions); Suppliers.memoize(this::readGenesisConfigOptions);
private final Supplier<MiningConfiguration> miningParametersSupplier = private final Supplier<MiningConfiguration> miningParametersSupplier =
Suppliers.memoize(this::getMiningParameters); Suppliers.memoize(this::getMiningParameters);
private final Supplier<ApiConfiguration> apiConfigurationSupplier =
Suppliers.memoize(this::getApiConfiguration);
private RocksDBPlugin rocksDBPlugin; private RocksDBPlugin rocksDBPlugin;
@@ -712,7 +713,6 @@ public class BesuCommand implements DefaultCommandValues, Runnable {
private WebSocketConfiguration webSocketConfiguration; private WebSocketConfiguration webSocketConfiguration;
private JsonRpcIpcConfiguration jsonRpcIpcConfiguration; private JsonRpcIpcConfiguration jsonRpcIpcConfiguration;
private InProcessRpcConfiguration inProcessRpcConfiguration; private InProcessRpcConfiguration inProcessRpcConfiguration;
private ApiConfiguration apiConfiguration;
private MetricsConfiguration metricsConfiguration; private MetricsConfiguration metricsConfiguration;
private Optional<PermissioningConfiguration> permissioningConfiguration; private Optional<PermissioningConfiguration> permissioningConfiguration;
private DataStorageConfiguration dataStorageConfiguration; private DataStorageConfiguration dataStorageConfiguration;
@@ -1237,7 +1237,7 @@ public class BesuCommand implements DefaultCommandValues, Runnable {
webSocketConfiguration, webSocketConfiguration,
jsonRpcIpcConfiguration, jsonRpcIpcConfiguration,
inProcessRpcConfiguration, inProcessRpcConfiguration,
apiConfiguration, apiConfigurationSupplier.get(),
metricsConfiguration, metricsConfiguration,
permissioningConfiguration, permissioningConfiguration,
staticNodes, staticNodes,
@@ -1249,11 +1249,7 @@ public class BesuCommand implements DefaultCommandValues, Runnable {
besuController.getProtocolContext().getBlockchain(), besuController.getProtocolSchedule()); besuController.getProtocolContext().getBlockchain(), besuController.getProtocolSchedule());
transactionSimulationServiceImpl.init( transactionSimulationServiceImpl.init(
besuController.getProtocolContext().getBlockchain(), besuController.getProtocolContext().getBlockchain(),
new TransactionSimulator( besuController.getTransactionSimulator());
besuController.getProtocolContext().getBlockchain(),
besuController.getProtocolContext().getWorldStateArchive(),
besuController.getProtocolSchedule(),
apiConfiguration.getGasCap()));
rpcEndpointServiceImpl.init(runner.getInProcessRpcMethods()); rpcEndpointServiceImpl.init(runner.getInProcessRpcMethods());
besuPluginContext.addService( besuPluginContext.addService(
@@ -1447,7 +1443,6 @@ public class BesuCommand implements DefaultCommandValues, Runnable {
validateTransactionPoolOptions(); validateTransactionPoolOptions();
validateDataStorageOptions(); validateDataStorageOptions();
validateGraphQlOptions(); validateGraphQlOptions();
validateApiOptions();
validateConsensusSyncCompatibilityOptions(); validateConsensusSyncCompatibilityOptions();
validatePluginOptions(); validatePluginOptions();
} }
@@ -1705,7 +1700,6 @@ public class BesuCommand implements DefaultCommandValues, Runnable {
unstableIpcOptions.getIpcPath(), unstableIpcOptions.getIpcPath(),
unstableIpcOptions.getRpcIpcApis()); unstableIpcOptions.getRpcIpcApis());
inProcessRpcConfiguration = inProcessRpcOptions.toDomainObject(); inProcessRpcConfiguration = inProcessRpcOptions.toDomainObject();
apiConfiguration = apiConfigurationOptions.apiConfiguration();
dataStorageConfiguration = getDataStorageConfiguration(); dataStorageConfiguration = getDataStorageConfiguration();
// hostsWhitelist is a hidden option. If it is specified, add the list to hostAllowlist // hostsWhitelist is a hidden option. If it is specified, add the list to hostAllowlist
if (!hostsWhitelist.isEmpty()) { if (!hostsWhitelist.isEmpty()) {
@@ -1823,6 +1817,7 @@ public class BesuCommand implements DefaultCommandValues, Runnable {
.chainPruningConfiguration(unstableChainPruningOptions.toDomainObject()) .chainPruningConfiguration(unstableChainPruningOptions.toDomainObject())
.cacheLastBlocks(numberOfblocksToCache) .cacheLastBlocks(numberOfblocksToCache)
.genesisStateHashCacheEnabled(genesisStateHashCacheEnabled) .genesisStateHashCacheEnabled(genesisStateHashCacheEnabled)
.apiConfiguration(apiConfigurationSupplier.get())
.besuComponent(besuComponent); .besuComponent(besuComponent);
if (DataStorageFormat.BONSAI.equals(getDataStorageConfiguration().getDataStorageFormat())) { if (DataStorageFormat.BONSAI.equals(getDataStorageConfiguration().getDataStorageFormat())) {
final DiffBasedSubStorageConfiguration subStorageConfiguration = final DiffBasedSubStorageConfiguration subStorageConfiguration =
@@ -2148,6 +2143,11 @@ public class BesuCommand implements DefaultCommandValues, Runnable {
return miningParameters; return miningParameters;
} }
private ApiConfiguration getApiConfiguration() {
validateApiOptions();
return apiConfigurationOptions.apiConfiguration();
}
/** /**
* Get the data storage configuration * Get the data storage configuration
* *

View File

@@ -35,6 +35,7 @@ import org.hyperledger.besu.ethereum.eth.transactions.TransactionPool;
import org.hyperledger.besu.ethereum.mainnet.ProtocolSchedule; import org.hyperledger.besu.ethereum.mainnet.ProtocolSchedule;
import org.hyperledger.besu.ethereum.p2p.config.SubProtocolConfiguration; import org.hyperledger.besu.ethereum.p2p.config.SubProtocolConfiguration;
import org.hyperledger.besu.ethereum.storage.StorageProvider; import org.hyperledger.besu.ethereum.storage.StorageProvider;
import org.hyperledger.besu.ethereum.transaction.TransactionSimulator;
import org.hyperledger.besu.ethereum.worldstate.DataStorageConfiguration; import org.hyperledger.besu.ethereum.worldstate.DataStorageConfiguration;
import java.io.Closeable; import java.io.Closeable;
@@ -66,7 +67,6 @@ public class BesuController implements java.io.Closeable {
private final NodeKey nodeKey; private final NodeKey nodeKey;
private final Synchronizer synchronizer; private final Synchronizer synchronizer;
private final JsonRpcMethods additionalJsonRpcMethodsFactory; private final JsonRpcMethods additionalJsonRpcMethodsFactory;
private final TransactionPool transactionPool; private final TransactionPool transactionPool;
private final MiningCoordinator miningCoordinator; private final MiningCoordinator miningCoordinator;
private final PrivacyParameters privacyParameters; private final PrivacyParameters privacyParameters;
@@ -77,6 +77,7 @@ public class BesuController implements java.io.Closeable {
private final EthPeers ethPeers; private final EthPeers ethPeers;
private final StorageProvider storageProvider; private final StorageProvider storageProvider;
private final DataStorageConfiguration dataStorageConfiguration; private final DataStorageConfiguration dataStorageConfiguration;
private final TransactionSimulator transactionSimulator;
/** /**
* Instantiates a new Besu controller. * Instantiates a new Besu controller.
@@ -99,6 +100,7 @@ public class BesuController implements java.io.Closeable {
* @param ethPeers the eth peers * @param ethPeers the eth peers
* @param storageProvider the storage provider * @param storageProvider the storage provider
* @param dataStorageConfiguration the data storage configuration * @param dataStorageConfiguration the data storage configuration
* @param transactionSimulator the transaction simulator
*/ */
BesuController( BesuController(
final ProtocolSchedule protocolSchedule, final ProtocolSchedule protocolSchedule,
@@ -118,7 +120,8 @@ public class BesuController implements java.io.Closeable {
final PluginServiceFactory additionalPluginServices, final PluginServiceFactory additionalPluginServices,
final EthPeers ethPeers, final EthPeers ethPeers,
final StorageProvider storageProvider, final StorageProvider storageProvider,
final DataStorageConfiguration dataStorageConfiguration) { final DataStorageConfiguration dataStorageConfiguration,
final TransactionSimulator transactionSimulator) {
this.protocolSchedule = protocolSchedule; this.protocolSchedule = protocolSchedule;
this.protocolContext = protocolContext; this.protocolContext = protocolContext;
this.ethProtocolManager = ethProtocolManager; this.ethProtocolManager = ethProtocolManager;
@@ -137,6 +140,7 @@ public class BesuController implements java.io.Closeable {
this.ethPeers = ethPeers; this.ethPeers = ethPeers;
this.storageProvider = storageProvider; this.storageProvider = storageProvider;
this.dataStorageConfiguration = dataStorageConfiguration; this.dataStorageConfiguration = dataStorageConfiguration;
this.transactionSimulator = transactionSimulator;
} }
/** /**
@@ -307,6 +311,15 @@ public class BesuController implements java.io.Closeable {
return dataStorageConfiguration; return dataStorageConfiguration;
} }
/**
* Gets the transaction simulator
*
* @return the transaction simulator
*/
public TransactionSimulator getTransactionSimulator() {
return transactionSimulator;
}
/** The type Builder. */ /** The type Builder. */
public static class Builder { public static class Builder {
/** Instantiates a new Builder. */ /** Instantiates a new Builder. */

View File

@@ -28,6 +28,7 @@ import org.hyperledger.besu.datatypes.Hash;
import org.hyperledger.besu.ethereum.ConsensusContext; import org.hyperledger.besu.ethereum.ConsensusContext;
import org.hyperledger.besu.ethereum.GasLimitCalculator; import org.hyperledger.besu.ethereum.GasLimitCalculator;
import org.hyperledger.besu.ethereum.ProtocolContext; import org.hyperledger.besu.ethereum.ProtocolContext;
import org.hyperledger.besu.ethereum.api.ApiConfiguration;
import org.hyperledger.besu.ethereum.api.jsonrpc.methods.JsonRpcMethods; import org.hyperledger.besu.ethereum.api.jsonrpc.methods.JsonRpcMethods;
import org.hyperledger.besu.ethereum.blockcreation.MiningCoordinator; import org.hyperledger.besu.ethereum.blockcreation.MiningCoordinator;
import org.hyperledger.besu.ethereum.chain.BadBlockManager; import org.hyperledger.besu.ethereum.chain.BadBlockManager;
@@ -84,6 +85,7 @@ import org.hyperledger.besu.ethereum.p2p.config.NetworkingConfiguration;
import org.hyperledger.besu.ethereum.p2p.config.SubProtocolConfiguration; import org.hyperledger.besu.ethereum.p2p.config.SubProtocolConfiguration;
import org.hyperledger.besu.ethereum.storage.StorageProvider; import org.hyperledger.besu.ethereum.storage.StorageProvider;
import org.hyperledger.besu.ethereum.storage.keyvalue.KeyValueSegmentIdentifier; import org.hyperledger.besu.ethereum.storage.keyvalue.KeyValueSegmentIdentifier;
import org.hyperledger.besu.ethereum.transaction.TransactionSimulator;
import org.hyperledger.besu.ethereum.trie.diffbased.bonsai.BonsaiWorldStateProvider; import org.hyperledger.besu.ethereum.trie.diffbased.bonsai.BonsaiWorldStateProvider;
import org.hyperledger.besu.ethereum.trie.diffbased.bonsai.cache.BonsaiCachedMerkleTrieLoader; import org.hyperledger.besu.ethereum.trie.diffbased.bonsai.cache.BonsaiCachedMerkleTrieLoader;
import org.hyperledger.besu.ethereum.trie.diffbased.bonsai.storage.BonsaiWorldStateKeyValueStorage; import org.hyperledger.besu.ethereum.trie.diffbased.bonsai.storage.BonsaiWorldStateKeyValueStorage;
@@ -211,6 +213,12 @@ public abstract class BesuControllerBuilder implements MiningParameterOverrides
/** whether parallel transaction processing is enabled or not */ /** whether parallel transaction processing is enabled or not */
protected boolean isParallelTxProcessingEnabled; protected boolean isParallelTxProcessingEnabled;
/** The API configuration */
protected ApiConfiguration apiConfiguration;
/** The transaction simulator */
protected TransactionSimulator transactionSimulator;
/** Instantiates a new Besu controller builder. */ /** Instantiates a new Besu controller builder. */
protected BesuControllerBuilder() {} protected BesuControllerBuilder() {}
@@ -272,6 +280,17 @@ public abstract class BesuControllerBuilder implements MiningParameterOverrides
return this; return this;
} }
/**
* API configuration besu controller builder.
*
* @param apiConfiguration the API config
* @return the besu controller builder
*/
public BesuControllerBuilder apiConfiguration(final ApiConfiguration apiConfiguration) {
this.apiConfiguration = apiConfiguration;
return this;
}
/** /**
* Eth protocol configuration besu controller builder. * Eth protocol configuration besu controller builder.
* *
@@ -556,6 +575,7 @@ public abstract class BesuControllerBuilder implements MiningParameterOverrides
checkNotNull(gasLimitCalculator, "Missing gas limit calculator"); checkNotNull(gasLimitCalculator, "Missing gas limit calculator");
checkNotNull(evmConfiguration, "Missing evm config"); checkNotNull(evmConfiguration, "Missing evm config");
checkNotNull(networkingConfiguration, "Missing network configuration"); checkNotNull(networkingConfiguration, "Missing network configuration");
checkNotNull(apiConfiguration, "Missing API configuration");
checkNotNull(dataStorageConfiguration, "Missing data storage configuration"); checkNotNull(dataStorageConfiguration, "Missing data storage configuration");
checkNotNull(besuComponent, "Must supply a BesuComponent"); checkNotNull(besuComponent, "Must supply a BesuComponent");
prepForBuild(); prepForBuild();
@@ -604,6 +624,10 @@ public abstract class BesuControllerBuilder implements MiningParameterOverrides
genesisState.writeStateTo(worldStateArchive.getMutable()); genesisState.writeStateTo(worldStateArchive.getMutable());
} }
transactionSimulator =
new TransactionSimulator(
blockchain, worldStateArchive, protocolSchedule, apiConfiguration.getGasCap());
final var consensusContext = final var consensusContext =
createConsensusContext(blockchain, worldStateArchive, protocolSchedule); createConsensusContext(blockchain, worldStateArchive, protocolSchedule);
@@ -795,7 +819,8 @@ public abstract class BesuControllerBuilder implements MiningParameterOverrides
additionalPluginServices, additionalPluginServices,
ethPeers, ethPeers,
storageProvider, storageProvider,
dataStorageConfiguration); dataStorageConfiguration,
transactionSimulator);
} }
private GenesisState getGenesisState( private GenesisState getGenesisState(

View File

@@ -79,7 +79,6 @@ import org.hyperledger.besu.ethereum.eth.sync.state.SyncState;
import org.hyperledger.besu.ethereum.eth.transactions.TransactionPool; import org.hyperledger.besu.ethereum.eth.transactions.TransactionPool;
import org.hyperledger.besu.ethereum.mainnet.ProtocolSchedule; import org.hyperledger.besu.ethereum.mainnet.ProtocolSchedule;
import org.hyperledger.besu.ethereum.p2p.config.SubProtocolConfiguration; import org.hyperledger.besu.ethereum.p2p.config.SubProtocolConfiguration;
import org.hyperledger.besu.ethereum.transaction.TransactionSimulator;
import org.hyperledger.besu.ethereum.worldstate.WorldStateArchive; import org.hyperledger.besu.ethereum.worldstate.WorldStateArchive;
import org.hyperledger.besu.plugin.services.BesuEvents; import org.hyperledger.besu.plugin.services.BesuEvents;
import org.hyperledger.besu.util.Subscribers; import org.hyperledger.besu.util.Subscribers;
@@ -399,8 +398,6 @@ public class QbftBesuControllerBuilder extends BftBesuControllerBuilder {
BlockValidatorProvider.forkingValidatorProvider( BlockValidatorProvider.forkingValidatorProvider(
blockchain, epochManager, bftBlockInterface().get(), validatorOverrides); blockchain, epochManager, bftBlockInterface().get(), validatorOverrides);
final TransactionSimulator transactionSimulator =
new TransactionSimulator(blockchain, worldStateArchive, protocolSchedule, 0L);
transactionValidatorProvider = transactionValidatorProvider =
new TransactionValidatorProvider( new TransactionValidatorProvider(
blockchain, new ValidatorContractController(transactionSimulator), qbftForksSchedule); blockchain, new ValidatorContractController(transactionSimulator), qbftForksSchedule);

View File

@@ -20,7 +20,6 @@ import static org.hyperledger.besu.ethereum.mainnet.feemarket.ExcessBlobGasCalcu
import org.hyperledger.besu.datatypes.BlobGas; import org.hyperledger.besu.datatypes.BlobGas;
import org.hyperledger.besu.datatypes.Hash; import org.hyperledger.besu.datatypes.Hash;
import org.hyperledger.besu.datatypes.Wei; import org.hyperledger.besu.datatypes.Wei;
import org.hyperledger.besu.ethereum.api.jsonrpc.internal.methods.TraceBlock.ChainUpdater;
import org.hyperledger.besu.ethereum.api.jsonrpc.internal.processor.Tracer; import org.hyperledger.besu.ethereum.api.jsonrpc.internal.processor.Tracer;
import org.hyperledger.besu.ethereum.api.query.BlockchainQueries; import org.hyperledger.besu.ethereum.api.query.BlockchainQueries;
import org.hyperledger.besu.ethereum.chain.Blockchain; import org.hyperledger.besu.ethereum.chain.Blockchain;
@@ -156,14 +155,14 @@ public class TraceServiceImpl implements TraceService {
blocks.get(0).getHash(), blocks.get(0).getHash(),
traceableState -> { traceableState -> {
final WorldUpdater worldStateUpdater = traceableState.updater(); final WorldUpdater worldStateUpdater = traceableState.updater();
final ChainUpdater chainUpdater = new ChainUpdater(traceableState, worldStateUpdater);
beforeTracing.accept(worldStateUpdater); beforeTracing.accept(worldStateUpdater);
final List<TransactionProcessingResult> results = new ArrayList<>(); final List<TransactionProcessingResult> results = new ArrayList<>();
blocks.forEach( blocks.forEach(
block -> { block -> {
results.addAll(trace(blockchain, block, chainUpdater, tracer)); results.addAll(trace(blockchain, block, worldStateUpdater, tracer));
worldStateUpdater.commit();
}); });
afterTracing.accept(chainUpdater.getNextUpdater()); afterTracing.accept(worldStateUpdater);
return Optional.of(results); return Optional.of(results);
}); });
} }
@@ -178,7 +177,7 @@ public class TraceServiceImpl implements TraceService {
blockchainQueries, blockchainQueries,
block.getHash(), block.getHash(),
traceableState -> traceableState ->
Optional.of(trace(blockchain, block, new ChainUpdater(traceableState), tracer))); Optional.of(trace(blockchain, block, traceableState.updater(), tracer)));
return results; return results;
} }
@@ -186,7 +185,7 @@ public class TraceServiceImpl implements TraceService {
private List<TransactionProcessingResult> trace( private List<TransactionProcessingResult> trace(
final Blockchain blockchain, final Blockchain blockchain,
final Block block, final Block block,
final ChainUpdater chainUpdater, final WorldUpdater worldUpdater,
final BlockAwareOperationTracer tracer) { final BlockAwareOperationTracer tracer) {
final List<TransactionProcessingResult> results = new ArrayList<>(); final List<TransactionProcessingResult> results = new ArrayList<>();
final ProtocolSpec protocolSpec = protocolSchedule.getByBlockHeader(block.getHeader()); final ProtocolSpec protocolSpec = protocolSchedule.getByBlockHeader(block.getHeader());
@@ -209,7 +208,6 @@ public class TraceServiceImpl implements TraceService {
.map(parent -> calculateExcessBlobGasForParent(protocolSpec, parent)) .map(parent -> calculateExcessBlobGasForParent(protocolSpec, parent))
.orElse(BlobGas.ZERO)); .orElse(BlobGas.ZERO));
final WorldUpdater worldUpdater = chainUpdater.getNextUpdater();
final TransactionProcessingResult result = final TransactionProcessingResult result =
transactionProcessor.processTransaction( transactionProcessor.processTransaction(
worldUpdater, worldUpdater,

View File

@@ -28,6 +28,7 @@ import org.hyperledger.besu.cryptoservices.NodeKeyUtils;
import org.hyperledger.besu.datatypes.Address; import org.hyperledger.besu.datatypes.Address;
import org.hyperledger.besu.enclave.EnclaveFactory; import org.hyperledger.besu.enclave.EnclaveFactory;
import org.hyperledger.besu.ethereum.GasLimitCalculator; import org.hyperledger.besu.ethereum.GasLimitCalculator;
import org.hyperledger.besu.ethereum.api.ImmutableApiConfiguration;
import org.hyperledger.besu.ethereum.core.BlockHeader; import org.hyperledger.besu.ethereum.core.BlockHeader;
import org.hyperledger.besu.ethereum.core.BlockHeaderTestFixture; import org.hyperledger.besu.ethereum.core.BlockHeaderTestFixture;
import org.hyperledger.besu.ethereum.core.InMemoryKeyValueStorageProvider; import org.hyperledger.besu.ethereum.core.InMemoryKeyValueStorageProvider;
@@ -162,6 +163,7 @@ class FlexGroupPrivacyTest {
.evmConfiguration(EvmConfiguration.DEFAULT) .evmConfiguration(EvmConfiguration.DEFAULT)
.networkConfiguration(NetworkingConfiguration.create()) .networkConfiguration(NetworkingConfiguration.create())
.besuComponent(context) .besuComponent(context)
.apiConfiguration(ImmutableApiConfiguration.builder().build())
.build(); .build();
} }
} }

View File

@@ -41,6 +41,7 @@ import org.hyperledger.besu.enclave.EnclaveFactory;
import org.hyperledger.besu.enclave.types.ReceiveResponse; import org.hyperledger.besu.enclave.types.ReceiveResponse;
import org.hyperledger.besu.ethereum.GasLimitCalculator; import org.hyperledger.besu.ethereum.GasLimitCalculator;
import org.hyperledger.besu.ethereum.ProtocolContext; import org.hyperledger.besu.ethereum.ProtocolContext;
import org.hyperledger.besu.ethereum.api.ImmutableApiConfiguration;
import org.hyperledger.besu.ethereum.chain.DefaultBlockchain; import org.hyperledger.besu.ethereum.chain.DefaultBlockchain;
import org.hyperledger.besu.ethereum.core.Block; import org.hyperledger.besu.ethereum.core.Block;
import org.hyperledger.besu.ethereum.core.BlockDataGenerator; import org.hyperledger.besu.ethereum.core.BlockDataGenerator;
@@ -558,6 +559,7 @@ public class PrivacyReorgTest {
.evmConfiguration(EvmConfiguration.DEFAULT) .evmConfiguration(EvmConfiguration.DEFAULT)
.networkConfiguration(NetworkingConfiguration.create()) .networkConfiguration(NetworkingConfiguration.create())
.besuComponent(context) .besuComponent(context)
.apiConfiguration(ImmutableApiConfiguration.builder().build())
.build(); .build();
return retval; return retval;
} }

View File

@@ -28,6 +28,7 @@ import org.hyperledger.besu.controller.BesuController;
import org.hyperledger.besu.cryptoservices.NodeKeyUtils; import org.hyperledger.besu.cryptoservices.NodeKeyUtils;
import org.hyperledger.besu.datatypes.Address; import org.hyperledger.besu.datatypes.Address;
import org.hyperledger.besu.ethereum.GasLimitCalculator; import org.hyperledger.besu.ethereum.GasLimitCalculator;
import org.hyperledger.besu.ethereum.api.ImmutableApiConfiguration;
import org.hyperledger.besu.ethereum.core.BlockHeader; import org.hyperledger.besu.ethereum.core.BlockHeader;
import org.hyperledger.besu.ethereum.core.BlockHeaderTestFixture; import org.hyperledger.besu.ethereum.core.BlockHeaderTestFixture;
import org.hyperledger.besu.ethereum.core.InMemoryKeyValueStorageProvider; import org.hyperledger.besu.ethereum.core.InMemoryKeyValueStorageProvider;
@@ -137,6 +138,7 @@ class PrivacyTest {
.evmConfiguration(EvmConfiguration.DEFAULT) .evmConfiguration(EvmConfiguration.DEFAULT)
.networkConfiguration(NetworkingConfiguration.create()) .networkConfiguration(NetworkingConfiguration.create())
.besuComponent(context) .besuComponent(context)
.apiConfiguration(ImmutableApiConfiguration.builder().build())
.build(); .build();
} }
} }

View File

@@ -510,6 +510,7 @@ public final class RunnerTest {
.besuComponent(mock(BesuComponent.class)) .besuComponent(mock(BesuComponent.class))
.maxPeers(25) .maxPeers(25)
.maxRemotelyInitiatedPeers(15) .maxRemotelyInitiatedPeers(15)
.apiConfiguration(ImmutableApiConfiguration.builder().build())
.build(); .build();
} }
} }

View File

@@ -25,6 +25,7 @@ import org.hyperledger.besu.components.BesuComponent;
import org.hyperledger.besu.controller.BesuController; import org.hyperledger.besu.controller.BesuController;
import org.hyperledger.besu.cryptoservices.NodeKeyUtils; import org.hyperledger.besu.cryptoservices.NodeKeyUtils;
import org.hyperledger.besu.ethereum.GasLimitCalculator; import org.hyperledger.besu.ethereum.GasLimitCalculator;
import org.hyperledger.besu.ethereum.api.ImmutableApiConfiguration;
import org.hyperledger.besu.ethereum.chain.Blockchain; import org.hyperledger.besu.ethereum.chain.Blockchain;
import org.hyperledger.besu.ethereum.core.Block; import org.hyperledger.besu.ethereum.core.Block;
import org.hyperledger.besu.ethereum.core.BlockBody; import org.hyperledger.besu.ethereum.core.BlockBody;
@@ -105,6 +106,7 @@ public final class RlpBlockExporterTest {
.evmConfiguration(EvmConfiguration.DEFAULT) .evmConfiguration(EvmConfiguration.DEFAULT)
.networkConfiguration(NetworkingConfiguration.create()) .networkConfiguration(NetworkingConfiguration.create())
.besuComponent(mock(BesuComponent.class)) .besuComponent(mock(BesuComponent.class))
.apiConfiguration(ImmutableApiConfiguration.builder().build())
.build(); .build();
} }

View File

@@ -28,6 +28,7 @@ import org.hyperledger.besu.cryptoservices.NodeKeyUtils;
import org.hyperledger.besu.datatypes.Address; import org.hyperledger.besu.datatypes.Address;
import org.hyperledger.besu.datatypes.Wei; import org.hyperledger.besu.datatypes.Wei;
import org.hyperledger.besu.ethereum.GasLimitCalculator; import org.hyperledger.besu.ethereum.GasLimitCalculator;
import org.hyperledger.besu.ethereum.api.ImmutableApiConfiguration;
import org.hyperledger.besu.ethereum.chain.Blockchain; import org.hyperledger.besu.ethereum.chain.Blockchain;
import org.hyperledger.besu.ethereum.core.Block; import org.hyperledger.besu.ethereum.core.Block;
import org.hyperledger.besu.ethereum.core.BlockBody; import org.hyperledger.besu.ethereum.core.BlockBody;
@@ -475,6 +476,7 @@ public abstract class JsonBlockImporterTest {
.evmConfiguration(EvmConfiguration.DEFAULT) .evmConfiguration(EvmConfiguration.DEFAULT)
.networkConfiguration(NetworkingConfiguration.create()) .networkConfiguration(NetworkingConfiguration.create())
.besuComponent(DaggerJsonBlockImporterTest_JsonBlockImportComponent.builder().build()) .besuComponent(DaggerJsonBlockImporterTest_JsonBlockImportComponent.builder().build())
.apiConfiguration(ImmutableApiConfiguration.builder().build())
.build(); .build();
} }

View File

@@ -25,6 +25,7 @@ import org.hyperledger.besu.config.MergeConfiguration;
import org.hyperledger.besu.controller.BesuController; import org.hyperledger.besu.controller.BesuController;
import org.hyperledger.besu.cryptoservices.NodeKeyUtils; import org.hyperledger.besu.cryptoservices.NodeKeyUtils;
import org.hyperledger.besu.ethereum.GasLimitCalculator; import org.hyperledger.besu.ethereum.GasLimitCalculator;
import org.hyperledger.besu.ethereum.api.ImmutableApiConfiguration;
import org.hyperledger.besu.ethereum.core.InMemoryKeyValueStorageProvider; import org.hyperledger.besu.ethereum.core.InMemoryKeyValueStorageProvider;
import org.hyperledger.besu.ethereum.core.MiningConfiguration; import org.hyperledger.besu.ethereum.core.MiningConfiguration;
import org.hyperledger.besu.ethereum.core.PrivacyParameters; import org.hyperledger.besu.ethereum.core.PrivacyParameters;
@@ -80,6 +81,7 @@ public final class RlpBlockImporterTest {
.evmConfiguration(EvmConfiguration.DEFAULT) .evmConfiguration(EvmConfiguration.DEFAULT)
.networkConfiguration(NetworkingConfiguration.create()) .networkConfiguration(NetworkingConfiguration.create())
.besuComponent(mock(BesuComponent.class)) .besuComponent(mock(BesuComponent.class))
.apiConfiguration(ImmutableApiConfiguration.builder().build())
.build(); .build();
final RlpBlockImporter.ImportResult result = final RlpBlockImporter.ImportResult result =
rlpBlockImporter.importBlockchain(source, targetController, false); rlpBlockImporter.importBlockchain(source, targetController, false);
@@ -114,6 +116,7 @@ public final class RlpBlockImporterTest {
.evmConfiguration(EvmConfiguration.DEFAULT) .evmConfiguration(EvmConfiguration.DEFAULT)
.networkConfiguration(NetworkingConfiguration.create()) .networkConfiguration(NetworkingConfiguration.create())
.besuComponent(mock(BesuComponent.class)) .besuComponent(mock(BesuComponent.class))
.apiConfiguration(ImmutableApiConfiguration.builder().build())
.build(); .build();
assertThatThrownBy( assertThatThrownBy(
@@ -145,6 +148,7 @@ public final class RlpBlockImporterTest {
.evmConfiguration(EvmConfiguration.DEFAULT) .evmConfiguration(EvmConfiguration.DEFAULT)
.networkConfiguration(NetworkingConfiguration.create()) .networkConfiguration(NetworkingConfiguration.create())
.besuComponent(mock(BesuComponent.class)) .besuComponent(mock(BesuComponent.class))
.apiConfiguration(ImmutableApiConfiguration.builder().build())
.build(); .build();
final RlpBlockImporter.ImportResult result = final RlpBlockImporter.ImportResult result =

View File

@@ -296,6 +296,7 @@ public abstract class CommandTestAbstract {
when(mockControllerBuilder.cacheLastBlocks(any())).thenReturn(mockControllerBuilder); when(mockControllerBuilder.cacheLastBlocks(any())).thenReturn(mockControllerBuilder);
when(mockControllerBuilder.genesisStateHashCacheEnabled(any())) when(mockControllerBuilder.genesisStateHashCacheEnabled(any()))
.thenReturn(mockControllerBuilder); .thenReturn(mockControllerBuilder);
when(mockControllerBuilder.apiConfiguration(any())).thenReturn(mockControllerBuilder);
when(mockControllerBuilder.build()).thenReturn(mockController); when(mockControllerBuilder.build()).thenReturn(mockController);
lenient().when(mockController.getProtocolManager()).thenReturn(mockEthProtocolManager); lenient().when(mockController.getProtocolManager()).thenReturn(mockEthProtocolManager);

View File

@@ -29,6 +29,7 @@ import org.hyperledger.besu.datatypes.Address;
import org.hyperledger.besu.datatypes.Hash; import org.hyperledger.besu.datatypes.Hash;
import org.hyperledger.besu.datatypes.Wei; import org.hyperledger.besu.datatypes.Wei;
import org.hyperledger.besu.ethereum.GasLimitCalculator; import org.hyperledger.besu.ethereum.GasLimitCalculator;
import org.hyperledger.besu.ethereum.api.ImmutableApiConfiguration;
import org.hyperledger.besu.ethereum.core.Block; import org.hyperledger.besu.ethereum.core.Block;
import org.hyperledger.besu.ethereum.core.BlockBody; import org.hyperledger.besu.ethereum.core.BlockBody;
import org.hyperledger.besu.ethereum.core.BlockHeader; import org.hyperledger.besu.ethereum.core.BlockHeader;
@@ -158,7 +159,8 @@ public abstract class AbstractBftBesuControllerBuilderTest {
.gasLimitCalculator(gasLimitCalculator) .gasLimitCalculator(gasLimitCalculator)
.evmConfiguration(EvmConfiguration.DEFAULT) .evmConfiguration(EvmConfiguration.DEFAULT)
.besuComponent(mock(BesuComponent.class)) .besuComponent(mock(BesuComponent.class))
.networkConfiguration(NetworkingConfiguration.create()); .networkConfiguration(NetworkingConfiguration.create())
.apiConfiguration(ImmutableApiConfiguration.builder().build());
} }
protected abstract void setupBftGenesisConfigFile() throws JsonProcessingException; protected abstract void setupBftGenesisConfigFile() throws JsonProcessingException;

View File

@@ -33,6 +33,7 @@ import org.hyperledger.besu.datatypes.Address;
import org.hyperledger.besu.datatypes.Hash; import org.hyperledger.besu.datatypes.Hash;
import org.hyperledger.besu.datatypes.Wei; import org.hyperledger.besu.datatypes.Wei;
import org.hyperledger.besu.ethereum.GasLimitCalculator; import org.hyperledger.besu.ethereum.GasLimitCalculator;
import org.hyperledger.besu.ethereum.api.ImmutableApiConfiguration;
import org.hyperledger.besu.ethereum.core.Block; import org.hyperledger.besu.ethereum.core.Block;
import org.hyperledger.besu.ethereum.core.BlockBody; import org.hyperledger.besu.ethereum.core.BlockBody;
import org.hyperledger.besu.ethereum.core.BlockHeader; import org.hyperledger.besu.ethereum.core.BlockHeader;
@@ -191,7 +192,8 @@ public class CliqueBesuControllerBuilderTest {
.gasLimitCalculator(gasLimitCalculator) .gasLimitCalculator(gasLimitCalculator)
.evmConfiguration(EvmConfiguration.DEFAULT) .evmConfiguration(EvmConfiguration.DEFAULT)
.besuComponent(mock(BesuComponent.class)) .besuComponent(mock(BesuComponent.class))
.networkConfiguration(NetworkingConfiguration.create()); .networkConfiguration(NetworkingConfiguration.create())
.apiConfiguration(ImmutableApiConfiguration.builder().build());
} }
@Test @Test

View File

@@ -33,6 +33,7 @@ import org.hyperledger.besu.cryptoservices.NodeKeyUtils;
import org.hyperledger.besu.datatypes.Hash; import org.hyperledger.besu.datatypes.Hash;
import org.hyperledger.besu.datatypes.Wei; import org.hyperledger.besu.datatypes.Wei;
import org.hyperledger.besu.ethereum.GasLimitCalculator; import org.hyperledger.besu.ethereum.GasLimitCalculator;
import org.hyperledger.besu.ethereum.api.ImmutableApiConfiguration;
import org.hyperledger.besu.ethereum.chain.Blockchain; import org.hyperledger.besu.ethereum.chain.Blockchain;
import org.hyperledger.besu.ethereum.chain.GenesisState; import org.hyperledger.besu.ethereum.chain.GenesisState;
import org.hyperledger.besu.ethereum.chain.MutableBlockchain; import org.hyperledger.besu.ethereum.chain.MutableBlockchain;
@@ -191,7 +192,8 @@ public class MergeBesuControllerBuilderTest {
.evmConfiguration(EvmConfiguration.DEFAULT) .evmConfiguration(EvmConfiguration.DEFAULT)
.networkConfiguration(NetworkingConfiguration.create()) .networkConfiguration(NetworkingConfiguration.create())
.besuComponent(mock(BesuComponent.class)) .besuComponent(mock(BesuComponent.class))
.networkId(networkId); .networkId(networkId)
.apiConfiguration(ImmutableApiConfiguration.builder().build());
} }
@Test @Test

View File

@@ -266,14 +266,14 @@ public class GenesisConfigFile {
} }
/** /**
* Gets target blob count. * Gets target blobs per block.
* *
* @return the target blob count * @return the target blobs per block
*/ */
public Optional<String> getTargetBlobCount() { public Optional<String> getTargetBlobsPerBlock() {
// TODO SLD EIP-7742 not sure if we should use a default value here or enforce any // TODO SLD EIP-7742 not sure if we should use a default value here or enforce any
// "pragueAtGenesis" genesis file (used in devnets) to have this value // "pragueAtGenesis" genesis file (used in devnets) to have this value
return JsonUtil.getValueAsString(genesisRoot, "targetblobcount"); return JsonUtil.getValueAsString(genesisRoot, "targetblobsperblock");
} }
/** /**

View File

@@ -214,7 +214,7 @@ public abstract class AbstractSECP256 implements SignatureAlgorithm {
@Override @Override
public CodeDelegationSignature createCodeDelegationSignature( public CodeDelegationSignature createCodeDelegationSignature(
final BigInteger r, final BigInteger s, final BigInteger yParity) { final BigInteger r, final BigInteger s, final byte yParity) {
return CodeDelegationSignature.create(r, s, yParity); return CodeDelegationSignature.create(r, s, yParity);
} }

View File

@@ -42,7 +42,7 @@ public class CodeDelegationSignature extends SECPSignature {
* @return the new CodeDelegationSignature * @return the new CodeDelegationSignature
*/ */
public static CodeDelegationSignature create( public static CodeDelegationSignature create(
final BigInteger r, final BigInteger s, final BigInteger yParity) { final BigInteger r, final BigInteger s, final byte yParity) {
checkNotNull(r); checkNotNull(r);
checkNotNull(s); checkNotNull(s);
@@ -56,11 +56,6 @@ public class CodeDelegationSignature extends SECPSignature {
"Invalid 's' value, should be < 2^256 but got " + s.toString(16)); "Invalid 's' value, should be < 2^256 but got " + s.toString(16));
} }
if (yParity.compareTo(TWO_POW_256) >= 0) { return new CodeDelegationSignature(r, s, yParity);
throw new IllegalArgumentException(
"Invalid 'yParity' value, should be < 2^256 but got " + yParity.toString(16));
}
return new CodeDelegationSignature(r, s, yParity.byteValue());
} }
} }

View File

@@ -224,7 +224,7 @@ public interface SignatureAlgorithm {
* @return the code delegation signature * @return the code delegation signature
*/ */
CodeDelegationSignature createCodeDelegationSignature( CodeDelegationSignature createCodeDelegationSignature(
final BigInteger r, final BigInteger s, final BigInteger yParity); final BigInteger r, final BigInteger s, final byte yParity);
/** /**
* Decode secp signature. * Decode secp signature.

View File

@@ -29,19 +29,19 @@ class CodeDelegationSignatureTest {
void testValidInputs() { void testValidInputs() {
BigInteger r = BigInteger.ONE; BigInteger r = BigInteger.ONE;
BigInteger s = BigInteger.TEN; BigInteger s = BigInteger.TEN;
BigInteger yParity = BigInteger.ONE; byte yParity = (byte) 1;
CodeDelegationSignature result = CodeDelegationSignature.create(r, s, yParity); CodeDelegationSignature result = CodeDelegationSignature.create(r, s, yParity);
assertThat(r).isEqualTo(result.getR()); assertThat(r).isEqualTo(result.getR());
assertThat(s).isEqualTo(result.getS()); assertThat(s).isEqualTo(result.getS());
assertThat(yParity.byteValue()).isEqualTo(result.getRecId()); assertThat(yParity).isEqualTo(result.getRecId());
} }
@Test @Test
void testNullRValue() { void testNullRValue() {
BigInteger s = BigInteger.TEN; BigInteger s = BigInteger.TEN;
BigInteger yParity = BigInteger.ZERO; byte yParity = (byte) 0;
assertThatExceptionOfType(NullPointerException.class) assertThatExceptionOfType(NullPointerException.class)
.isThrownBy(() -> CodeDelegationSignature.create(null, s, yParity)); .isThrownBy(() -> CodeDelegationSignature.create(null, s, yParity));
@@ -50,7 +50,7 @@ class CodeDelegationSignatureTest {
@Test @Test
void testNullSValue() { void testNullSValue() {
BigInteger r = BigInteger.ONE; BigInteger r = BigInteger.ONE;
BigInteger yParity = BigInteger.ZERO; byte yParity = (byte) 0;
assertThatExceptionOfType(NullPointerException.class) assertThatExceptionOfType(NullPointerException.class)
.isThrownBy(() -> CodeDelegationSignature.create(r, null, yParity)); .isThrownBy(() -> CodeDelegationSignature.create(r, null, yParity));
@@ -60,7 +60,7 @@ class CodeDelegationSignatureTest {
void testRValueExceedsTwoPow256() { void testRValueExceedsTwoPow256() {
BigInteger r = TWO_POW_256; BigInteger r = TWO_POW_256;
BigInteger s = BigInteger.TEN; BigInteger s = BigInteger.TEN;
BigInteger yParity = BigInteger.ZERO; byte yParity = (byte) 0;
assertThatExceptionOfType(IllegalArgumentException.class) assertThatExceptionOfType(IllegalArgumentException.class)
.isThrownBy(() -> CodeDelegationSignature.create(r, s, yParity)) .isThrownBy(() -> CodeDelegationSignature.create(r, s, yParity))
@@ -71,34 +71,23 @@ class CodeDelegationSignatureTest {
void testSValueExceedsTwoPow256() { void testSValueExceedsTwoPow256() {
BigInteger r = BigInteger.ONE; BigInteger r = BigInteger.ONE;
BigInteger s = TWO_POW_256; BigInteger s = TWO_POW_256;
BigInteger yParity = BigInteger.ZERO; byte yParity = (byte) 0;
assertThatExceptionOfType(IllegalArgumentException.class) assertThatExceptionOfType(IllegalArgumentException.class)
.isThrownBy(() -> CodeDelegationSignature.create(r, s, yParity)) .isThrownBy(() -> CodeDelegationSignature.create(r, s, yParity))
.withMessageContainingAll("Invalid 's' value, should be < 2^256"); .withMessageContainingAll("Invalid 's' value, should be < 2^256");
} }
@Test
void testYParityExceedsTwoPow256() {
BigInteger r = BigInteger.ONE;
BigInteger s = BigInteger.TWO;
BigInteger yParity = TWO_POW_256;
assertThatExceptionOfType(IllegalArgumentException.class)
.isThrownBy(() -> CodeDelegationSignature.create(r, s, yParity))
.withMessageContainingAll("Invalid 'yParity' value, should be < 2^256");
}
@Test @Test
void testValidYParityZero() { void testValidYParityZero() {
BigInteger r = BigInteger.ONE; BigInteger r = BigInteger.ONE;
BigInteger s = BigInteger.TEN; BigInteger s = BigInteger.TEN;
BigInteger yParity = BigInteger.ZERO; byte yParity = (byte) 0;
CodeDelegationSignature result = CodeDelegationSignature.create(r, s, yParity); CodeDelegationSignature result = CodeDelegationSignature.create(r, s, yParity);
assertThat(r).isEqualTo(result.getR()); assertThat(r).isEqualTo(result.getR());
assertThat(s).isEqualTo(result.getS()); assertThat(s).isEqualTo(result.getS());
assertThat(yParity.byteValue()).isEqualTo(result.getRecId()); assertThat(yParity).isEqualTo(result.getRecId());
} }
} }

View File

@@ -25,7 +25,7 @@ import java.util.Optional;
*/ */
public interface CodeDelegation { public interface CodeDelegation {
/** The cost of delegating code on an existing account. */ /** The cost of delegating code on an existing account. */
long PER_AUTH_BASE_COST = 2_500L; long PER_AUTH_BASE_COST = 12_500L;
/** /**
* Return the chain id. * Return the chain id.

View File

@@ -39,5 +39,5 @@ public enum JsonRpcResponseKey {
BASEFEE, BASEFEE,
WITHDRAWALS_ROOT, WITHDRAWALS_ROOT,
REQUESTS_HASH, REQUESTS_HASH,
TARGET_BLOB_COUNT TARGET_BLOBS_PER_BLOCK
} }

View File

@@ -107,9 +107,9 @@ public class JsonRpcResponseUtils {
values.containsKey(WITHDRAWALS_ROOT) ? hash(values.get(WITHDRAWALS_ROOT)) : null; values.containsKey(WITHDRAWALS_ROOT) ? hash(values.get(WITHDRAWALS_ROOT)) : null;
final Hash requestsHash = final Hash requestsHash =
values.containsKey(REQUESTS_HASH) ? hash(values.get(REQUESTS_HASH)) : null; values.containsKey(REQUESTS_HASH) ? hash(values.get(REQUESTS_HASH)) : null;
final UInt64 targetBlobCount = final UInt64 targetBlobsPerBlock =
values.containsKey(JsonRpcResponseKey.TARGET_BLOB_COUNT) values.containsKey(JsonRpcResponseKey.TARGET_BLOBS_PER_BLOCK)
? UInt64.fromHexString(values.get(JsonRpcResponseKey.TARGET_BLOB_COUNT)) ? UInt64.fromHexString(values.get(JsonRpcResponseKey.TARGET_BLOBS_PER_BLOCK))
: null; : null;
final List<JsonNode> ommers = new ArrayList<>(); final List<JsonNode> ommers = new ArrayList<>();
@@ -136,7 +136,7 @@ public class JsonRpcResponseUtils {
null, // ToDo 4844: set with the value of excess_blob_gas field null, // ToDo 4844: set with the value of excess_blob_gas field
null, // TODO 4788: set with the value of the parent beacon block root field null, // TODO 4788: set with the value of the parent beacon block root field
requestsHash, requestsHash,
targetBlobCount, targetBlobsPerBlock,
blockHeaderFunctions); blockHeaderFunctions);
return new JsonRpcSuccessResponse( return new JsonRpcSuccessResponse(

View File

@@ -45,6 +45,7 @@ import org.hyperledger.besu.ethereum.mainnet.ProtocolSpec;
import org.hyperledger.besu.ethereum.p2p.network.P2PNetwork; import org.hyperledger.besu.ethereum.p2p.network.P2PNetwork;
import org.hyperledger.besu.ethereum.permissioning.AccountLocalConfigPermissioningController; import org.hyperledger.besu.ethereum.permissioning.AccountLocalConfigPermissioningController;
import org.hyperledger.besu.ethereum.permissioning.NodeLocalConfigPermissioningController; import org.hyperledger.besu.ethereum.permissioning.NodeLocalConfigPermissioningController;
import org.hyperledger.besu.ethereum.transaction.TransactionSimulator;
import org.hyperledger.besu.ethereum.worldstate.WorldStateArchive; import org.hyperledger.besu.ethereum.worldstate.WorldStateArchive;
import org.hyperledger.besu.metrics.ObservableMetricsSystem; import org.hyperledger.besu.metrics.ObservableMetricsSystem;
import org.hyperledger.besu.metrics.noop.NoOpMetricsSystem; import org.hyperledger.besu.metrics.noop.NoOpMetricsSystem;
@@ -77,6 +78,7 @@ public class JsonRpcTestMethodsFactory {
private final BlockchainQueries blockchainQueries; private final BlockchainQueries blockchainQueries;
private final Synchronizer synchronizer; private final Synchronizer synchronizer;
private final ProtocolSchedule protocolSchedule; private final ProtocolSchedule protocolSchedule;
private final TransactionSimulator transactionSimulator;
public JsonRpcTestMethodsFactory(final BlockchainImporter importer) { public JsonRpcTestMethodsFactory(final BlockchainImporter importer) {
this.importer = importer; this.importer = importer;
@@ -98,6 +100,9 @@ public class JsonRpcTestMethodsFactory {
this.blockchainQueries = this.blockchainQueries =
new BlockchainQueries( new BlockchainQueries(
protocolSchedule, blockchain, stateArchive, MiningConfiguration.newDefault()); protocolSchedule, blockchain, stateArchive, MiningConfiguration.newDefault());
this.transactionSimulator =
new TransactionSimulator(blockchain, stateArchive, protocolSchedule, 0L);
} }
public JsonRpcTestMethodsFactory( public JsonRpcTestMethodsFactory(
@@ -117,6 +122,8 @@ public class JsonRpcTestMethodsFactory {
stateArchive, stateArchive,
MiningConfiguration.newDefault()); MiningConfiguration.newDefault());
this.synchronizer = mock(Synchronizer.class); this.synchronizer = mock(Synchronizer.class);
this.transactionSimulator =
new TransactionSimulator(blockchain, stateArchive, protocolSchedule, 0L);
} }
public JsonRpcTestMethodsFactory( public JsonRpcTestMethodsFactory(
@@ -137,6 +144,8 @@ public class JsonRpcTestMethodsFactory {
blockchain, blockchain,
stateArchive, stateArchive,
MiningConfiguration.newDefault()); MiningConfiguration.newDefault());
this.transactionSimulator =
new TransactionSimulator(blockchain, stateArchive, protocolSchedule, 0L);
} }
public BlockchainQueries getBlockchainQueries() { public BlockchainQueries getBlockchainQueries() {
@@ -219,6 +228,7 @@ public class JsonRpcTestMethodsFactory {
ethPeers, ethPeers,
Vertx.vertx(new VertxOptions().setWorkerPoolSize(1)), Vertx.vertx(new VertxOptions().setWorkerPoolSize(1)),
ImmutableApiConfiguration.builder().build(), ImmutableApiConfiguration.builder().build(),
Optional.empty()); Optional.empty(),
transactionSimulator);
} }
} }

View File

@@ -41,6 +41,6 @@ public enum GraphQLContextType {
/** Represents chain ID context. */ /** Represents chain ID context. */
CHAIN_ID, CHAIN_ID,
/** Represents gas cap context. */ /** Represents the transaction simulator. */
GAS_CAP TRANSACTION_SIMULATOR
} }

View File

@@ -332,10 +332,8 @@ public class BlockAdapterBase extends AdapterBase {
final ProtocolSchedule protocolSchedule = final ProtocolSchedule protocolSchedule =
environment.getGraphQlContext().get(GraphQLContextType.PROTOCOL_SCHEDULE); environment.getGraphQlContext().get(GraphQLContextType.PROTOCOL_SCHEDULE);
final long bn = header.getNumber(); final long bn = header.getNumber();
final long gasCap = environment.getGraphQlContext().get(GraphQLContextType.GAS_CAP);
final TransactionSimulator transactionSimulator = final TransactionSimulator transactionSimulator =
new TransactionSimulator( environment.getGraphQlContext().get(GraphQLContextType.TRANSACTION_SIMULATOR);
query.getBlockchain(), query.getWorldStateArchive(), protocolSchedule, gasCap);
long gasParam = -1; long gasParam = -1;
Wei gasPriceParam = null; Wei gasPriceParam = null;

View File

@@ -145,10 +145,8 @@ public class PendingStateAdapter extends AdapterBase {
final BlockchainQueries query = getBlockchainQueries(environment); final BlockchainQueries query = getBlockchainQueries(environment);
final ProtocolSchedule protocolSchedule = final ProtocolSchedule protocolSchedule =
environment.getGraphQlContext().get(GraphQLContextType.PROTOCOL_SCHEDULE); environment.getGraphQlContext().get(GraphQLContextType.PROTOCOL_SCHEDULE);
final long gasCap = environment.getGraphQlContext().get(GraphQLContextType.GAS_CAP);
final TransactionSimulator transactionSimulator = final TransactionSimulator transactionSimulator =
new TransactionSimulator( environment.getGraphQlContext().get(GraphQLContextType.TRANSACTION_SIMULATOR);
query.getBlockchain(), query.getWorldStateArchive(), protocolSchedule, gasCap);
long gasParam = -1; long gasParam = -1;
Wei gasPriceParam = null; Wei gasPriceParam = null;

View File

@@ -107,6 +107,7 @@ public class TracedJsonRpcProcessor implements JsonRpcProcessor {
case INVALID_PROPOSAL_PARAMS: case INVALID_PROPOSAL_PARAMS:
case INVALID_REMOTE_CAPABILITIES_PARAMS: case INVALID_REMOTE_CAPABILITIES_PARAMS:
case INVALID_REWARD_PERCENTILES_PARAMS: case INVALID_REWARD_PERCENTILES_PARAMS:
case INVALID_REQUESTS_PARAMS:
case INVALID_SEALER_ID_PARAMS: case INVALID_SEALER_ID_PARAMS:
case INVALID_STORAGE_KEYS_PARAMS: case INVALID_STORAGE_KEYS_PARAMS:
case INVALID_SUBSCRIPTION_PARAMS: case INVALID_SUBSCRIPTION_PARAMS:

View File

@@ -95,6 +95,7 @@ public enum RpcErrorType implements RpcMethodError {
INVALID_REMOTE_CAPABILITIES_PARAMS( INVALID_REMOTE_CAPABILITIES_PARAMS(
INVALID_PARAMS_ERROR_CODE, "Invalid remote capabilities params"), INVALID_PARAMS_ERROR_CODE, "Invalid remote capabilities params"),
INVALID_REWARD_PERCENTILES_PARAMS(INVALID_PARAMS_ERROR_CODE, "Invalid reward percentiles params"), INVALID_REWARD_PERCENTILES_PARAMS(INVALID_PARAMS_ERROR_CODE, "Invalid reward percentiles params"),
INVALID_REQUESTS_PARAMS(INVALID_PARAMS_ERROR_CODE, "Invalid requests params"),
INVALID_SEALER_ID_PARAMS(INVALID_PARAMS_ERROR_CODE, "Invalid sealer ID params"), INVALID_SEALER_ID_PARAMS(INVALID_PARAMS_ERROR_CODE, "Invalid sealer ID params"),
INVALID_STORAGE_KEYS_PARAMS(INVALID_PARAMS_ERROR_CODE, "Invalid storage keys params"), INVALID_STORAGE_KEYS_PARAMS(INVALID_PARAMS_ERROR_CODE, "Invalid storage keys params"),
INVALID_SUBSCRIPTION_PARAMS(INVALID_PARAMS_ERROR_CODE, "Invalid subscription params"), INVALID_SUBSCRIPTION_PARAMS(INVALID_PARAMS_ERROR_CODE, "Invalid subscription params"),

View File

@@ -88,7 +88,7 @@ public class BlockResult implements JsonRpcResult {
private final String blobGasUsed; private final String blobGasUsed;
private final String excessBlobGas; private final String excessBlobGas;
private final String parentBeaconBlockRoot; private final String parentBeaconBlockRoot;
private final String targetBlobCount; private final String targetBlobsPerBlock;
public BlockResult( public BlockResult(
final BlockHeader header, final BlockHeader header,
@@ -139,7 +139,7 @@ public class BlockResult implements JsonRpcResult {
this.excessBlobGas = header.getExcessBlobGas().map(Quantity::create).orElse(null); this.excessBlobGas = header.getExcessBlobGas().map(Quantity::create).orElse(null);
this.parentBeaconBlockRoot = this.parentBeaconBlockRoot =
header.getParentBeaconBlockRoot().map(Bytes32::toHexString).orElse(null); header.getParentBeaconBlockRoot().map(Bytes32::toHexString).orElse(null);
this.targetBlobCount = header.getTargetBlobCount().map(Quantity::create).orElse(null); this.targetBlobsPerBlock = header.getTargetBlobsPerBlock().map(Quantity::create).orElse(null);
} }
@JsonGetter(value = "number") @JsonGetter(value = "number")
@@ -278,8 +278,8 @@ public class BlockResult implements JsonRpcResult {
return parentBeaconBlockRoot; return parentBeaconBlockRoot;
} }
@JsonGetter(value = "targetBlobCount") @JsonGetter(value = "targetBlobsPerBlock")
public String getTargetBlobCount() { public String getTargetBlobsPerBlock() {
return targetBlobCount; return targetBlobsPerBlock;
} }
} }

View File

@@ -15,7 +15,6 @@
package org.hyperledger.besu.ethereum.api.jsonrpc.methods; package org.hyperledger.besu.ethereum.api.jsonrpc.methods;
import org.hyperledger.besu.ethereum.ProtocolContext; import org.hyperledger.besu.ethereum.ProtocolContext;
import org.hyperledger.besu.ethereum.api.ApiConfiguration;
import org.hyperledger.besu.ethereum.api.jsonrpc.RpcApis; import org.hyperledger.besu.ethereum.api.jsonrpc.RpcApis;
import org.hyperledger.besu.ethereum.api.jsonrpc.internal.DebugReplayBlock; import org.hyperledger.besu.ethereum.api.jsonrpc.internal.DebugReplayBlock;
import org.hyperledger.besu.ethereum.api.jsonrpc.internal.methods.DebugAccountAt; import org.hyperledger.besu.ethereum.api.jsonrpc.internal.methods.DebugAccountAt;
@@ -64,7 +63,7 @@ public class DebugJsonRpcMethods extends ApiGroupJsonRpcMethods {
private final TransactionPool transactionPool; private final TransactionPool transactionPool;
private final Synchronizer synchronizer; private final Synchronizer synchronizer;
private final Path dataDir; private final Path dataDir;
private final ApiConfiguration apiConfiguration; private final TransactionSimulator transactionSimulator;
DebugJsonRpcMethods( DebugJsonRpcMethods(
final BlockchainQueries blockchainQueries, final BlockchainQueries blockchainQueries,
@@ -74,7 +73,7 @@ public class DebugJsonRpcMethods extends ApiGroupJsonRpcMethods {
final TransactionPool transactionPool, final TransactionPool transactionPool,
final Synchronizer synchronizer, final Synchronizer synchronizer,
final Path dataDir, final Path dataDir,
final ApiConfiguration apiConfiguration) { final TransactionSimulator transactionSimulator) {
this.blockchainQueries = blockchainQueries; this.blockchainQueries = blockchainQueries;
this.protocolContext = protocolContext; this.protocolContext = protocolContext;
this.protocolSchedule = protocolSchedule; this.protocolSchedule = protocolSchedule;
@@ -82,7 +81,7 @@ public class DebugJsonRpcMethods extends ApiGroupJsonRpcMethods {
this.transactionPool = transactionPool; this.transactionPool = transactionPool;
this.synchronizer = synchronizer; this.synchronizer = synchronizer;
this.dataDir = dataDir; this.dataDir = dataDir;
this.apiConfiguration = apiConfiguration; this.transactionSimulator = transactionSimulator;
} }
@Override @Override
@@ -120,13 +119,6 @@ public class DebugJsonRpcMethods extends ApiGroupJsonRpcMethods {
new DebugGetRawBlock(blockchainQueries), new DebugGetRawBlock(blockchainQueries),
new DebugGetRawReceipts(blockchainQueries), new DebugGetRawReceipts(blockchainQueries),
new DebugGetRawTransaction(blockchainQueries), new DebugGetRawTransaction(blockchainQueries),
new DebugTraceCall( new DebugTraceCall(blockchainQueries, protocolSchedule, transactionSimulator));
blockchainQueries,
protocolSchedule,
new TransactionSimulator(
blockchainQueries.getBlockchain(),
blockchainQueries.getWorldStateArchive(),
protocolSchedule,
apiConfiguration.getGasCap())));
} }
} }

View File

@@ -89,6 +89,7 @@ public class EthJsonRpcMethods extends ApiGroupJsonRpcMethods {
private final MiningCoordinator miningCoordinator; private final MiningCoordinator miningCoordinator;
private final Set<Capability> supportedCapabilities; private final Set<Capability> supportedCapabilities;
private final ApiConfiguration apiConfiguration; private final ApiConfiguration apiConfiguration;
private final TransactionSimulator transactionSimulator;
public EthJsonRpcMethods( public EthJsonRpcMethods(
final BlockchainQueries blockchainQueries, final BlockchainQueries blockchainQueries,
@@ -98,7 +99,8 @@ public class EthJsonRpcMethods extends ApiGroupJsonRpcMethods {
final TransactionPool transactionPool, final TransactionPool transactionPool,
final MiningCoordinator miningCoordinator, final MiningCoordinator miningCoordinator,
final Set<Capability> supportedCapabilities, final Set<Capability> supportedCapabilities,
final ApiConfiguration apiConfiguration) { final ApiConfiguration apiConfiguration,
final TransactionSimulator transactionSimulator) {
this.blockchainQueries = blockchainQueries; this.blockchainQueries = blockchainQueries;
this.synchronizer = synchronizer; this.synchronizer = synchronizer;
this.protocolSchedule = protocolSchedule; this.protocolSchedule = protocolSchedule;
@@ -107,6 +109,7 @@ public class EthJsonRpcMethods extends ApiGroupJsonRpcMethods {
this.miningCoordinator = miningCoordinator; this.miningCoordinator = miningCoordinator;
this.supportedCapabilities = supportedCapabilities; this.supportedCapabilities = supportedCapabilities;
this.apiConfiguration = apiConfiguration; this.apiConfiguration = apiConfiguration;
this.transactionSimulator = transactionSimulator;
} }
@Override @Override
@@ -125,13 +128,7 @@ public class EthJsonRpcMethods extends ApiGroupJsonRpcMethods {
new EthGetBlockReceipts(blockchainQueries, protocolSchedule), new EthGetBlockReceipts(blockchainQueries, protocolSchedule),
new EthGetBlockTransactionCountByNumber(blockchainQueries), new EthGetBlockTransactionCountByNumber(blockchainQueries),
new EthGetBlockTransactionCountByHash(blockchainQueries), new EthGetBlockTransactionCountByHash(blockchainQueries),
new EthCall( new EthCall(blockchainQueries, transactionSimulator),
blockchainQueries,
new TransactionSimulator(
blockchainQueries.getBlockchain(),
blockchainQueries.getWorldStateArchive(),
protocolSchedule,
apiConfiguration.getGasCap())),
new EthFeeHistory(protocolSchedule, blockchainQueries, miningCoordinator, apiConfiguration), new EthFeeHistory(protocolSchedule, blockchainQueries, miningCoordinator, apiConfiguration),
new EthGetCode(blockchainQueries), new EthGetCode(blockchainQueries),
new EthGetLogs(blockchainQueries, apiConfiguration.getMaxLogsRange()), new EthGetLogs(blockchainQueries, apiConfiguration.getMaxLogsRange()),
@@ -155,20 +152,8 @@ public class EthJsonRpcMethods extends ApiGroupJsonRpcMethods {
new EthGetStorageAt(blockchainQueries), new EthGetStorageAt(blockchainQueries),
new EthSendRawTransaction(transactionPool), new EthSendRawTransaction(transactionPool),
new EthSendTransaction(), new EthSendTransaction(),
new EthEstimateGas( new EthEstimateGas(blockchainQueries, transactionSimulator),
blockchainQueries, new EthCreateAccessList(blockchainQueries, transactionSimulator),
new TransactionSimulator(
blockchainQueries.getBlockchain(),
blockchainQueries.getWorldStateArchive(),
protocolSchedule,
apiConfiguration.getGasCap())),
new EthCreateAccessList(
blockchainQueries,
new TransactionSimulator(
blockchainQueries.getBlockchain(),
blockchainQueries.getWorldStateArchive(),
protocolSchedule,
apiConfiguration.getGasCap())),
new EthMining(miningCoordinator), new EthMining(miningCoordinator),
new EthCoinbase(miningCoordinator), new EthCoinbase(miningCoordinator),
new EthProtocolVersion(supportedCapabilities), new EthProtocolVersion(supportedCapabilities),

View File

@@ -36,6 +36,7 @@ import org.hyperledger.besu.ethereum.p2p.peers.EnodeDnsConfiguration;
import org.hyperledger.besu.ethereum.p2p.rlpx.wire.Capability; import org.hyperledger.besu.ethereum.p2p.rlpx.wire.Capability;
import org.hyperledger.besu.ethereum.permissioning.AccountLocalConfigPermissioningController; import org.hyperledger.besu.ethereum.permissioning.AccountLocalConfigPermissioningController;
import org.hyperledger.besu.ethereum.permissioning.NodeLocalConfigPermissioningController; import org.hyperledger.besu.ethereum.permissioning.NodeLocalConfigPermissioningController;
import org.hyperledger.besu.ethereum.transaction.TransactionSimulator;
import org.hyperledger.besu.metrics.ObservableMetricsSystem; import org.hyperledger.besu.metrics.ObservableMetricsSystem;
import org.hyperledger.besu.metrics.prometheus.MetricsConfiguration; import org.hyperledger.besu.metrics.prometheus.MetricsConfiguration;
import org.hyperledger.besu.nat.NatService; import org.hyperledger.besu.nat.NatService;
@@ -85,7 +86,8 @@ public class JsonRpcMethodsFactory {
final EthPeers ethPeers, final EthPeers ethPeers,
final Vertx consensusEngineServer, final Vertx consensusEngineServer,
final ApiConfiguration apiConfiguration, final ApiConfiguration apiConfiguration,
final Optional<EnodeDnsConfiguration> enodeDnsConfiguration) { final Optional<EnodeDnsConfiguration> enodeDnsConfiguration,
final TransactionSimulator transactionSimulator) {
final Map<String, JsonRpcMethod> enabled = new HashMap<>(); final Map<String, JsonRpcMethod> enabled = new HashMap<>();
if (!rpcApis.isEmpty()) { if (!rpcApis.isEmpty()) {
final JsonRpcMethod modules = new RpcModules(rpcApis); final JsonRpcMethod modules = new RpcModules(rpcApis);
@@ -111,7 +113,7 @@ public class JsonRpcMethodsFactory {
transactionPool, transactionPool,
synchronizer, synchronizer,
dataDir, dataDir,
apiConfiguration), transactionSimulator),
new EeaJsonRpcMethods( new EeaJsonRpcMethods(
blockchainQueries, protocolSchedule, transactionPool, privacyParameters), blockchainQueries, protocolSchedule, transactionPool, privacyParameters),
new ExecutionEngineJsonRpcMethods( new ExecutionEngineJsonRpcMethods(
@@ -131,7 +133,8 @@ public class JsonRpcMethodsFactory {
transactionPool, transactionPool,
miningCoordinator, miningCoordinator,
supportedCapabilities, supportedCapabilities,
apiConfiguration), apiConfiguration,
transactionSimulator),
new NetJsonRpcMethods( new NetJsonRpcMethods(
p2pNetwork, p2pNetwork,
networkId, networkId,
@@ -155,6 +158,7 @@ public class JsonRpcMethodsFactory {
protocolSchedule, protocolSchedule,
protocolContext, protocolContext,
apiConfiguration, apiConfiguration,
transactionSimulator,
metricsSystem), metricsSystem),
new TxPoolJsonRpcMethods(transactionPool), new TxPoolJsonRpcMethods(transactionPool),
new PluginsJsonRpcMethods(namedPlugins)); new PluginsJsonRpcMethods(namedPlugins));

View File

@@ -41,6 +41,7 @@ public class TraceJsonRpcMethods extends ApiGroupJsonRpcMethods {
private final ProtocolSchedule protocolSchedule; private final ProtocolSchedule protocolSchedule;
private final ApiConfiguration apiConfiguration; private final ApiConfiguration apiConfiguration;
private final ProtocolContext protocolContext; private final ProtocolContext protocolContext;
private final TransactionSimulator transactionSimulator;
private final MetricsSystem metricsSystem; private final MetricsSystem metricsSystem;
TraceJsonRpcMethods( TraceJsonRpcMethods(
@@ -48,11 +49,13 @@ public class TraceJsonRpcMethods extends ApiGroupJsonRpcMethods {
final ProtocolSchedule protocolSchedule, final ProtocolSchedule protocolSchedule,
final ProtocolContext protocolContext, final ProtocolContext protocolContext,
final ApiConfiguration apiConfiguration, final ApiConfiguration apiConfiguration,
final TransactionSimulator transactionSimulator,
final MetricsSystem metricsSystem) { final MetricsSystem metricsSystem) {
this.blockchainQueries = blockchainQueries; this.blockchainQueries = blockchainQueries;
this.protocolSchedule = protocolSchedule; this.protocolSchedule = protocolSchedule;
this.protocolContext = protocolContext; this.protocolContext = protocolContext;
this.apiConfiguration = apiConfiguration; this.apiConfiguration = apiConfiguration;
this.transactionSimulator = transactionSimulator;
this.metricsSystem = metricsSystem; this.metricsSystem = metricsSystem;
} }
@@ -76,29 +79,8 @@ public class TraceJsonRpcMethods extends ApiGroupJsonRpcMethods {
new TraceTransaction( new TraceTransaction(
() -> new BlockTracer(blockReplay), protocolSchedule, blockchainQueries), () -> new BlockTracer(blockReplay), protocolSchedule, blockchainQueries),
new TraceBlock(protocolSchedule, blockchainQueries, metricsSystem), new TraceBlock(protocolSchedule, blockchainQueries, metricsSystem),
new TraceCall( new TraceCall(blockchainQueries, protocolSchedule, transactionSimulator),
blockchainQueries, new TraceCallMany(blockchainQueries, protocolSchedule, transactionSimulator),
protocolSchedule, new TraceRawTransaction(protocolSchedule, blockchainQueries, transactionSimulator));
new TransactionSimulator(
blockchainQueries.getBlockchain(),
blockchainQueries.getWorldStateArchive(),
protocolSchedule,
apiConfiguration.getGasCap())),
new TraceCallMany(
blockchainQueries,
protocolSchedule,
new TransactionSimulator(
blockchainQueries.getBlockchain(),
blockchainQueries.getWorldStateArchive(),
protocolSchedule,
apiConfiguration.getGasCap())),
new TraceRawTransaction(
protocolSchedule,
blockchainQueries,
new TransactionSimulator(
blockchainQueries.getBlockchain(),
blockchainQueries.getWorldStateArchive(),
protocolSchedule,
apiConfiguration.getGasCap())));
} }
} }

View File

@@ -38,6 +38,7 @@ import org.hyperledger.besu.ethereum.eth.transactions.TransactionPool;
import org.hyperledger.besu.ethereum.mainnet.ValidationResult; import org.hyperledger.besu.ethereum.mainnet.ValidationResult;
import org.hyperledger.besu.ethereum.p2p.rlpx.wire.Capability; import org.hyperledger.besu.ethereum.p2p.rlpx.wire.Capability;
import org.hyperledger.besu.ethereum.transaction.TransactionInvalidReason; import org.hyperledger.besu.ethereum.transaction.TransactionInvalidReason;
import org.hyperledger.besu.ethereum.transaction.TransactionSimulator;
import org.hyperledger.besu.plugin.data.SyncStatus; import org.hyperledger.besu.plugin.data.SyncStatus;
import org.hyperledger.besu.plugin.services.storage.DataStorageFormat; import org.hyperledger.besu.plugin.services.storage.DataStorageFormat;
@@ -135,6 +136,13 @@ public abstract class AbstractEthGraphQLHttpServiceTest {
final GraphQLDataFetchers dataFetchers = new GraphQLDataFetchers(supportedCapabilities); final GraphQLDataFetchers dataFetchers = new GraphQLDataFetchers(supportedCapabilities);
final GraphQL graphQL = GraphQLProvider.buildGraphQL(dataFetchers); final GraphQL graphQL = GraphQLProvider.buildGraphQL(dataFetchers);
final var transactionSimulator =
new TransactionSimulator(
blockchain,
blockchainSetupUtil.getWorldArchive(),
blockchainSetupUtil.getProtocolSchedule(),
0L);
service = service =
new GraphQLHttpService( new GraphQLHttpService(
vertx, vertx,
@@ -152,8 +160,8 @@ public abstract class AbstractEthGraphQLHttpServiceTest {
miningCoordinatorMock, miningCoordinatorMock,
GraphQLContextType.SYNCHRONIZER, GraphQLContextType.SYNCHRONIZER,
synchronizerMock, synchronizerMock,
GraphQLContextType.GAS_CAP, GraphQLContextType.TRANSACTION_SIMULATOR,
0L), transactionSimulator),
mock(EthScheduler.class)); mock(EthScheduler.class));
service.start().join(); service.start().join();

View File

@@ -46,6 +46,7 @@ import org.hyperledger.besu.ethereum.mainnet.ValidationResult;
import org.hyperledger.besu.ethereum.p2p.network.P2PNetwork; import org.hyperledger.besu.ethereum.p2p.network.P2PNetwork;
import org.hyperledger.besu.ethereum.p2p.rlpx.wire.Capability; import org.hyperledger.besu.ethereum.p2p.rlpx.wire.Capability;
import org.hyperledger.besu.ethereum.transaction.TransactionInvalidReason; import org.hyperledger.besu.ethereum.transaction.TransactionInvalidReason;
import org.hyperledger.besu.ethereum.transaction.TransactionSimulator;
import org.hyperledger.besu.metrics.noop.NoOpMetricsSystem; import org.hyperledger.besu.metrics.noop.NoOpMetricsSystem;
import org.hyperledger.besu.metrics.prometheus.MetricsConfiguration; import org.hyperledger.besu.metrics.prometheus.MetricsConfiguration;
import org.hyperledger.besu.nat.NatService; import org.hyperledger.besu.nat.NatService;
@@ -169,6 +170,13 @@ public abstract class AbstractJsonRpcHttpServiceTest {
final NatService natService = new NatService(Optional.empty()); final NatService natService = new NatService(Optional.empty());
final var transactionSimulator =
new TransactionSimulator(
blockchainSetupUtil.getBlockchain(),
blockchainSetupUtil.getWorldArchive(),
blockchainSetupUtil.getProtocolSchedule(),
0L);
return new JsonRpcMethodsFactory() return new JsonRpcMethodsFactory()
.methods( .methods(
CLIENT_NODE_NAME, CLIENT_NODE_NAME,
@@ -201,7 +209,8 @@ public abstract class AbstractJsonRpcHttpServiceTest {
mock(EthPeers.class), mock(EthPeers.class),
syncVertx, syncVertx,
mock(ApiConfiguration.class), mock(ApiConfiguration.class),
Optional.empty()); Optional.empty(),
transactionSimulator);
} }
protected void startService() throws Exception { protected void startService() throws Exception {

View File

@@ -41,6 +41,7 @@ import org.hyperledger.besu.ethereum.p2p.network.P2PNetwork;
import org.hyperledger.besu.ethereum.p2p.rlpx.wire.Capability; import org.hyperledger.besu.ethereum.p2p.rlpx.wire.Capability;
import org.hyperledger.besu.ethereum.permissioning.AccountLocalConfigPermissioningController; import org.hyperledger.besu.ethereum.permissioning.AccountLocalConfigPermissioningController;
import org.hyperledger.besu.ethereum.permissioning.NodeLocalConfigPermissioningController; import org.hyperledger.besu.ethereum.permissioning.NodeLocalConfigPermissioningController;
import org.hyperledger.besu.ethereum.transaction.TransactionSimulator;
import org.hyperledger.besu.metrics.noop.NoOpMetricsSystem; import org.hyperledger.besu.metrics.noop.NoOpMetricsSystem;
import org.hyperledger.besu.metrics.prometheus.MetricsConfiguration; import org.hyperledger.besu.metrics.prometheus.MetricsConfiguration;
import org.hyperledger.besu.nat.NatService; import org.hyperledger.besu.nat.NatService;
@@ -138,7 +139,8 @@ public class JsonRpcHttpServiceHostAllowlistTest {
mock(EthPeers.class), mock(EthPeers.class),
vertx, vertx,
mock(ApiConfiguration.class), mock(ApiConfiguration.class),
Optional.empty()); Optional.empty(),
mock(TransactionSimulator.class));
service = createJsonRpcHttpService(); service = createJsonRpcHttpService();
service.start().join(); service.start().join();

View File

@@ -46,6 +46,7 @@ import org.hyperledger.besu.ethereum.eth.transactions.TransactionPool;
import org.hyperledger.besu.ethereum.mainnet.MainnetProtocolSchedule; import org.hyperledger.besu.ethereum.mainnet.MainnetProtocolSchedule;
import org.hyperledger.besu.ethereum.p2p.network.P2PNetwork; import org.hyperledger.besu.ethereum.p2p.network.P2PNetwork;
import org.hyperledger.besu.ethereum.p2p.rlpx.wire.Capability; import org.hyperledger.besu.ethereum.p2p.rlpx.wire.Capability;
import org.hyperledger.besu.ethereum.transaction.TransactionSimulator;
import org.hyperledger.besu.metrics.noop.NoOpMetricsSystem; import org.hyperledger.besu.metrics.noop.NoOpMetricsSystem;
import org.hyperledger.besu.metrics.prometheus.MetricsConfiguration; import org.hyperledger.besu.metrics.prometheus.MetricsConfiguration;
import org.hyperledger.besu.nat.NatService; import org.hyperledger.besu.nat.NatService;
@@ -169,7 +170,8 @@ public class JsonRpcHttpServiceLoginTest {
mock(EthPeers.class), mock(EthPeers.class),
vertx, vertx,
mock(ApiConfiguration.class), mock(ApiConfiguration.class),
Optional.empty()); Optional.empty(),
mock(TransactionSimulator.class));
service = createJsonRpcHttpService(); service = createJsonRpcHttpService();
jwtAuth = service.authenticationService.get().getJwtAuthProvider(); jwtAuth = service.authenticationService.get().getJwtAuthProvider();
service.start().join(); service.start().join();

View File

@@ -51,6 +51,7 @@ import org.hyperledger.besu.ethereum.p2p.network.P2PNetwork;
import org.hyperledger.besu.ethereum.p2p.rlpx.wire.Capability; import org.hyperledger.besu.ethereum.p2p.rlpx.wire.Capability;
import org.hyperledger.besu.ethereum.permissioning.AccountLocalConfigPermissioningController; import org.hyperledger.besu.ethereum.permissioning.AccountLocalConfigPermissioningController;
import org.hyperledger.besu.ethereum.permissioning.NodeLocalConfigPermissioningController; import org.hyperledger.besu.ethereum.permissioning.NodeLocalConfigPermissioningController;
import org.hyperledger.besu.ethereum.transaction.TransactionSimulator;
import org.hyperledger.besu.metrics.noop.NoOpMetricsSystem; import org.hyperledger.besu.metrics.noop.NoOpMetricsSystem;
import org.hyperledger.besu.metrics.prometheus.MetricsConfiguration; import org.hyperledger.besu.metrics.prometheus.MetricsConfiguration;
import org.hyperledger.besu.nat.NatService; import org.hyperledger.besu.nat.NatService;
@@ -235,7 +236,8 @@ public class JsonRpcHttpServiceRpcApisTest {
mock(EthPeers.class), mock(EthPeers.class),
vertx, vertx,
mock(ApiConfiguration.class), mock(ApiConfiguration.class),
Optional.empty()); Optional.empty(),
mock(TransactionSimulator.class));
final JsonRpcHttpService jsonRpcHttpService = final JsonRpcHttpService jsonRpcHttpService =
new JsonRpcHttpService( new JsonRpcHttpService(
vertx, vertx,
@@ -346,7 +348,8 @@ public class JsonRpcHttpServiceRpcApisTest {
mock(EthPeers.class), mock(EthPeers.class),
vertx, vertx,
mock(ApiConfiguration.class), mock(ApiConfiguration.class),
Optional.empty()); Optional.empty(),
mock(TransactionSimulator.class));
final JsonRpcHttpService jsonRpcHttpService = final JsonRpcHttpService jsonRpcHttpService =
new JsonRpcHttpService( new JsonRpcHttpService(
vertx, vertx,

View File

@@ -41,6 +41,7 @@ import org.hyperledger.besu.ethereum.p2p.network.P2PNetwork;
import org.hyperledger.besu.ethereum.p2p.rlpx.wire.Capability; import org.hyperledger.besu.ethereum.p2p.rlpx.wire.Capability;
import org.hyperledger.besu.ethereum.permissioning.AccountLocalConfigPermissioningController; import org.hyperledger.besu.ethereum.permissioning.AccountLocalConfigPermissioningController;
import org.hyperledger.besu.ethereum.permissioning.NodeLocalConfigPermissioningController; import org.hyperledger.besu.ethereum.permissioning.NodeLocalConfigPermissioningController;
import org.hyperledger.besu.ethereum.transaction.TransactionSimulator;
import org.hyperledger.besu.evm.internal.EvmConfiguration; import org.hyperledger.besu.evm.internal.EvmConfiguration;
import org.hyperledger.besu.metrics.noop.NoOpMetricsSystem; import org.hyperledger.besu.metrics.noop.NoOpMetricsSystem;
import org.hyperledger.besu.metrics.prometheus.MetricsConfiguration; import org.hyperledger.besu.metrics.prometheus.MetricsConfiguration;
@@ -147,7 +148,8 @@ public class JsonRpcHttpServiceTestBase {
ethPeersMock, ethPeersMock,
vertx, vertx,
mock(ApiConfiguration.class), mock(ApiConfiguration.class),
Optional.empty()); Optional.empty(),
mock(TransactionSimulator.class));
disabledRpcMethods = new HashMap<>(); disabledRpcMethods = new HashMap<>();
addedRpcMethods = new HashSet<>(); addedRpcMethods = new HashSet<>();

View File

@@ -48,6 +48,7 @@ import org.hyperledger.besu.ethereum.p2p.network.P2PNetwork;
import org.hyperledger.besu.ethereum.p2p.rlpx.wire.Capability; import org.hyperledger.besu.ethereum.p2p.rlpx.wire.Capability;
import org.hyperledger.besu.ethereum.permissioning.AccountLocalConfigPermissioningController; import org.hyperledger.besu.ethereum.permissioning.AccountLocalConfigPermissioningController;
import org.hyperledger.besu.ethereum.permissioning.NodeLocalConfigPermissioningController; import org.hyperledger.besu.ethereum.permissioning.NodeLocalConfigPermissioningController;
import org.hyperledger.besu.ethereum.transaction.TransactionSimulator;
import org.hyperledger.besu.metrics.noop.NoOpMetricsSystem; import org.hyperledger.besu.metrics.noop.NoOpMetricsSystem;
import org.hyperledger.besu.metrics.prometheus.MetricsConfiguration; import org.hyperledger.besu.metrics.prometheus.MetricsConfiguration;
import org.hyperledger.besu.nat.NatService; import org.hyperledger.besu.nat.NatService;
@@ -152,7 +153,8 @@ public class JsonRpcHttpServiceTlsClientAuthTest {
mock(EthPeers.class), mock(EthPeers.class),
vertx, vertx,
mock(ApiConfiguration.class), mock(ApiConfiguration.class),
Optional.empty()); Optional.empty(),
mock(TransactionSimulator.class));
System.setProperty("javax.net.ssl.trustStore", CLIENT_AS_CA_CERT.getKeyStoreFile().toString()); System.setProperty("javax.net.ssl.trustStore", CLIENT_AS_CA_CERT.getKeyStoreFile().toString());
System.setProperty( System.setProperty(

View File

@@ -47,6 +47,7 @@ import org.hyperledger.besu.ethereum.p2p.network.P2PNetwork;
import org.hyperledger.besu.ethereum.p2p.rlpx.wire.Capability; import org.hyperledger.besu.ethereum.p2p.rlpx.wire.Capability;
import org.hyperledger.besu.ethereum.permissioning.AccountLocalConfigPermissioningController; import org.hyperledger.besu.ethereum.permissioning.AccountLocalConfigPermissioningController;
import org.hyperledger.besu.ethereum.permissioning.NodeLocalConfigPermissioningController; import org.hyperledger.besu.ethereum.permissioning.NodeLocalConfigPermissioningController;
import org.hyperledger.besu.ethereum.transaction.TransactionSimulator;
import org.hyperledger.besu.metrics.noop.NoOpMetricsSystem; import org.hyperledger.besu.metrics.noop.NoOpMetricsSystem;
import org.hyperledger.besu.metrics.prometheus.MetricsConfiguration; import org.hyperledger.besu.metrics.prometheus.MetricsConfiguration;
import org.hyperledger.besu.nat.NatService; import org.hyperledger.besu.nat.NatService;
@@ -140,7 +141,8 @@ class JsonRpcHttpServiceTlsMisconfigurationTest {
mock(EthPeers.class), mock(EthPeers.class),
vertx, vertx,
mock(ApiConfiguration.class), mock(ApiConfiguration.class),
Optional.empty()); Optional.empty(),
mock(TransactionSimulator.class));
} }
@AfterEach @AfterEach

View File

@@ -47,6 +47,7 @@ import org.hyperledger.besu.ethereum.p2p.network.P2PNetwork;
import org.hyperledger.besu.ethereum.p2p.rlpx.wire.Capability; import org.hyperledger.besu.ethereum.p2p.rlpx.wire.Capability;
import org.hyperledger.besu.ethereum.permissioning.AccountLocalConfigPermissioningController; import org.hyperledger.besu.ethereum.permissioning.AccountLocalConfigPermissioningController;
import org.hyperledger.besu.ethereum.permissioning.NodeLocalConfigPermissioningController; import org.hyperledger.besu.ethereum.permissioning.NodeLocalConfigPermissioningController;
import org.hyperledger.besu.ethereum.transaction.TransactionSimulator;
import org.hyperledger.besu.metrics.noop.NoOpMetricsSystem; import org.hyperledger.besu.metrics.noop.NoOpMetricsSystem;
import org.hyperledger.besu.metrics.prometheus.MetricsConfiguration; import org.hyperledger.besu.metrics.prometheus.MetricsConfiguration;
import org.hyperledger.besu.nat.NatService; import org.hyperledger.besu.nat.NatService;
@@ -141,7 +142,8 @@ public class JsonRpcHttpServiceTlsTest {
mock(EthPeers.class), mock(EthPeers.class),
vertx, vertx,
mock(ApiConfiguration.class), mock(ApiConfiguration.class),
Optional.empty()); Optional.empty(),
mock(TransactionSimulator.class));
service = createJsonRpcHttpService(createJsonRpcConfig()); service = createJsonRpcHttpService(createJsonRpcConfig());
service.start().join(); service.start().join();
baseUrl = service.url(); baseUrl = service.url();

View File

@@ -54,6 +54,7 @@ import org.hyperledger.besu.ethereum.eth.transactions.TransactionPool;
import org.hyperledger.besu.ethereum.mainnet.MainnetProtocolSchedule; import org.hyperledger.besu.ethereum.mainnet.MainnetProtocolSchedule;
import org.hyperledger.besu.ethereum.p2p.network.P2PNetwork; import org.hyperledger.besu.ethereum.p2p.network.P2PNetwork;
import org.hyperledger.besu.ethereum.p2p.rlpx.wire.Capability; import org.hyperledger.besu.ethereum.p2p.rlpx.wire.Capability;
import org.hyperledger.besu.ethereum.transaction.TransactionSimulator;
import org.hyperledger.besu.metrics.noop.NoOpMetricsSystem; import org.hyperledger.besu.metrics.noop.NoOpMetricsSystem;
import org.hyperledger.besu.metrics.prometheus.MetricsConfiguration; import org.hyperledger.besu.metrics.prometheus.MetricsConfiguration;
import org.hyperledger.besu.nat.NatService; import org.hyperledger.besu.nat.NatService;
@@ -205,7 +206,8 @@ public class WebSocketServiceLoginTest {
mock(EthPeers.class), mock(EthPeers.class),
vertx, vertx,
mock(ApiConfiguration.class), mock(ApiConfiguration.class),
Optional.empty())); Optional.empty(),
mock(TransactionSimulator.class)));
websocketMethods.putAll(rpcMethods); websocketMethods.putAll(rpcMethods);
webSocketMessageHandlerSpy = webSocketMessageHandlerSpy =

View File

@@ -219,11 +219,11 @@ public final class GenesisState {
.parentBeaconBlockRoot( .parentBeaconBlockRoot(
(isCancunAtGenesis(genesis) ? parseParentBeaconBlockRoot(genesis) : null)) (isCancunAtGenesis(genesis) ? parseParentBeaconBlockRoot(genesis) : null))
.requestsHash(isPragueAtGenesis(genesis) ? Hash.EMPTY_REQUESTS_HASH : null) .requestsHash(isPragueAtGenesis(genesis) ? Hash.EMPTY_REQUESTS_HASH : null)
.targetBlobCount( .targetBlobsPerBlock(
isPragueAtGenesis(genesis) isPragueAtGenesis(genesis)
// TODO SLD EIP-7742 Currently defaulting to null due to dependency on web3j // TODO SLD EIP-7742 Currently defaulting to null due to dependency on web3j
// BlockHeader in CodeDelegationTransactionAcceptanceTest // BlockHeader in CodeDelegationTransactionAcceptanceTest
? genesis.getTargetBlobCount().map(UInt64::fromHexString).orElse(null) ? genesis.getTargetBlobsPerBlock().map(UInt64::fromHexString).orElse(null)
: null) : null)
.buildBlockHeader(); .buildBlockHeader();
} }

View File

@@ -66,7 +66,7 @@ public class BlockHeader extends SealableBlockHeader
final BlobGas excessBlobGas, final BlobGas excessBlobGas,
final Bytes32 parentBeaconBlockRoot, final Bytes32 parentBeaconBlockRoot,
final Hash requestsHash, final Hash requestsHash,
final UInt64 targetBlobCount, final UInt64 targetBlobsPerBlock,
final BlockHeaderFunctions blockHeaderFunctions) { final BlockHeaderFunctions blockHeaderFunctions) {
super( super(
parentHash, parentHash,
@@ -89,7 +89,7 @@ public class BlockHeader extends SealableBlockHeader
excessBlobGas, excessBlobGas,
parentBeaconBlockRoot, parentBeaconBlockRoot,
requestsHash, requestsHash,
targetBlobCount); targetBlobsPerBlock);
this.nonce = nonce; this.nonce = nonce;
this.hash = Suppliers.memoize(() -> blockHeaderFunctions.hash(this)); this.hash = Suppliers.memoize(() -> blockHeaderFunctions.hash(this));
this.parsedExtraData = Suppliers.memoize(() -> blockHeaderFunctions.parseExtraData(this)); this.parsedExtraData = Suppliers.memoize(() -> blockHeaderFunctions.parseExtraData(this));
@@ -191,8 +191,8 @@ public class BlockHeader extends SealableBlockHeader
if (requestsHash == null) break; if (requestsHash == null) break;
out.writeBytes(requestsHash); out.writeBytes(requestsHash);
if (targetBlobCount == null) break; if (targetBlobsPerBlock == null) break;
out.writeUInt64Scalar(targetBlobCount); out.writeUInt64Scalar(targetBlobsPerBlock);
} while (false); } while (false);
out.endList(); out.endList();
} }
@@ -225,7 +225,8 @@ public class BlockHeader extends SealableBlockHeader
!input.isEndOfCurrentList() ? BlobGas.of(input.readUInt64Scalar()) : null; !input.isEndOfCurrentList() ? BlobGas.of(input.readUInt64Scalar()) : null;
final Bytes32 parentBeaconBlockRoot = !input.isEndOfCurrentList() ? input.readBytes32() : null; final Bytes32 parentBeaconBlockRoot = !input.isEndOfCurrentList() ? input.readBytes32() : null;
final Hash requestsHash = !input.isEndOfCurrentList() ? Hash.wrap(input.readBytes32()) : null; final Hash requestsHash = !input.isEndOfCurrentList() ? Hash.wrap(input.readBytes32()) : null;
final UInt64 targetBlobCount = !input.isEndOfCurrentList() ? input.readUInt64Scalar() : null; final UInt64 targetBlobsPerBlock =
!input.isEndOfCurrentList() ? input.readUInt64Scalar() : null;
input.leaveList(); input.leaveList();
return new BlockHeader( return new BlockHeader(
parentHash, parentHash,
@@ -249,7 +250,7 @@ public class BlockHeader extends SealableBlockHeader
excessBlobGas, excessBlobGas,
parentBeaconBlockRoot, parentBeaconBlockRoot,
requestsHash, requestsHash,
targetBlobCount, targetBlobsPerBlock,
blockHeaderFunctions); blockHeaderFunctions);
} }
@@ -303,8 +304,8 @@ public class BlockHeader extends SealableBlockHeader
if (requestsHash != null) { if (requestsHash != null) {
sb.append("requestsHash=").append(requestsHash); sb.append("requestsHash=").append(requestsHash);
} }
if (targetBlobCount != null) { if (targetBlobsPerBlock != null) {
sb.append("targetBlobCount=").append(targetBlobCount); sb.append("targetBlobsPerBlock=").append(targetBlobsPerBlock);
} }
return sb.append("}").toString(); return sb.append("}").toString();
} }
@@ -340,7 +341,7 @@ public class BlockHeader extends SealableBlockHeader
.getRequestsHash() .getRequestsHash()
.map(h -> Hash.fromHexString(h.toHexString())) .map(h -> Hash.fromHexString(h.toHexString()))
.orElse(null), .orElse(null),
pluginBlockHeader.getTargetBlobCount().orElse(null), pluginBlockHeader.getTargetBlobsPerBlock().orElse(null),
blockHeaderFunctions); blockHeaderFunctions);
} }

View File

@@ -77,7 +77,7 @@ public class BlockHeaderBuilder {
private Long blobGasUsed = null; private Long blobGasUsed = null;
private BlobGas excessBlobGas = null; private BlobGas excessBlobGas = null;
private Bytes32 parentBeaconBlockRoot = null; private Bytes32 parentBeaconBlockRoot = null;
private UInt64 targetBlobCount = null; private UInt64 targetBlobsPerBlock = null;
public static BlockHeaderBuilder create() { public static BlockHeaderBuilder create() {
return new BlockHeaderBuilder(); return new BlockHeaderBuilder();
@@ -127,7 +127,7 @@ public class BlockHeaderBuilder {
.excessBlobGas(header.getExcessBlobGas().orElse(null)) .excessBlobGas(header.getExcessBlobGas().orElse(null))
.parentBeaconBlockRoot(header.getParentBeaconBlockRoot().orElse(null)) .parentBeaconBlockRoot(header.getParentBeaconBlockRoot().orElse(null))
.requestsHash(header.getRequestsHash().orElse(null)) .requestsHash(header.getRequestsHash().orElse(null))
.targetBlobCount(header.getTargetBlobCount().orElse(null)); .targetBlobsPerBlock(header.getTargetBlobsPerBlock().orElse(null));
} }
public static BlockHeaderBuilder fromBuilder(final BlockHeaderBuilder fromBuilder) { public static BlockHeaderBuilder fromBuilder(final BlockHeaderBuilder fromBuilder) {
@@ -152,7 +152,7 @@ public class BlockHeaderBuilder {
.excessBlobGas(fromBuilder.excessBlobGas) .excessBlobGas(fromBuilder.excessBlobGas)
.parentBeaconBlockRoot(fromBuilder.parentBeaconBlockRoot) .parentBeaconBlockRoot(fromBuilder.parentBeaconBlockRoot)
.requestsHash(fromBuilder.requestsHash) .requestsHash(fromBuilder.requestsHash)
.targetBlobCount(fromBuilder.targetBlobCount) .targetBlobsPerBlock(fromBuilder.targetBlobsPerBlock)
.blockHeaderFunctions(fromBuilder.blockHeaderFunctions); .blockHeaderFunctions(fromBuilder.blockHeaderFunctions);
toBuilder.nonce = fromBuilder.nonce; toBuilder.nonce = fromBuilder.nonce;
return toBuilder; return toBuilder;
@@ -183,7 +183,7 @@ public class BlockHeaderBuilder {
excessBlobGas, excessBlobGas,
parentBeaconBlockRoot, parentBeaconBlockRoot,
requestsHash, requestsHash,
targetBlobCount, targetBlobsPerBlock,
blockHeaderFunctions); blockHeaderFunctions);
} }
@@ -200,7 +200,7 @@ public class BlockHeaderBuilder {
baseFee, baseFee,
mixHashOrPrevRandao, mixHashOrPrevRandao,
parentBeaconBlockRoot, parentBeaconBlockRoot,
targetBlobCount); targetBlobsPerBlock);
} }
public SealableBlockHeader buildSealableBlockHeader() { public SealableBlockHeader buildSealableBlockHeader() {
@@ -227,7 +227,7 @@ public class BlockHeaderBuilder {
excessBlobGas, excessBlobGas,
parentBeaconBlockRoot, parentBeaconBlockRoot,
requestsHash, requestsHash,
targetBlobCount); targetBlobsPerBlock);
} }
private void validateBlockHeader() { private void validateBlockHeader() {
@@ -267,7 +267,7 @@ public class BlockHeaderBuilder {
baseFee(processableBlockHeader.getBaseFee().orElse(null)); baseFee(processableBlockHeader.getBaseFee().orElse(null));
processableBlockHeader.getPrevRandao().ifPresent(this::prevRandao); processableBlockHeader.getPrevRandao().ifPresent(this::prevRandao);
processableBlockHeader.getParentBeaconBlockRoot().ifPresent(this::parentBeaconBlockRoot); processableBlockHeader.getParentBeaconBlockRoot().ifPresent(this::parentBeaconBlockRoot);
processableBlockHeader.getTargetBlobCount().ifPresent(this::targetBlobCount); processableBlockHeader.getTargetBlobsPerBlock().ifPresent(this::targetBlobsPerBlock);
return this; return this;
} }
@@ -293,7 +293,7 @@ public class BlockHeaderBuilder {
sealableBlockHeader.getExcessBlobGas().ifPresent(this::excessBlobGas); sealableBlockHeader.getExcessBlobGas().ifPresent(this::excessBlobGas);
sealableBlockHeader.getParentBeaconBlockRoot().ifPresent(this::parentBeaconBlockRoot); sealableBlockHeader.getParentBeaconBlockRoot().ifPresent(this::parentBeaconBlockRoot);
requestsHash(sealableBlockHeader.getRequestsHash().orElse(null)); requestsHash(sealableBlockHeader.getRequestsHash().orElse(null));
sealableBlockHeader.getTargetBlobCount().ifPresent(this::targetBlobCount); sealableBlockHeader.getTargetBlobsPerBlock().ifPresent(this::targetBlobsPerBlock);
return this; return this;
} }
@@ -428,8 +428,8 @@ public class BlockHeaderBuilder {
return this; return this;
} }
public BlockHeaderBuilder targetBlobCount(final UInt64 targetBlobCount) { public BlockHeaderBuilder targetBlobsPerBlock(final UInt64 targetBlobsPerBlock) {
this.targetBlobCount = targetBlobCount; this.targetBlobsPerBlock = targetBlobsPerBlock;
return this; return this;
} }
} }

View File

@@ -20,7 +20,7 @@ import org.hyperledger.besu.crypto.SignatureAlgorithm;
import org.hyperledger.besu.crypto.SignatureAlgorithmFactory; import org.hyperledger.besu.crypto.SignatureAlgorithmFactory;
import org.hyperledger.besu.datatypes.Address; import org.hyperledger.besu.datatypes.Address;
import org.hyperledger.besu.datatypes.Hash; import org.hyperledger.besu.datatypes.Hash;
import org.hyperledger.besu.ethereum.core.encoding.CodeDelegationEncoder; import org.hyperledger.besu.ethereum.core.encoding.CodeDelegationTransactionEncoder;
import org.hyperledger.besu.ethereum.rlp.BytesValueRLPOutput; import org.hyperledger.besu.ethereum.rlp.BytesValueRLPOutput;
import java.math.BigInteger; import java.math.BigInteger;
@@ -140,7 +140,7 @@ public class CodeDelegation implements org.hyperledger.besu.datatypes.CodeDelega
private Optional<Address> computeAuthority() { private Optional<Address> computeAuthority() {
BytesValueRLPOutput rlpOutput = new BytesValueRLPOutput(); BytesValueRLPOutput rlpOutput = new BytesValueRLPOutput();
CodeDelegationEncoder.encodeSingleCodeDelegationWithoutSignature(this, rlpOutput); CodeDelegationTransactionEncoder.encodeSingleCodeDelegationWithoutSignature(this, rlpOutput);
final Hash hash = Hash.hash(Bytes.concatenate(MAGIC, rlpOutput.encoded())); final Hash hash = Hash.hash(Bytes.concatenate(MAGIC, rlpOutput.encoded()));

View File

@@ -48,7 +48,7 @@ public class ProcessableBlockHeader
// parentBeaconBlockRoot is included for Cancun // parentBeaconBlockRoot is included for Cancun
protected final Bytes32 parentBeaconBlockRoot; protected final Bytes32 parentBeaconBlockRoot;
// TODO SLD Quantity or UInt64Value<UInt64> instead? // TODO SLD Quantity or UInt64Value<UInt64> instead?
protected final UInt64 targetBlobCount; protected final UInt64 targetBlobsPerBlock;
protected ProcessableBlockHeader( protected ProcessableBlockHeader(
final Hash parentHash, final Hash parentHash,
@@ -60,7 +60,7 @@ public class ProcessableBlockHeader
final Wei baseFee, final Wei baseFee,
final Bytes32 mixHashOrPrevRandao, final Bytes32 mixHashOrPrevRandao,
final Bytes32 parentBeaconBlockRoot, final Bytes32 parentBeaconBlockRoot,
final UInt64 targetBlobCount) { final UInt64 targetBlobsPerBlock) {
this.parentHash = parentHash; this.parentHash = parentHash;
this.coinbase = coinbase; this.coinbase = coinbase;
this.difficulty = difficulty; this.difficulty = difficulty;
@@ -70,7 +70,7 @@ public class ProcessableBlockHeader
this.baseFee = baseFee; this.baseFee = baseFee;
this.mixHashOrPrevRandao = mixHashOrPrevRandao; this.mixHashOrPrevRandao = mixHashOrPrevRandao;
this.parentBeaconBlockRoot = parentBeaconBlockRoot; this.parentBeaconBlockRoot = parentBeaconBlockRoot;
this.targetBlobCount = targetBlobCount; this.targetBlobsPerBlock = targetBlobsPerBlock;
} }
/** /**
@@ -184,13 +184,13 @@ public class ProcessableBlockHeader
} }
/** /**
* Returns the target blob count if available. * Returns the target blobs per block if available.
* *
* @return the target blob count if available. * @return the target blobs per block if available.
*/ */
@Override @Override
public Optional<UInt64> getTargetBlobCount() { public Optional<UInt64> getTargetBlobsPerBlock() {
return Optional.ofNullable(targetBlobCount); return Optional.ofNullable(targetBlobsPerBlock);
} }
public String toLogString() { public String toLogString() {

View File

@@ -71,7 +71,7 @@ public class SealableBlockHeader extends ProcessableBlockHeader {
final BlobGas excessBlobGas, final BlobGas excessBlobGas,
final Bytes32 parentBeaconBlockRoot, final Bytes32 parentBeaconBlockRoot,
final Hash requestsHash, final Hash requestsHash,
final UInt64 targetBlobCount) { final UInt64 targetBlobsPerBlock) {
super( super(
parentHash, parentHash,
coinbase, coinbase,
@@ -82,7 +82,7 @@ public class SealableBlockHeader extends ProcessableBlockHeader {
baseFee, baseFee,
mixHashOrPrevRandao, mixHashOrPrevRandao,
parentBeaconBlockRoot, parentBeaconBlockRoot,
targetBlobCount); targetBlobsPerBlock);
this.ommersHash = ommersHash; this.ommersHash = ommersHash;
this.stateRoot = stateRoot; this.stateRoot = stateRoot;
this.transactionsRoot = transactionsRoot; this.transactionsRoot = transactionsRoot;

View File

@@ -38,7 +38,7 @@ import org.hyperledger.besu.datatypes.VersionedHash;
import org.hyperledger.besu.datatypes.Wei; import org.hyperledger.besu.datatypes.Wei;
import org.hyperledger.besu.ethereum.core.encoding.AccessListTransactionEncoder; import org.hyperledger.besu.ethereum.core.encoding.AccessListTransactionEncoder;
import org.hyperledger.besu.ethereum.core.encoding.BlobTransactionEncoder; import org.hyperledger.besu.ethereum.core.encoding.BlobTransactionEncoder;
import org.hyperledger.besu.ethereum.core.encoding.CodeDelegationEncoder; import org.hyperledger.besu.ethereum.core.encoding.CodeDelegationTransactionEncoder;
import org.hyperledger.besu.ethereum.core.encoding.EncodingContext; import org.hyperledger.besu.ethereum.core.encoding.EncodingContext;
import org.hyperledger.besu.ethereum.core.encoding.TransactionDecoder; import org.hyperledger.besu.ethereum.core.encoding.TransactionDecoder;
import org.hyperledger.besu.ethereum.core.encoding.TransactionEncoder; import org.hyperledger.besu.ethereum.core.encoding.TransactionEncoder;
@@ -937,7 +937,8 @@ public class Transaction
chainId, chainId,
accessList, accessList,
rlpOutput); rlpOutput);
CodeDelegationEncoder.encodeCodeDelegationInner(authorizationList, rlpOutput); CodeDelegationTransactionEncoder.encodeCodeDelegationInner(
authorizationList, rlpOutput);
rlpOutput.endList(); rlpOutput.endList();
}); });
return Bytes.concatenate(Bytes.of(TransactionType.DELEGATE_CODE.getSerializedType()), encoded); return Bytes.concatenate(Bytes.of(TransactionType.DELEGATE_CODE.getSerializedType()), encoded);

View File

@@ -81,7 +81,7 @@ public class CodeDelegationTransactionDecoder {
final Address address = Address.wrap(input.readBytes()); final Address address = Address.wrap(input.readBytes());
final long nonce = input.readLongScalar(); final long nonce = input.readLongScalar();
final BigInteger yParity = input.readUInt256Scalar().toUnsignedBigInteger(); final byte yParity = (byte) input.readUnsignedByteScalar();
final BigInteger r = input.readUInt256Scalar().toUnsignedBigInteger(); final BigInteger r = input.readUInt256Scalar().toUnsignedBigInteger();
final BigInteger s = input.readUInt256Scalar().toUnsignedBigInteger(); final BigInteger s = input.readUInt256Scalar().toUnsignedBigInteger();

View File

@@ -25,9 +25,9 @@ import java.util.List;
import org.apache.tuweni.bytes.Bytes; import org.apache.tuweni.bytes.Bytes;
public class CodeDelegationEncoder { public class CodeDelegationTransactionEncoder {
private CodeDelegationEncoder() { private CodeDelegationTransactionEncoder() {
// private constructor // private constructor
} }
@@ -49,7 +49,7 @@ public class CodeDelegationEncoder {
final CodeDelegation payload, final RLPOutput rlpOutput) { final CodeDelegation payload, final RLPOutput rlpOutput) {
rlpOutput.startList(); rlpOutput.startList();
encodeAuthorizationDetails(payload, rlpOutput); encodeAuthorizationDetails(payload, rlpOutput);
rlpOutput.writeIntScalar(payload.signature().getRecId()); rlpOutput.writeUnsignedByte(payload.signature().getRecId() & 0xFF);
rlpOutput.writeBigIntegerScalar(payload.signature().getR()); rlpOutput.writeBigIntegerScalar(payload.signature().getR());
rlpOutput.writeBigIntegerScalar(payload.signature().getS()); rlpOutput.writeBigIntegerScalar(payload.signature().getS());
rlpOutput.endList(); rlpOutput.endList();

View File

@@ -41,7 +41,7 @@ public class TransactionEncoder {
TransactionType.BLOB, TransactionType.BLOB,
BlobTransactionEncoder::encode, BlobTransactionEncoder::encode,
TransactionType.DELEGATE_CODE, TransactionType.DELEGATE_CODE,
CodeDelegationEncoder::encode); CodeDelegationTransactionEncoder::encode);
private static final ImmutableMap<TransactionType, Encoder> POOLED_TRANSACTION_ENCODERS = private static final ImmutableMap<TransactionType, Encoder> POOLED_TRANSACTION_ENCODERS =
ImmutableMap.of(TransactionType.BLOB, BlobPooledTransactionEncoder::encode); ImmutableMap.of(TransactionType.BLOB, BlobPooledTransactionEncoder::encode);

View File

@@ -14,6 +14,8 @@
*/ */
package org.hyperledger.besu.ethereum.mainnet; package org.hyperledger.besu.ethereum.mainnet;
import static org.hyperledger.besu.evm.account.Account.MAX_NONCE;
import org.hyperledger.besu.datatypes.Address; import org.hyperledger.besu.datatypes.Address;
import org.hyperledger.besu.ethereum.core.CodeDelegation; import org.hyperledger.besu.ethereum.core.CodeDelegation;
import org.hyperledger.besu.ethereum.core.Transaction; import org.hyperledger.besu.ethereum.core.Transaction;
@@ -30,9 +32,12 @@ public class CodeDelegationProcessor {
private static final Logger LOG = LoggerFactory.getLogger(CodeDelegationProcessor.class); private static final Logger LOG = LoggerFactory.getLogger(CodeDelegationProcessor.class);
private final Optional<BigInteger> maybeChainId; private final Optional<BigInteger> maybeChainId;
private final BigInteger halfCurveOrder;
public CodeDelegationProcessor(final Optional<BigInteger> maybeChainId) { public CodeDelegationProcessor(
final Optional<BigInteger> maybeChainId, final BigInteger halfCurveOrder) {
this.maybeChainId = maybeChainId; this.maybeChainId = maybeChainId;
this.halfCurveOrder = halfCurveOrder;
} }
/** /**
@@ -89,6 +94,22 @@ public class CodeDelegationProcessor {
return; return;
} }
if (codeDelegation.nonce() == MAX_NONCE) {
LOG.trace("Nonce of code delegation must be less than 2^64-1");
return;
}
if (codeDelegation.signature().getS().compareTo(halfCurveOrder) > 0) {
LOG.trace(
"Invalid signature for code delegation. S value must be less or equal than the half curve order.");
return;
}
if (codeDelegation.signature().getRecId() != 0 && codeDelegation.signature().getRecId() != 1) {
LOG.trace("Invalid signature for code delegation. RecId must be 0 or 1.");
return;
}
final Optional<Address> authorizer = codeDelegation.authorizer(); final Optional<Address> authorizer = codeDelegation.authorizer();
if (authorizer.isEmpty()) { if (authorizer.isEmpty()) {
LOG.trace("Invalid signature for code delegation"); LOG.trace("Invalid signature for code delegation");
@@ -128,7 +149,9 @@ public class CodeDelegationProcessor {
result.incremenentAlreadyExistingDelegators(); result.incremenentAlreadyExistingDelegators();
} }
evmWorldUpdater.authorizedCodeService().addDelegatedCode(authority, codeDelegation.address()); evmWorldUpdater
.authorizedCodeService()
.processDelegatedCodeAuthorization(authority, codeDelegation.address());
authority.incrementNonce(); authority.incrementNonce();
} }
} }

View File

@@ -18,6 +18,8 @@ import static org.hyperledger.besu.ethereum.mainnet.requests.MainnetRequestsProc
import org.hyperledger.besu.config.GenesisConfigOptions; import org.hyperledger.besu.config.GenesisConfigOptions;
import org.hyperledger.besu.config.PowAlgorithm; import org.hyperledger.besu.config.PowAlgorithm;
import org.hyperledger.besu.crypto.SignatureAlgorithm;
import org.hyperledger.besu.crypto.SignatureAlgorithmFactory;
import org.hyperledger.besu.datatypes.Address; import org.hyperledger.besu.datatypes.Address;
import org.hyperledger.besu.datatypes.TransactionType; import org.hyperledger.besu.datatypes.TransactionType;
import org.hyperledger.besu.datatypes.Wei; import org.hyperledger.besu.datatypes.Wei;
@@ -80,6 +82,8 @@ import java.util.Optional;
import java.util.Set; import java.util.Set;
import java.util.stream.IntStream; import java.util.stream.IntStream;
import com.google.common.base.Supplier;
import com.google.common.base.Suppliers;
import com.google.common.io.Resources; import com.google.common.io.Resources;
import io.vertx.core.json.JsonArray; import io.vertx.core.json.JsonArray;
@@ -89,6 +93,9 @@ public abstract class MainnetProtocolSpecs {
private static final Address RIPEMD160_PRECOMPILE = private static final Address RIPEMD160_PRECOMPILE =
Address.fromHexString("0x0000000000000000000000000000000000000003"); Address.fromHexString("0x0000000000000000000000000000000000000003");
private static final Supplier<SignatureAlgorithm> SIGNATURE_ALGORITHM =
Suppliers.memoize(SignatureAlgorithmFactory::getInstance);
// A consensus bug at Ethereum mainnet transaction 0xcf416c53 // A consensus bug at Ethereum mainnet transaction 0xcf416c53
// deleted an empty account even when the message execution scope // deleted an empty account even when the message execution scope
// failed, but the transaction itself succeeded. // failed, but the transaction itself succeeded.
@@ -714,7 +721,8 @@ public abstract class MainnetProtocolSpecs {
evmConfiguration.evmStackSize(), evmConfiguration.evmStackSize(),
feeMarket, feeMarket,
CoinbaseFeePriceCalculator.eip1559(), CoinbaseFeePriceCalculator.eip1559(),
new CodeDelegationProcessor(chainId))) new CodeDelegationProcessor(
chainId, SIGNATURE_ALGORITHM.get().getHalfCurveOrder())))
// change to check for max blob gas per block for EIP-4844 // change to check for max blob gas per block for EIP-4844
.transactionValidatorFactoryBuilder( .transactionValidatorFactoryBuilder(
(evm, gasLimitCalculator, feeMarket) -> (evm, gasLimitCalculator, feeMarket) ->

View File

@@ -286,7 +286,7 @@ public class MainnetTransactionProcessor {
final TransactionValidationParams transactionValidationParams, final TransactionValidationParams transactionValidationParams,
final PrivateMetadataUpdater privateMetadataUpdater, final PrivateMetadataUpdater privateMetadataUpdater,
final Wei blobGasPrice) { final Wei blobGasPrice) {
final EVMWorldUpdater evmWorldUpdater = new EVMWorldUpdater(worldState); final EVMWorldUpdater evmWorldUpdater = new EVMWorldUpdater(worldState, gasCalculator);
try { try {
final var transactionValidator = transactionValidatorFactory.get(); final var transactionValidator = transactionValidatorFactory.get();
LOG.trace("Starting execution of {}", transaction); LOG.trace("Starting execution of {}", transaction);
@@ -352,6 +352,8 @@ public class MainnetTransactionProcessor {
codeDelegationRefund = codeDelegationRefund =
gasCalculator.calculateDelegateCodeGasRefund( gasCalculator.calculateDelegateCodeGasRefund(
(codeDelegationResult.alreadyExistingDelegators())); (codeDelegationResult.alreadyExistingDelegators()));
evmWorldUpdater.commit();
} }
final List<AccessListEntry> accessListEntries = transaction.getAccessList().orElse(List.of()); final List<AccessListEntry> accessListEntries = transaction.getAccessList().orElse(List.of());
@@ -415,7 +417,6 @@ public class MainnetTransactionProcessor {
.miningBeneficiary(miningBeneficiary) .miningBeneficiary(miningBeneficiary)
.blockHashLookup(blockHashLookup) .blockHashLookup(blockHashLookup)
.contextVariables(contextVariablesBuilder.build()) .contextVariables(contextVariablesBuilder.build())
.accessListWarmAddresses(warmAddressList)
.accessListWarmStorage(storageList); .accessListWarmStorage(storageList);
if (transaction.getVersionedHashes().isPresent()) { if (transaction.getVersionedHashes().isPresent()) {
@@ -439,11 +440,17 @@ public class MainnetTransactionProcessor {
.contract(contractAddress) .contract(contractAddress)
.inputData(initCodeBytes.slice(code.getSize())) .inputData(initCodeBytes.slice(code.getSize()))
.code(code) .code(code)
.accessListWarmAddresses(warmAddressList)
.build(); .build();
} else { } else {
@SuppressWarnings("OptionalGetWithoutIsPresent") // isContractCall tests isPresent @SuppressWarnings("OptionalGetWithoutIsPresent") // isContractCall tests isPresent
final Address to = transaction.getTo().get(); final Address to = transaction.getTo().get();
final Optional<Account> maybeContract = Optional.ofNullable(evmWorldUpdater.get(to)); final Optional<Account> maybeContract = Optional.ofNullable(evmWorldUpdater.get(to));
if (maybeContract.isPresent() && maybeContract.get().hasDelegatedCode()) {
warmAddressList.add(maybeContract.get().delegatedCodeAddress().get());
}
initialFrame = initialFrame =
commonMessageFrameBuilder commonMessageFrameBuilder
.type(MessageFrame.Type.MESSAGE_CALL) .type(MessageFrame.Type.MESSAGE_CALL)
@@ -454,6 +461,7 @@ public class MainnetTransactionProcessor {
maybeContract maybeContract
.map(c -> messageCallProcessor.getCodeFromEVM(c.getCodeHash(), c.getCode())) .map(c -> messageCallProcessor.getCodeFromEVM(c.getCodeHash(), c.getCode()))
.orElse(CodeV0.EMPTY_CODE)) .orElse(CodeV0.EMPTY_CODE))
.accessListWarmAddresses(warmAddressList)
.build(); .build();
} }
Deque<MessageFrame> messageFrameStack = initialFrame.getMessageFrameStack(); Deque<MessageFrame> messageFrameStack = initialFrame.getMessageFrameStack();

View File

@@ -52,6 +52,8 @@ import org.bouncycastle.crypto.digests.SHA256Digest;
*/ */
public class MainnetTransactionValidator implements TransactionValidator { public class MainnetTransactionValidator implements TransactionValidator {
public static final BigInteger TWO_POW_8 = BigInteger.TWO.pow(8);
public static final BigInteger TWO_POW_64 = BigInteger.TWO.pow(64);
public static final BigInteger TWO_POW_256 = BigInteger.TWO.pow(256); public static final BigInteger TWO_POW_256 = BigInteger.TWO.pow(256);
private final GasCalculator gasCalculator; private final GasCalculator gasCalculator;
@@ -158,30 +160,26 @@ public class MainnetTransactionValidator implements TransactionValidator {
"transaction code delegation transactions must have a to address"); "transaction code delegation transactions must have a to address");
} }
final BigInteger halfCurveOrder = SignatureAlgorithmFactory.getInstance().getHalfCurveOrder();
final Optional<ValidationResult<TransactionInvalidReason>> validationResult = final Optional<ValidationResult<TransactionInvalidReason>> validationResult =
transaction transaction
.getCodeDelegationList() .getCodeDelegationList()
.map( .map(
codeDelegations -> { codeDelegations -> {
for (CodeDelegation codeDelegation : codeDelegations) { for (CodeDelegation codeDelegation : codeDelegations) {
if (codeDelegation.chainId().compareTo(TWO_POW_256) >= 0) { if (codeDelegation.chainId().compareTo(TWO_POW_64) >= 0) {
throw new IllegalArgumentException( throw new IllegalArgumentException(
"Invalid 'chainId' value, should be < 2^256 but got " "Invalid 'chainId' value, should be < 2^64 but got "
+ codeDelegation.chainId()); + codeDelegation.chainId());
} }
if (codeDelegation.signature().getS().compareTo(halfCurveOrder) > 0) { if (codeDelegation.r().compareTo(TWO_POW_256) >= 0) {
return ValidationResult.invalid( throw new IllegalArgumentException(
TransactionInvalidReason.INVALID_SIGNATURE, "Invalid 'r' value, should be < 2^256 but got " + codeDelegation.r());
"Invalid signature for code delegation. S value must be less or equal than the half curve order.");
} }
if (codeDelegation.signature().getRecId() != 0 if (codeDelegation.s().compareTo(TWO_POW_256) >= 0) {
&& codeDelegation.signature().getRecId() != 1) { throw new IllegalArgumentException(
return ValidationResult.invalid( "Invalid 's' value, should be < 2^256 but got " + codeDelegation.s());
TransactionInvalidReason.INVALID_SIGNATURE,
"Invalid signature for code delegation. RecId value must be 0 or 1.");
} }
} }

View File

@@ -56,7 +56,7 @@ public class BlockHeaderTestFixture {
private Optional<BlobGas> excessBlobGas = Optional.empty(); private Optional<BlobGas> excessBlobGas = Optional.empty();
private Optional<Long> blobGasUsed = Optional.empty(); private Optional<Long> blobGasUsed = Optional.empty();
private Optional<Bytes32> parentBeaconBlockRoot = Optional.empty(); private Optional<Bytes32> parentBeaconBlockRoot = Optional.empty();
private Optional<UInt64> targetBlobCount = Optional.empty(); private Optional<UInt64> targetBlobsPerBlock = Optional.empty();
public BlockHeader buildHeader() { public BlockHeader buildHeader() {
final BlockHeaderBuilder builder = BlockHeaderBuilder.create(); final BlockHeaderBuilder builder = BlockHeaderBuilder.create();
@@ -82,7 +82,7 @@ public class BlockHeaderTestFixture {
blobGasUsed.ifPresent(builder::blobGasUsed); blobGasUsed.ifPresent(builder::blobGasUsed);
requestsHash.ifPresent(builder::requestsHash); requestsHash.ifPresent(builder::requestsHash);
parentBeaconBlockRoot.ifPresent(builder::parentBeaconBlockRoot); parentBeaconBlockRoot.ifPresent(builder::parentBeaconBlockRoot);
targetBlobCount.ifPresent(builder::targetBlobCount); targetBlobsPerBlock.ifPresent(builder::targetBlobsPerBlock);
builder.blockHeaderFunctions(blockHeaderFunctions); builder.blockHeaderFunctions(blockHeaderFunctions);
return builder.buildBlockHeader(); return builder.buildBlockHeader();
@@ -205,8 +205,8 @@ public class BlockHeaderTestFixture {
return this; return this;
} }
public BlockHeaderTestFixture targetBlobCount(final UInt64 targetBlobCount) { public BlockHeaderTestFixture targetBlobsPerBlock(final UInt64 targetBlobsPerBlock) {
this.targetBlobCount = Optional.of(targetBlobCount); this.targetBlobsPerBlock = Optional.of(targetBlobsPerBlock);
return this; return this;
} }
} }

View File

@@ -328,8 +328,8 @@ final class GenesisStateTest {
.isEqualTo( .isEqualTo(
Hash.fromHexString( Hash.fromHexString(
"0x6036c41849da9c076ed79654d434017387a88fb833c2856b32e18218b3341c5f")); "0x6036c41849da9c076ed79654d434017387a88fb833c2856b32e18218b3341c5f"));
assertThat(header.getTargetBlobCount().isPresent()).isTrue(); assertThat(header.getTargetBlobsPerBlock().isPresent()).isTrue();
assertThat(header.getTargetBlobCount().get()).isEqualTo(UInt64.ONE); assertThat(header.getTargetBlobsPerBlock().get()).isEqualTo(UInt64.ONE);
assertThat(header.getHash()) assertThat(header.getHash())
.isEqualTo( .isEqualTo(

View File

@@ -30,7 +30,7 @@ import org.apache.tuweni.bytes.Bytes;
import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test; import org.junit.jupiter.api.Test;
class CodeDelegationEncoderTest { class CodeDelegationTransactionEncoderTest {
private static final Supplier<SignatureAlgorithm> SIGNATURE_ALGORITHM = private static final Supplier<SignatureAlgorithm> SIGNATURE_ALGORITHM =
Suppliers.memoize(SignatureAlgorithmFactory::getInstance); Suppliers.memoize(SignatureAlgorithmFactory::getInstance);
@@ -59,7 +59,7 @@ class CodeDelegationEncoderTest {
"3b1dbace38ceb862a65bf2eac0637693b5c3493bcb2a022dd614c0a74cce0b99", 16), "3b1dbace38ceb862a65bf2eac0637693b5c3493bcb2a022dd614c0a74cce0b99", 16),
(byte) 0)); (byte) 0));
CodeDelegationEncoder.encodeSingleCodeDelegation(authorization, output); CodeDelegationTransactionEncoder.encodeSingleCodeDelegation(authorization, output);
assertThat(output.encoded()) assertThat(output.encoded())
.isEqualTo( .isEqualTo(
@@ -85,7 +85,7 @@ class CodeDelegationEncoderTest {
"25b58a1ff8ad00bddbbfa1d5c2411961cbb6d08dcdc8ae88303db3c6cf983031", 16), "25b58a1ff8ad00bddbbfa1d5c2411961cbb6d08dcdc8ae88303db3c6cf983031", 16),
(byte) 1)); (byte) 1));
CodeDelegationEncoder.encodeSingleCodeDelegation(authorization, output); CodeDelegationTransactionEncoder.encodeSingleCodeDelegation(authorization, output);
assertThat(output.encoded()) assertThat(output.encoded())
.isEqualTo( .isEqualTo(
@@ -111,7 +111,7 @@ class CodeDelegationEncoderTest {
"3c8a25b2becd6e666f69803d1ae3322f2e137b7745c2c7f19da80f993ffde4df", 16), "3c8a25b2becd6e666f69803d1ae3322f2e137b7745c2c7f19da80f993ffde4df", 16),
(byte) 1)); (byte) 1));
CodeDelegationEncoder.encodeSingleCodeDelegation(authorization, output); CodeDelegationTransactionEncoder.encodeSingleCodeDelegation(authorization, output);
assertThat(output.encoded()) assertThat(output.encoded())
.isEqualTo( .isEqualTo(

View File

@@ -0,0 +1,236 @@
/*
* Copyright contributors to Hyperledger Besu.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
* an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
* specific language governing permissions and limitations under the License.
*
* SPDX-License-Identifier: Apache-2.0
*/
package org.hyperledger.besu.ethereum.mainnet;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import org.hyperledger.besu.crypto.SECPSignature;
import org.hyperledger.besu.datatypes.Address;
import org.hyperledger.besu.datatypes.CodeDelegation;
import org.hyperledger.besu.ethereum.core.Transaction;
import org.hyperledger.besu.evm.account.Account;
import org.hyperledger.besu.evm.account.MutableAccount;
import org.hyperledger.besu.evm.worldstate.DelegatedCodeService;
import org.hyperledger.besu.evm.worldstate.EVMWorldUpdater;
import java.math.BigInteger;
import java.util.List;
import java.util.Optional;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.Mock;
import org.mockito.junit.jupiter.MockitoExtension;
@ExtendWith(MockitoExtension.class)
class CodeDelegationProcessorTest {
@Mock private EVMWorldUpdater worldUpdater;
@Mock private Transaction transaction;
@Mock private DelegatedCodeService authorizedCodeService;
@Mock private MutableAccount authority;
private CodeDelegationProcessor processor;
private static final BigInteger CHAIN_ID = BigInteger.valueOf(1);
private static final BigInteger HALF_CURVE_ORDER = BigInteger.valueOf(1000);
private static final Address DELEGATE_ADDRESS =
Address.fromHexString("0x9876543210987654321098765432109876543210");
@BeforeEach
void setUp() {
processor = new CodeDelegationProcessor(Optional.of(CHAIN_ID), HALF_CURVE_ORDER);
}
@Test
void shouldRejectInvalidChainId() {
// Arrange
CodeDelegation codeDelegation = createCodeDelegation(BigInteger.valueOf(2), 0L);
when(transaction.getCodeDelegationList()).thenReturn(Optional.of(List.of(codeDelegation)));
// Act
CodeDelegationResult result = processor.process(worldUpdater, transaction);
// Assert
assertThat(result.alreadyExistingDelegators()).isZero();
verify(worldUpdater, never()).createAccount(any());
verify(worldUpdater, never()).getAccount(any());
}
@Test
void shouldRejectMaxNonce() {
// Arrange
CodeDelegation codeDelegation = createCodeDelegation(CHAIN_ID, Account.MAX_NONCE);
when(transaction.getCodeDelegationList()).thenReturn(Optional.of(List.of(codeDelegation)));
// Act
CodeDelegationResult result = processor.process(worldUpdater, transaction);
// Assert
assertThat(result.alreadyExistingDelegators()).isZero();
verify(worldUpdater, never()).createAccount(any());
verify(worldUpdater, never()).getAccount(any());
}
@Test
void shouldProcessValidDelegationForNewAccount() {
// Arrange
when(worldUpdater.authorizedCodeService()).thenReturn(authorizedCodeService);
CodeDelegation codeDelegation = createCodeDelegation(CHAIN_ID, 0L);
when(transaction.getCodeDelegationList()).thenReturn(Optional.of(List.of(codeDelegation)));
when(worldUpdater.getAccount(any())).thenReturn(null);
when(worldUpdater.createAccount(any())).thenReturn(authority);
when(authority.getNonce()).thenReturn(0L);
// Act
CodeDelegationResult result = processor.process(worldUpdater, transaction);
// Assert
assertThat(result.alreadyExistingDelegators()).isZero();
verify(worldUpdater).createAccount(any());
verify(authority).incrementNonce();
verify(authorizedCodeService).processDelegatedCodeAuthorization(authority, DELEGATE_ADDRESS);
}
@Test
void shouldProcessValidDelegationForExistingAccount() {
// Arrange
when(worldUpdater.authorizedCodeService()).thenReturn(authorizedCodeService);
CodeDelegation codeDelegation = createCodeDelegation(CHAIN_ID, 1L);
when(transaction.getCodeDelegationList()).thenReturn(Optional.of(List.of(codeDelegation)));
when(worldUpdater.getAccount(any())).thenReturn(authority);
when(authority.getNonce()).thenReturn(1L);
when(authorizedCodeService.canSetDelegatedCode(any())).thenReturn(true);
// Act
CodeDelegationResult result = processor.process(worldUpdater, transaction);
// Assert
assertThat(result.alreadyExistingDelegators()).isEqualTo(1);
verify(worldUpdater, never()).createAccount(any());
verify(authority).incrementNonce();
verify(authorizedCodeService).processDelegatedCodeAuthorization(authority, DELEGATE_ADDRESS);
}
@Test
void shouldRejectDelegationWithInvalidNonce() {
// Arrange
when(worldUpdater.authorizedCodeService()).thenReturn(authorizedCodeService);
CodeDelegation codeDelegation = createCodeDelegation(CHAIN_ID, 2L);
when(transaction.getCodeDelegationList()).thenReturn(Optional.of(List.of(codeDelegation)));
when(worldUpdater.getAccount(any())).thenReturn(authority);
when(authorizedCodeService.canSetDelegatedCode(any())).thenReturn(true);
// Act
CodeDelegationResult result = processor.process(worldUpdater, transaction);
// Assert
assertThat(result.alreadyExistingDelegators()).isZero();
verify(authority, never()).incrementNonce();
verify(authorizedCodeService, never()).processDelegatedCodeAuthorization(any(), any());
}
@Test
void shouldRejectDelegationWithSGreaterThanHalfCurveOrder() {
// Arrange
CodeDelegation codeDelegation =
createCodeDelegation(CHAIN_ID, 1L, HALF_CURVE_ORDER.add(BigInteger.ONE));
when(transaction.getCodeDelegationList()).thenReturn(Optional.of(List.of(codeDelegation)));
// Act
CodeDelegationResult result = processor.process(worldUpdater, transaction);
// Assert
assertThat(result.alreadyExistingDelegators()).isZero();
verify(authority, never()).incrementNonce();
verify(authorizedCodeService, never()).processDelegatedCodeAuthorization(any(), any());
}
@Test
void shouldRejectDelegationWithRecIdNeitherZeroNorOne() {
// Arrange
final SECPSignature signature = new SECPSignature(BigInteger.ONE, BigInteger.ONE, (byte) 2);
CodeDelegation codeDelegation =
new org.hyperledger.besu.ethereum.core.CodeDelegation(
CHAIN_ID, CodeDelegationProcessorTest.DELEGATE_ADDRESS, 1L, signature);
when(transaction.getCodeDelegationList()).thenReturn(Optional.of(List.of(codeDelegation)));
// Act
CodeDelegationResult result = processor.process(worldUpdater, transaction);
// Assert
assertThat(result.alreadyExistingDelegators()).isZero();
verify(authority, never()).incrementNonce();
verify(authorizedCodeService, never()).processDelegatedCodeAuthorization(any(), any());
}
@Test
void shouldRejectDelegationWithInvalidSignature() {
// Arrange
CodeDelegation codeDelegation = mock(org.hyperledger.besu.ethereum.core.CodeDelegation.class);
when(codeDelegation.chainId()).thenReturn(CHAIN_ID);
when(codeDelegation.nonce()).thenReturn(1L);
when(codeDelegation.signature())
.thenReturn(new SECPSignature(BigInteger.ONE, BigInteger.ONE, (byte) 0));
when(codeDelegation.authorizer()).thenReturn(Optional.empty());
when(transaction.getCodeDelegationList()).thenReturn(Optional.of(List.of(codeDelegation)));
// Act
CodeDelegationResult result = processor.process(worldUpdater, transaction);
// Assert
assertThat(result.alreadyExistingDelegators()).isZero();
verify(authority, never()).incrementNonce();
verify(authorizedCodeService, never()).processDelegatedCodeAuthorization(any(), any());
}
@Test
void shouldRejectDelegationWhenCannotSetDelegatedCode() {
// Arrange
when(worldUpdater.authorizedCodeService()).thenReturn(authorizedCodeService);
CodeDelegation codeDelegation = createCodeDelegation(CHAIN_ID, 1L);
when(transaction.getCodeDelegationList()).thenReturn(Optional.of(List.of(codeDelegation)));
when(worldUpdater.getAccount(any())).thenReturn(authority);
when(authorizedCodeService.canSetDelegatedCode(any())).thenReturn(false);
// Act
CodeDelegationResult result = processor.process(worldUpdater, transaction);
// Assert
assertThat(result.alreadyExistingDelegators()).isZero();
verify(authority, never()).incrementNonce();
verify(authorizedCodeService, never()).processDelegatedCodeAuthorization(any(), any());
}
private CodeDelegation createCodeDelegation(final BigInteger chainId, final long nonce) {
return createCodeDelegation(chainId, nonce, BigInteger.ONE);
}
private CodeDelegation createCodeDelegation(
final BigInteger chainId, final long nonce, final BigInteger s) {
final SECPSignature signature = new SECPSignature(BigInteger.ONE, s, (byte) 0);
return new org.hyperledger.besu.ethereum.core.CodeDelegation(
chainId, CodeDelegationProcessorTest.DELEGATE_ADDRESS, nonce, signature);
}
}

View File

@@ -89,7 +89,7 @@ class MainnetTransactionProcessorTest {
MAX_STACK_SIZE, MAX_STACK_SIZE,
FeeMarket.legacy(), FeeMarket.legacy(),
CoinbaseFeePriceCalculator.frontier(), CoinbaseFeePriceCalculator.frontier(),
new CodeDelegationProcessor(Optional.of(BigInteger.ONE))); new CodeDelegationProcessor(Optional.of(BigInteger.ONE), BigInteger.TEN));
} }
@Test @Test

View File

@@ -4074,5 +4074,5 @@
"gasUsed": "0x0", "gasUsed": "0x0",
"parentHash": "0x0000000000000000000000000000000000000000000000000000000000000000", "parentHash": "0x0000000000000000000000000000000000000000000000000000000000000000",
"baseFeePerGas": "0x3b9aca00", "baseFeePerGas": "0x3b9aca00",
"targetBlobCount": "0x1" "targetBlobsPerBlock": "0x1"
} }

View File

@@ -27,6 +27,7 @@ import org.hyperledger.besu.ethereum.core.BlockHeaderTestFixture;
import org.hyperledger.besu.ethereum.core.MutableWorldState; import org.hyperledger.besu.ethereum.core.MutableWorldState;
import org.hyperledger.besu.ethereum.eth.manager.EthContext; import org.hyperledger.besu.ethereum.eth.manager.EthContext;
import org.hyperledger.besu.ethereum.eth.manager.EthProtocolManager; import org.hyperledger.besu.ethereum.eth.manager.EthProtocolManager;
import org.hyperledger.besu.ethereum.eth.manager.EthProtocolManagerTestBuilder;
import org.hyperledger.besu.ethereum.eth.manager.EthProtocolManagerTestUtil; import org.hyperledger.besu.ethereum.eth.manager.EthProtocolManagerTestUtil;
import org.hyperledger.besu.ethereum.eth.manager.EthScheduler; import org.hyperledger.besu.ethereum.eth.manager.EthScheduler;
import org.hyperledger.besu.ethereum.eth.manager.RespondingEthPeer; import org.hyperledger.besu.ethereum.eth.manager.RespondingEthPeer;
@@ -94,12 +95,14 @@ public class WorldStateDownloaderBenchmark {
tempDir = Files.createTempDir().toPath(); tempDir = Files.createTempDir().toPath();
ethProtocolManager = ethProtocolManager =
EthProtocolManagerTestUtil.create( EthProtocolManagerTestBuilder.builder()
new EthScheduler( .setEthScheduler(
syncConfig.getDownloaderParallelism(), new EthScheduler(
syncConfig.getTransactionsParallelism(), syncConfig.getDownloaderParallelism(),
syncConfig.getComputationParallelism(), syncConfig.getTransactionsParallelism(),
metricsSystem)); syncConfig.getComputationParallelism(),
metricsSystem))
.build();
peer = EthProtocolManagerTestUtil.createPeer(ethProtocolManager, blockHeader.getNumber()); peer = EthProtocolManagerTestUtil.createPeer(ethProtocolManager, blockHeader.getNumber());

View File

@@ -58,7 +58,7 @@ public class EthPeersTest {
@BeforeEach @BeforeEach
public void setup() throws Exception { public void setup() throws Exception {
when(peerRequest.sendRequest(any())).thenReturn(responseStream); when(peerRequest.sendRequest(any())).thenReturn(responseStream);
ethProtocolManager = EthProtocolManagerTestUtil.create(); ethProtocolManager = EthProtocolManagerTestBuilder.builder().build();
ethPeers = ethProtocolManager.ethContext().getEthPeers(); ethPeers = ethProtocolManager.ethContext().getEthPeers();
final ChainHeadTracker mock = mock(ChainHeadTracker.class); final ChainHeadTracker mock = mock(ChainHeadTracker.class);
final BlockHeader blockHeader = mock(BlockHeader.class); final BlockHeader blockHeader = mock(BlockHeader.class);

View File

@@ -77,6 +77,7 @@ import org.hyperledger.besu.ethereum.worldstate.WorldStateArchive;
import org.hyperledger.besu.metrics.noop.NoOpMetricsSystem; import org.hyperledger.besu.metrics.noop.NoOpMetricsSystem;
import org.hyperledger.besu.plugin.services.MetricsSystem; import org.hyperledger.besu.plugin.services.MetricsSystem;
import org.hyperledger.besu.plugin.services.storage.DataStorageFormat; import org.hyperledger.besu.plugin.services.storage.DataStorageFormat;
import org.hyperledger.besu.testutil.DeterministicEthScheduler;
import org.hyperledger.besu.testutil.TestClock; import org.hyperledger.besu.testutil.TestClock;
import java.math.BigInteger; import java.math.BigInteger;
@@ -132,13 +133,14 @@ public final class EthProtocolManagerTest {
@Test @Test
public void handleMalformedRequestIdMessage() { public void handleMalformedRequestIdMessage() {
try (final EthProtocolManager ethManager = try (final EthProtocolManager ethManager =
EthProtocolManagerTestUtil.create( EthProtocolManagerTestBuilder.builder()
protocolSchedule, .setProtocolSchedule(protocolSchedule)
blockchain, .setBlockchain(blockchain)
() -> false, .setEthScheduler(new DeterministicEthScheduler(() -> false))
protocolContext.getWorldStateArchive(), .setWorldStateArchive(protocolContext.getWorldStateArchive())
transactionPool, .setTransactionPool(transactionPool)
EthProtocolConfiguration.defaultConfig())) { .setEthereumWireProtocolConfiguration(EthProtocolConfiguration.defaultConfig())
.build()) {
// this is a non-request id message, but we'll be processing it with eth66, make sure we // this is a non-request id message, but we'll be processing it with eth66, make sure we
// disconnect the peer gracefully // disconnect the peer gracefully
final MessageData messageData = GetBlockHeadersMessage.create(1, 1, 0, false); final MessageData messageData = GetBlockHeadersMessage.create(1, 1, 0, false);
@@ -151,13 +153,14 @@ public final class EthProtocolManagerTest {
@Test @Test
public void disconnectOnUnsolicitedMessage() { public void disconnectOnUnsolicitedMessage() {
try (final EthProtocolManager ethManager = try (final EthProtocolManager ethManager =
EthProtocolManagerTestUtil.create( EthProtocolManagerTestBuilder.builder()
protocolSchedule, .setProtocolSchedule(protocolSchedule)
blockchain, .setBlockchain(blockchain)
() -> false, .setEthScheduler(new DeterministicEthScheduler(() -> false))
protocolContext.getWorldStateArchive(), .setWorldStateArchive(protocolContext.getWorldStateArchive())
transactionPool, .setTransactionPool(transactionPool)
EthProtocolConfiguration.defaultConfig())) { .setEthereumWireProtocolConfiguration(EthProtocolConfiguration.defaultConfig())
.build()) {
final MessageData messageData = final MessageData messageData =
BlockHeadersMessage.create(Collections.singletonList(blockchain.getBlockHeader(1).get())); BlockHeadersMessage.create(Collections.singletonList(blockchain.getBlockHeader(1).get()));
final MockPeerConnection peer = setupPeer(ethManager, (cap, msg, conn) -> {}); final MockPeerConnection peer = setupPeer(ethManager, (cap, msg, conn) -> {});
@@ -169,13 +172,14 @@ public final class EthProtocolManagerTest {
@Test @Test
public void disconnectOnFailureToSendStatusMessage() { public void disconnectOnFailureToSendStatusMessage() {
try (final EthProtocolManager ethManager = try (final EthProtocolManager ethManager =
EthProtocolManagerTestUtil.create( EthProtocolManagerTestBuilder.builder()
protocolSchedule, .setProtocolSchedule(protocolSchedule)
blockchain, .setBlockchain(blockchain)
() -> false, .setEthScheduler(new DeterministicEthScheduler(() -> false))
protocolContext.getWorldStateArchive(), .setWorldStateArchive(protocolContext.getWorldStateArchive())
transactionPool, .setTransactionPool(transactionPool)
EthProtocolConfiguration.defaultConfig())) { .setEthereumWireProtocolConfiguration(EthProtocolConfiguration.defaultConfig())
.build()) {
final MessageData messageData = final MessageData messageData =
BlockHeadersMessage.create(Collections.singletonList(blockchain.getBlockHeader(1).get())); BlockHeadersMessage.create(Collections.singletonList(blockchain.getBlockHeader(1).get()));
final MockPeerConnection peer = final MockPeerConnection peer =
@@ -188,13 +192,14 @@ public final class EthProtocolManagerTest {
@Test @Test
public void disconnectOnWrongChainId() { public void disconnectOnWrongChainId() {
try (final EthProtocolManager ethManager = try (final EthProtocolManager ethManager =
EthProtocolManagerTestUtil.create( EthProtocolManagerTestBuilder.builder()
protocolSchedule, .setProtocolSchedule(protocolSchedule)
blockchain, .setBlockchain(blockchain)
() -> false, .setEthScheduler(new DeterministicEthScheduler(() -> false))
protocolContext.getWorldStateArchive(), .setWorldStateArchive(protocolContext.getWorldStateArchive())
transactionPool, .setTransactionPool(transactionPool)
EthProtocolConfiguration.defaultConfig())) { .setEthereumWireProtocolConfiguration(EthProtocolConfiguration.defaultConfig())
.build()) {
final MessageData messageData = final MessageData messageData =
BlockHeadersMessage.create(Collections.singletonList(blockchain.getBlockHeader(1).get())); BlockHeadersMessage.create(Collections.singletonList(blockchain.getBlockHeader(1).get()));
final MockPeerConnection peer = final MockPeerConnection peer =
@@ -219,13 +224,14 @@ public final class EthProtocolManagerTest {
public void disconnectNewPoWPeers() { public void disconnectNewPoWPeers() {
final MergePeerFilter mergePeerFilter = new MergePeerFilter(); final MergePeerFilter mergePeerFilter = new MergePeerFilter();
try (final EthProtocolManager ethManager = try (final EthProtocolManager ethManager =
EthProtocolManagerTestUtil.create( EthProtocolManagerTestBuilder.builder()
protocolSchedule, .setProtocolSchedule(protocolSchedule)
blockchain, .setBlockchain(blockchain)
protocolContext.getWorldStateArchive(), .setWorldStateArchive(protocolContext.getWorldStateArchive())
transactionPool, .setTransactionPool(transactionPool)
EthProtocolConfiguration.defaultConfig(), .setEthereumWireProtocolConfiguration(EthProtocolConfiguration.defaultConfig())
Optional.of(mergePeerFilter))) { .setMergePeerFilter(Optional.of(mergePeerFilter))
.build()) {
final MockPeerConnection workPeer = setupPeer(ethManager, (cap, msg, conn) -> {}); final MockPeerConnection workPeer = setupPeer(ethManager, (cap, msg, conn) -> {});
final MockPeerConnection stakePeer = setupPeer(ethManager, (cap, msg, conn) -> {}); final MockPeerConnection stakePeer = setupPeer(ethManager, (cap, msg, conn) -> {});
@@ -267,13 +273,14 @@ public final class EthProtocolManagerTest {
@Test @Test
public void doNotDisconnectOnLargeMessageWithinLimits() { public void doNotDisconnectOnLargeMessageWithinLimits() {
try (final EthProtocolManager ethManager = try (final EthProtocolManager ethManager =
EthProtocolManagerTestUtil.create( EthProtocolManagerTestBuilder.builder()
protocolSchedule, .setProtocolSchedule(protocolSchedule)
blockchain, .setBlockchain(blockchain)
() -> false, .setEthScheduler(new DeterministicEthScheduler(() -> false))
protocolContext.getWorldStateArchive(), .setWorldStateArchive(protocolContext.getWorldStateArchive())
transactionPool, .setTransactionPool(transactionPool)
EthProtocolConfiguration.defaultConfig())) { .setEthereumWireProtocolConfiguration(EthProtocolConfiguration.defaultConfig())
.build()) {
final MessageData messageData = mock(MessageData.class); final MessageData messageData = mock(MessageData.class);
when(messageData.getSize()).thenReturn(EthProtocolConfiguration.DEFAULT_MAX_MESSAGE_SIZE); when(messageData.getSize()).thenReturn(EthProtocolConfiguration.DEFAULT_MAX_MESSAGE_SIZE);
when(messageData.getCode()).thenReturn(EthPV62.TRANSACTIONS); when(messageData.getCode()).thenReturn(EthPV62.TRANSACTIONS);
@@ -287,13 +294,14 @@ public final class EthProtocolManagerTest {
@Test @Test
public void disconnectOnWrongGenesisHash() { public void disconnectOnWrongGenesisHash() {
try (final EthProtocolManager ethManager = try (final EthProtocolManager ethManager =
EthProtocolManagerTestUtil.create( EthProtocolManagerTestBuilder.builder()
protocolSchedule, .setProtocolSchedule(protocolSchedule)
blockchain, .setBlockchain(blockchain)
() -> false, .setEthScheduler(new DeterministicEthScheduler(() -> false))
protocolContext.getWorldStateArchive(), .setWorldStateArchive(protocolContext.getWorldStateArchive())
transactionPool, .setTransactionPool(transactionPool)
EthProtocolConfiguration.defaultConfig())) { .setEthereumWireProtocolConfiguration(EthProtocolConfiguration.defaultConfig())
.build()) {
final MessageData messageData = final MessageData messageData =
BlockHeadersMessage.create(Collections.singletonList(blockchain.getBlockHeader(1).get())); BlockHeadersMessage.create(Collections.singletonList(blockchain.getBlockHeader(1).get()));
final MockPeerConnection peer = final MockPeerConnection peer =
@@ -317,13 +325,14 @@ public final class EthProtocolManagerTest {
@Test @Test
public void doNotDisconnectOnValidMessage() { public void doNotDisconnectOnValidMessage() {
try (final EthProtocolManager ethManager = try (final EthProtocolManager ethManager =
EthProtocolManagerTestUtil.create( EthProtocolManagerTestBuilder.builder()
protocolSchedule, .setProtocolSchedule(protocolSchedule)
blockchain, .setBlockchain(blockchain)
() -> false, .setEthScheduler(new DeterministicEthScheduler(() -> false))
protocolContext.getWorldStateArchive(), .setWorldStateArchive(protocolContext.getWorldStateArchive())
transactionPool, .setTransactionPool(transactionPool)
EthProtocolConfiguration.defaultConfig())) { .setEthereumWireProtocolConfiguration(EthProtocolConfiguration.defaultConfig())
.build()) {
final MessageData messageData = final MessageData messageData =
GetBlockBodiesMessage.create(Collections.singletonList(gen.hash())); GetBlockBodiesMessage.create(Collections.singletonList(gen.hash()));
final MockPeerConnection peer = setupPeer(ethManager, (cap, msg, conn) -> {}); final MockPeerConnection peer = setupPeer(ethManager, (cap, msg, conn) -> {});
@@ -339,13 +348,14 @@ public final class EthProtocolManagerTest {
public void respondToGetHeaders() throws ExecutionException, InterruptedException { public void respondToGetHeaders() throws ExecutionException, InterruptedException {
final CompletableFuture<Void> done = new CompletableFuture<>(); final CompletableFuture<Void> done = new CompletableFuture<>();
try (final EthProtocolManager ethManager = try (final EthProtocolManager ethManager =
EthProtocolManagerTestUtil.create( EthProtocolManagerTestBuilder.builder()
protocolSchedule, .setProtocolSchedule(protocolSchedule)
blockchain, .setBlockchain(blockchain)
() -> false, .setEthScheduler(new DeterministicEthScheduler(() -> false))
protocolContext.getWorldStateArchive(), .setWorldStateArchive(protocolContext.getWorldStateArchive())
transactionPool, .setTransactionPool(transactionPool)
EthProtocolConfiguration.defaultConfig())) { .setEthereumWireProtocolConfiguration(EthProtocolConfiguration.defaultConfig())
.build()) {
final long startBlock = 5L; final long startBlock = 5L;
final int blockCount = 5; final int blockCount = 5;
final MessageData messageData = final MessageData messageData =
@@ -379,13 +389,14 @@ public final class EthProtocolManagerTest {
final EthProtocolConfiguration config = final EthProtocolConfiguration config =
EthProtocolConfiguration.builder().maxGetBlockHeaders(limit).build(); EthProtocolConfiguration.builder().maxGetBlockHeaders(limit).build();
try (final EthProtocolManager ethManager = try (final EthProtocolManager ethManager =
EthProtocolManagerTestUtil.create( EthProtocolManagerTestBuilder.builder()
protocolSchedule, .setProtocolSchedule(protocolSchedule)
blockchain, .setBlockchain(blockchain)
() -> false, .setEthScheduler(new DeterministicEthScheduler(() -> false))
protocolContext.getWorldStateArchive(), .setWorldStateArchive(protocolContext.getWorldStateArchive())
transactionPool, .setTransactionPool(transactionPool)
config)) { .setEthereumWireProtocolConfiguration(config)
.build()) {
final long startBlock = 5L; final long startBlock = 5L;
final int blockCount = 10; final int blockCount = 10;
final MessageData messageData = final MessageData messageData =
@@ -416,13 +427,14 @@ public final class EthProtocolManagerTest {
public void respondToGetHeadersReversed() throws ExecutionException, InterruptedException { public void respondToGetHeadersReversed() throws ExecutionException, InterruptedException {
final CompletableFuture<Void> done = new CompletableFuture<>(); final CompletableFuture<Void> done = new CompletableFuture<>();
try (final EthProtocolManager ethManager = try (final EthProtocolManager ethManager =
EthProtocolManagerTestUtil.create( EthProtocolManagerTestBuilder.builder()
protocolSchedule, .setProtocolSchedule(protocolSchedule)
blockchain, .setBlockchain(blockchain)
() -> false, .setEthScheduler(new DeterministicEthScheduler(() -> false))
protocolContext.getWorldStateArchive(), .setWorldStateArchive(protocolContext.getWorldStateArchive())
transactionPool, .setTransactionPool(transactionPool)
EthProtocolConfiguration.defaultConfig())) { .setEthereumWireProtocolConfiguration(EthProtocolConfiguration.defaultConfig())
.build()) {
final long endBlock = 10L; final long endBlock = 10L;
final int blockCount = 5; final int blockCount = 5;
@@ -453,13 +465,14 @@ public final class EthProtocolManagerTest {
public void respondToGetHeadersWithSkip() throws ExecutionException, InterruptedException { public void respondToGetHeadersWithSkip() throws ExecutionException, InterruptedException {
final CompletableFuture<Void> done = new CompletableFuture<>(); final CompletableFuture<Void> done = new CompletableFuture<>();
try (final EthProtocolManager ethManager = try (final EthProtocolManager ethManager =
EthProtocolManagerTestUtil.create( EthProtocolManagerTestBuilder.builder()
protocolSchedule, .setProtocolSchedule(protocolSchedule)
blockchain, .setBlockchain(blockchain)
() -> false, .setEthScheduler(new DeterministicEthScheduler(() -> false))
protocolContext.getWorldStateArchive(), .setWorldStateArchive(protocolContext.getWorldStateArchive())
transactionPool, .setTransactionPool(transactionPool)
EthProtocolConfiguration.defaultConfig())) { .setEthereumWireProtocolConfiguration(EthProtocolConfiguration.defaultConfig())
.build()) {
final long startBlock = 5L; final long startBlock = 5L;
final int blockCount = 5; final int blockCount = 5;
@@ -493,13 +506,14 @@ public final class EthProtocolManagerTest {
throws ExecutionException, InterruptedException { throws ExecutionException, InterruptedException {
final CompletableFuture<Void> done = new CompletableFuture<>(); final CompletableFuture<Void> done = new CompletableFuture<>();
try (final EthProtocolManager ethManager = try (final EthProtocolManager ethManager =
EthProtocolManagerTestUtil.create( EthProtocolManagerTestBuilder.builder()
protocolSchedule, .setProtocolSchedule(protocolSchedule)
blockchain, .setBlockchain(blockchain)
() -> false, .setEthScheduler(new DeterministicEthScheduler(() -> false))
protocolContext.getWorldStateArchive(), .setWorldStateArchive(protocolContext.getWorldStateArchive())
transactionPool, .setTransactionPool(transactionPool)
EthProtocolConfiguration.defaultConfig())) { .setEthereumWireProtocolConfiguration(EthProtocolConfiguration.defaultConfig())
.build()) {
final long endBlock = 10L; final long endBlock = 10L;
final int blockCount = 5; final int blockCount = 5;
@@ -557,13 +571,14 @@ public final class EthProtocolManagerTest {
public void respondToGetHeadersPartial() throws ExecutionException, InterruptedException { public void respondToGetHeadersPartial() throws ExecutionException, InterruptedException {
final CompletableFuture<Void> done = new CompletableFuture<>(); final CompletableFuture<Void> done = new CompletableFuture<>();
try (final EthProtocolManager ethManager = try (final EthProtocolManager ethManager =
EthProtocolManagerTestUtil.create( EthProtocolManagerTestBuilder.builder()
protocolSchedule, .setProtocolSchedule(protocolSchedule)
blockchain, .setBlockchain(blockchain)
() -> false, .setEthScheduler(new DeterministicEthScheduler(() -> false))
protocolContext.getWorldStateArchive(), .setWorldStateArchive(protocolContext.getWorldStateArchive())
transactionPool, .setTransactionPool(transactionPool)
EthProtocolConfiguration.defaultConfig())) { .setEthereumWireProtocolConfiguration(EthProtocolConfiguration.defaultConfig())
.build()) {
final long startBlock = blockchain.getChainHeadBlockNumber() - 1L; final long startBlock = blockchain.getChainHeadBlockNumber() - 1L;
final int blockCount = 5; final int blockCount = 5;
@@ -595,13 +610,14 @@ public final class EthProtocolManagerTest {
public void respondToGetHeadersEmpty() throws ExecutionException, InterruptedException { public void respondToGetHeadersEmpty() throws ExecutionException, InterruptedException {
final CompletableFuture<Void> done = new CompletableFuture<>(); final CompletableFuture<Void> done = new CompletableFuture<>();
try (final EthProtocolManager ethManager = try (final EthProtocolManager ethManager =
EthProtocolManagerTestUtil.create( EthProtocolManagerTestBuilder.builder()
protocolSchedule, .setProtocolSchedule(protocolSchedule)
blockchain, .setBlockchain(blockchain)
() -> false, .setEthScheduler(new DeterministicEthScheduler(() -> false))
protocolContext.getWorldStateArchive(), .setWorldStateArchive(protocolContext.getWorldStateArchive())
transactionPool, .setTransactionPool(transactionPool)
EthProtocolConfiguration.defaultConfig())) { .setEthereumWireProtocolConfiguration(EthProtocolConfiguration.defaultConfig())
.build()) {
final long startBlock = blockchain.getChainHeadBlockNumber() + 1; final long startBlock = blockchain.getChainHeadBlockNumber() + 1;
final int blockCount = 5; final int blockCount = 5;
@@ -630,13 +646,14 @@ public final class EthProtocolManagerTest {
public void respondToGetBodies() throws ExecutionException, InterruptedException { public void respondToGetBodies() throws ExecutionException, InterruptedException {
final CompletableFuture<Void> done = new CompletableFuture<>(); final CompletableFuture<Void> done = new CompletableFuture<>();
try (final EthProtocolManager ethManager = try (final EthProtocolManager ethManager =
EthProtocolManagerTestUtil.create( EthProtocolManagerTestBuilder.builder()
protocolSchedule, .setProtocolSchedule(protocolSchedule)
blockchain, .setBlockchain(blockchain)
() -> false, .setEthScheduler(new DeterministicEthScheduler(() -> false))
protocolContext.getWorldStateArchive(), .setWorldStateArchive(protocolContext.getWorldStateArchive())
transactionPool, .setTransactionPool(transactionPool)
EthProtocolConfiguration.defaultConfig())) { .setEthereumWireProtocolConfiguration(EthProtocolConfiguration.defaultConfig())
.build()) {
// Setup blocks query // Setup blocks query
final long startBlock = blockchain.getChainHeadBlockNumber() - 5; final long startBlock = blockchain.getChainHeadBlockNumber() - 5;
@@ -683,13 +700,14 @@ public final class EthProtocolManagerTest {
final EthProtocolConfiguration config = final EthProtocolConfiguration config =
EthProtocolConfiguration.builder().maxGetBlockBodies(limit).build(); EthProtocolConfiguration.builder().maxGetBlockBodies(limit).build();
try (final EthProtocolManager ethManager = try (final EthProtocolManager ethManager =
EthProtocolManagerTestUtil.create( EthProtocolManagerTestBuilder.builder()
protocolSchedule, .setProtocolSchedule(protocolSchedule)
blockchain, .setBlockchain(blockchain)
() -> false, .setEthScheduler(new DeterministicEthScheduler(() -> false))
protocolContext.getWorldStateArchive(), .setWorldStateArchive(protocolContext.getWorldStateArchive())
transactionPool, .setTransactionPool(transactionPool)
config)) { .setEthereumWireProtocolConfiguration(config)
.build()) {
// Setup blocks query // Setup blocks query
final int blockCount = 10; final int blockCount = 10;
final long startBlock = blockchain.getChainHeadBlockNumber() - blockCount; final long startBlock = blockchain.getChainHeadBlockNumber() - blockCount;
@@ -732,13 +750,14 @@ public final class EthProtocolManagerTest {
public void respondToGetBodiesPartial() throws ExecutionException, InterruptedException { public void respondToGetBodiesPartial() throws ExecutionException, InterruptedException {
final CompletableFuture<Void> done = new CompletableFuture<>(); final CompletableFuture<Void> done = new CompletableFuture<>();
try (final EthProtocolManager ethManager = try (final EthProtocolManager ethManager =
EthProtocolManagerTestUtil.create( EthProtocolManagerTestBuilder.builder()
protocolSchedule, .setProtocolSchedule(protocolSchedule)
blockchain, .setBlockchain(blockchain)
() -> false, .setEthScheduler(new DeterministicEthScheduler(() -> false))
protocolContext.getWorldStateArchive(), .setWorldStateArchive(protocolContext.getWorldStateArchive())
transactionPool, .setTransactionPool(transactionPool)
EthProtocolConfiguration.defaultConfig())) { .setEthereumWireProtocolConfiguration(EthProtocolConfiguration.defaultConfig())
.build()) {
// Setup blocks query // Setup blocks query
final long expectedBlockNumber = blockchain.getChainHeadBlockNumber() - 1; final long expectedBlockNumber = blockchain.getChainHeadBlockNumber() - 1;
final BlockHeader header = blockchain.getBlockHeader(expectedBlockNumber).get(); final BlockHeader header = blockchain.getBlockHeader(expectedBlockNumber).get();
@@ -775,13 +794,14 @@ public final class EthProtocolManagerTest {
public void respondToGetReceipts() throws ExecutionException, InterruptedException { public void respondToGetReceipts() throws ExecutionException, InterruptedException {
final CompletableFuture<Void> done = new CompletableFuture<>(); final CompletableFuture<Void> done = new CompletableFuture<>();
try (final EthProtocolManager ethManager = try (final EthProtocolManager ethManager =
EthProtocolManagerTestUtil.create( EthProtocolManagerTestBuilder.builder()
protocolSchedule, .setProtocolSchedule(protocolSchedule)
blockchain, .setBlockchain(blockchain)
() -> false, .setEthScheduler(new DeterministicEthScheduler(() -> false))
protocolContext.getWorldStateArchive(), .setWorldStateArchive(protocolContext.getWorldStateArchive())
transactionPool, .setTransactionPool(transactionPool)
EthProtocolConfiguration.defaultConfig())) { .setEthereumWireProtocolConfiguration(EthProtocolConfiguration.defaultConfig())
.build()) {
// Setup blocks query // Setup blocks query
final long startBlock = blockchain.getChainHeadBlockNumber() - 5; final long startBlock = blockchain.getChainHeadBlockNumber() - 5;
final int blockCount = 2; final int blockCount = 2;
@@ -826,13 +846,14 @@ public final class EthProtocolManagerTest {
final EthProtocolConfiguration config = final EthProtocolConfiguration config =
EthProtocolConfiguration.builder().maxGetReceipts(limit).build(); EthProtocolConfiguration.builder().maxGetReceipts(limit).build();
try (final EthProtocolManager ethManager = try (final EthProtocolManager ethManager =
EthProtocolManagerTestUtil.create( EthProtocolManagerTestBuilder.builder()
protocolSchedule, .setProtocolSchedule(protocolSchedule)
blockchain, .setBlockchain(blockchain)
() -> false, .setEthScheduler(new DeterministicEthScheduler(() -> false))
protocolContext.getWorldStateArchive(), .setWorldStateArchive(protocolContext.getWorldStateArchive())
transactionPool, .setTransactionPool(transactionPool)
config)) { .setEthereumWireProtocolConfiguration(config)
.build()) {
// Setup blocks query // Setup blocks query
final int blockCount = 10; final int blockCount = 10;
final long startBlock = blockchain.getChainHeadBlockNumber() - blockCount; final long startBlock = blockchain.getChainHeadBlockNumber() - blockCount;
@@ -874,13 +895,14 @@ public final class EthProtocolManagerTest {
public void respondToGetReceiptsPartial() throws ExecutionException, InterruptedException { public void respondToGetReceiptsPartial() throws ExecutionException, InterruptedException {
final CompletableFuture<Void> done = new CompletableFuture<>(); final CompletableFuture<Void> done = new CompletableFuture<>();
try (final EthProtocolManager ethManager = try (final EthProtocolManager ethManager =
EthProtocolManagerTestUtil.create( EthProtocolManagerTestBuilder.builder()
protocolSchedule, .setProtocolSchedule(protocolSchedule)
blockchain, .setBlockchain(blockchain)
() -> false, .setEthScheduler(new DeterministicEthScheduler(() -> false))
protocolContext.getWorldStateArchive(), .setWorldStateArchive(protocolContext.getWorldStateArchive())
transactionPool, .setTransactionPool(transactionPool)
EthProtocolConfiguration.defaultConfig())) { .setEthereumWireProtocolConfiguration(EthProtocolConfiguration.defaultConfig())
.build()) {
// Setup blocks query // Setup blocks query
final long blockNumber = blockchain.getChainHeadBlockNumber() - 5; final long blockNumber = blockchain.getChainHeadBlockNumber() - 5;
final BlockHeader header = blockchain.getBlockHeader(blockNumber).get(); final BlockHeader header = blockchain.getBlockHeader(blockNumber).get();
@@ -919,13 +941,14 @@ public final class EthProtocolManagerTest {
final WorldStateArchive worldStateArchive = protocolContext.getWorldStateArchive(); final WorldStateArchive worldStateArchive = protocolContext.getWorldStateArchive();
try (final EthProtocolManager ethManager = try (final EthProtocolManager ethManager =
EthProtocolManagerTestUtil.create( EthProtocolManagerTestBuilder.builder()
protocolSchedule, .setProtocolSchedule(protocolSchedule)
blockchain, .setBlockchain(blockchain)
() -> false, .setEthScheduler(new DeterministicEthScheduler(() -> false))
protocolContext.getWorldStateArchive(), .setWorldStateArchive(protocolContext.getWorldStateArchive())
transactionPool, .setTransactionPool(transactionPool)
EthProtocolConfiguration.defaultConfig())) { .setEthereumWireProtocolConfiguration(EthProtocolConfiguration.defaultConfig())
.build()) {
// Setup node data query // Setup node data query
final List<Bytes> expectedResults = new ArrayList<>(); final List<Bytes> expectedResults = new ArrayList<>();
@@ -967,13 +990,14 @@ public final class EthProtocolManagerTest {
@Test @Test
public void newBlockMinedSendsNewBlockMessageToAllPeers() { public void newBlockMinedSendsNewBlockMessageToAllPeers() {
try (final EthProtocolManager ethManager = try (final EthProtocolManager ethManager =
EthProtocolManagerTestUtil.create( EthProtocolManagerTestBuilder.builder()
protocolSchedule, .setProtocolSchedule(protocolSchedule)
blockchain, .setBlockchain(blockchain)
() -> false, .setEthScheduler(new DeterministicEthScheduler(() -> false))
protocolContext.getWorldStateArchive(), .setWorldStateArchive(protocolContext.getWorldStateArchive())
transactionPool, .setTransactionPool(transactionPool)
EthProtocolConfiguration.defaultConfig())) { .setEthereumWireProtocolConfiguration(EthProtocolConfiguration.defaultConfig())
.build()) {
// Define handler to validate response // Define handler to validate response
final PeerSendHandler onSend = mock(PeerSendHandler.class); final PeerSendHandler onSend = mock(PeerSendHandler.class);
final List<PeerConnection> peers = Lists.newArrayList(); final List<PeerConnection> peers = Lists.newArrayList();
@@ -1038,13 +1062,14 @@ public final class EthProtocolManagerTest {
final CompletableFuture<Void> done = new CompletableFuture<>(); final CompletableFuture<Void> done = new CompletableFuture<>();
try (final EthProtocolManager ethManager = try (final EthProtocolManager ethManager =
EthProtocolManagerTestUtil.create( EthProtocolManagerTestBuilder.builder()
protocolSchedule, .setProtocolSchedule(protocolSchedule)
blockchain, .setBlockchain(blockchain)
() -> false, .setEthScheduler(new DeterministicEthScheduler(() -> false))
protocolContext.getWorldStateArchive(), .setWorldStateArchive(protocolContext.getWorldStateArchive())
transactionPool, .setTransactionPool(transactionPool)
EthProtocolConfiguration.defaultConfig())) { .setEthereumWireProtocolConfiguration(EthProtocolConfiguration.defaultConfig())
.build()) {
final long startBlock = 1L; final long startBlock = 1L;
final int requestedBlockCount = 13; final int requestedBlockCount = 13;
@@ -1105,13 +1130,14 @@ public final class EthProtocolManagerTest {
final TransactionsMessage transactionMessage = TransactionsMessage.readFrom(raw); final TransactionsMessage transactionMessage = TransactionsMessage.readFrom(raw);
try (final EthProtocolManager ethManager = try (final EthProtocolManager ethManager =
EthProtocolManagerTestUtil.create( EthProtocolManagerTestBuilder.builder()
protocolSchedule, .setProtocolSchedule(protocolSchedule)
blockchain, .setBlockchain(blockchain)
ethScheduler, .setEthScheduler(ethScheduler)
protocolContext.getWorldStateArchive(), .setWorldStateArchive(protocolContext.getWorldStateArchive())
transactionPool, .setTransactionPool(transactionPool)
EthProtocolConfiguration.defaultConfig())) { .setEthereumWireProtocolConfiguration(EthProtocolConfiguration.defaultConfig())
.build()) {
// Create a transaction pool. This has a side effect of registering a listener for the // Create a transaction pool. This has a side effect of registering a listener for the
// transactions message. // transactions message.
TransactionPoolFactory.createTransactionPool( TransactionPoolFactory.createTransactionPool(
@@ -1141,15 +1167,17 @@ public final class EthProtocolManagerTest {
public void forkIdForChainHeadLegacyNoForksNotEmpty() { public void forkIdForChainHeadLegacyNoForksNotEmpty() {
final EthScheduler ethScheduler = mock(EthScheduler.class); final EthScheduler ethScheduler = mock(EthScheduler.class);
try (final EthProtocolManager ethManager = try (final EthProtocolManager ethManager =
EthProtocolManagerTestUtil.create( EthProtocolManagerTestBuilder.builder()
protocolSchedule, .setProtocolSchedule(protocolSchedule)
blockchain, .setBlockchain(blockchain)
ethScheduler, .setEthScheduler(ethScheduler)
protocolContext.getWorldStateArchive(), .setWorldStateArchive(protocolContext.getWorldStateArchive())
transactionPool, .setTransactionPool(transactionPool)
EthProtocolConfiguration.defaultConfig(), .setEthereumWireProtocolConfiguration(EthProtocolConfiguration.defaultConfig())
new ForkIdManager( .setForkIdManager(
blockchain, Collections.emptyList(), Collections.emptyList(), true))) { new ForkIdManager(
blockchain, Collections.emptyList(), Collections.emptyList(), true))
.build()) {
assertThat(ethManager.getForkIdAsBytesList()).isNotEmpty(); assertThat(ethManager.getForkIdAsBytesList()).isNotEmpty();
final CRC32 genesisHashCRC = new CRC32(); final CRC32 genesisHashCRC = new CRC32();

View File

@@ -0,0 +1,245 @@
/*
* Copyright contributors to Besu.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
* an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
* specific language governing permissions and limitations under the License.
*
* SPDX-License-Identifier: Apache-2.0
*/
package org.hyperledger.besu.ethereum.eth.manager;
import static org.hyperledger.besu.ethereum.core.InMemoryKeyValueStorageProvider.createInMemoryBlockchain;
import static org.mockito.Mockito.mock;
import org.hyperledger.besu.config.GenesisConfigFile;
import org.hyperledger.besu.ethereum.chain.Blockchain;
import org.hyperledger.besu.ethereum.chain.GenesisState;
import org.hyperledger.besu.ethereum.core.BlockchainSetupUtil;
import org.hyperledger.besu.ethereum.core.ProtocolScheduleFixture;
import org.hyperledger.besu.ethereum.eth.EthProtocolConfiguration;
import org.hyperledger.besu.ethereum.eth.peervalidation.PeerValidator;
import org.hyperledger.besu.ethereum.eth.sync.SyncMode;
import org.hyperledger.besu.ethereum.eth.sync.SynchronizerConfiguration;
import org.hyperledger.besu.ethereum.eth.transactions.TransactionPool;
import org.hyperledger.besu.ethereum.forkid.ForkIdManager;
import org.hyperledger.besu.ethereum.mainnet.ProtocolSchedule;
import org.hyperledger.besu.ethereum.worldstate.WorldStateArchive;
import org.hyperledger.besu.metrics.noop.NoOpMetricsSystem;
import org.hyperledger.besu.plugin.services.storage.DataStorageFormat;
import org.hyperledger.besu.testutil.DeterministicEthScheduler;
import org.hyperledger.besu.testutil.TestClock;
import java.math.BigInteger;
import java.util.Collections;
import java.util.List;
import java.util.Optional;
import org.apache.tuweni.bytes.Bytes;
public class EthProtocolManagerTestBuilder {
private static final BigInteger DEFAULT_NETWORK_ID = BigInteger.ONE;
private static final ProtocolSchedule DEFAULT_PROTOCOL_SCHEDULE = ProtocolScheduleFixture.MAINNET;
private ProtocolSchedule protocolSchedule;
private GenesisConfigFile genesisConfigFile;
private GenesisState genesisState;
private Blockchain blockchain;
private BigInteger networkId;
private WorldStateArchive worldStateArchive;
private TransactionPool transactionPool;
private EthProtocolConfiguration ethereumWireProtocolConfiguration;
private ForkIdManager forkIdManager;
private EthPeers ethPeers;
private EthMessages ethMessages;
private EthMessages snapMessages;
private EthScheduler ethScheduler;
private EthContext ethContext;
private List<PeerValidator> peerValidators;
private Optional<MergePeerFilter> mergePeerFilter;
private SynchronizerConfiguration synchronizerConfiguration;
public static EthProtocolManagerTestBuilder builder() {
return new EthProtocolManagerTestBuilder();
}
public EthProtocolManagerTestBuilder setProtocolSchedule(
final ProtocolSchedule protocolSchedule) {
this.protocolSchedule = protocolSchedule;
return this;
}
public EthProtocolManagerTestBuilder setGenesisConfigFile(
final GenesisConfigFile genesisConfigFile) {
this.genesisConfigFile = genesisConfigFile;
return this;
}
public EthProtocolManagerTestBuilder setGenesisState(final GenesisState genesisState) {
this.genesisState = genesisState;
return this;
}
public EthProtocolManagerTestBuilder setBlockchain(final Blockchain blockchain) {
this.blockchain = blockchain;
return this;
}
public EthProtocolManagerTestBuilder setNetworkId(final BigInteger networkId) {
this.networkId = networkId;
return this;
}
public EthProtocolManagerTestBuilder setWorldStateArchive(
final WorldStateArchive worldStateArchive) {
this.worldStateArchive = worldStateArchive;
return this;
}
public EthProtocolManagerTestBuilder setTransactionPool(final TransactionPool transactionPool) {
this.transactionPool = transactionPool;
return this;
}
public EthProtocolManagerTestBuilder setEthereumWireProtocolConfiguration(
final EthProtocolConfiguration ethereumWireProtocolConfiguration) {
this.ethereumWireProtocolConfiguration = ethereumWireProtocolConfiguration;
return this;
}
public EthProtocolManagerTestBuilder setForkIdManager(final ForkIdManager forkIdManager) {
this.forkIdManager = forkIdManager;
return this;
}
public EthProtocolManagerTestBuilder setEthPeers(final EthPeers ethPeers) {
this.ethPeers = ethPeers;
return this;
}
public EthProtocolManagerTestBuilder setEthMessages(final EthMessages ethMessages) {
this.ethMessages = ethMessages;
return this;
}
public EthProtocolManagerTestBuilder setSnapMessages(final EthMessages snapMessages) {
this.snapMessages = snapMessages;
return this;
}
public EthProtocolManagerTestBuilder setEthContext(final EthContext ethContext) {
this.ethContext = ethContext;
return this;
}
public EthProtocolManagerTestBuilder setPeerValidators(final List<PeerValidator> peerValidators) {
this.peerValidators = peerValidators;
return this;
}
public EthProtocolManagerTestBuilder setMergePeerFilter(
final Optional<MergePeerFilter> mergePeerFilter) {
this.mergePeerFilter = mergePeerFilter;
return this;
}
public EthProtocolManagerTestBuilder setSynchronizerConfiguration(
final SynchronizerConfiguration synchronizerConfiguration) {
this.synchronizerConfiguration = synchronizerConfiguration;
return this;
}
public EthProtocolManagerTestBuilder setEthScheduler(final EthScheduler ethScheduler) {
this.ethScheduler = ethScheduler;
return this;
}
public EthProtocolManager build() {
if (protocolSchedule == null) {
protocolSchedule = DEFAULT_PROTOCOL_SCHEDULE;
}
if (genesisConfigFile == null) {
genesisConfigFile = GenesisConfigFile.mainnet();
}
if (genesisState == null) {
genesisState = GenesisState.fromConfig(genesisConfigFile, protocolSchedule);
}
if (blockchain == null) {
blockchain = createInMemoryBlockchain(genesisState.getBlock());
}
if (networkId == null) {
networkId = DEFAULT_NETWORK_ID;
}
if (worldStateArchive == null) {
worldStateArchive =
BlockchainSetupUtil.forTesting(DataStorageFormat.FOREST).getWorldArchive();
}
if (transactionPool == null) {
transactionPool = mock(TransactionPool.class);
}
if (ethereumWireProtocolConfiguration == null) {
ethereumWireProtocolConfiguration = EthProtocolConfiguration.defaultConfig();
}
if (forkIdManager == null) {
forkIdManager =
new ForkIdManager(blockchain, Collections.emptyList(), Collections.emptyList(), false);
}
if (ethPeers == null) {
ethPeers =
new EthPeers(
() -> protocolSchedule.getByBlockHeader(blockchain.getChainHeadHeader()),
TestClock.fixed(),
new NoOpMetricsSystem(),
EthProtocolConfiguration.DEFAULT_MAX_MESSAGE_SIZE,
Collections.emptyList(),
Bytes.random(64),
25,
25,
false,
SyncMode.FAST,
forkIdManager);
}
ethPeers.setChainHeadTracker(EthProtocolManagerTestUtil.getChainHeadTrackerMock());
if (ethMessages == null) {
ethMessages = new EthMessages();
}
if (snapMessages == null) {
snapMessages = new EthMessages();
}
if (ethScheduler == null) {
ethScheduler =
new DeterministicEthScheduler(DeterministicEthScheduler.TimeoutPolicy.NEVER_TIMEOUT);
}
if (ethContext == null) {
ethContext = new EthContext(ethPeers, ethMessages, snapMessages, ethScheduler);
}
if (peerValidators == null) {
peerValidators = Collections.emptyList();
}
if (mergePeerFilter == null) {
mergePeerFilter = Optional.of(new MergePeerFilter());
}
if (synchronizerConfiguration == null) {
synchronizerConfiguration = SynchronizerConfiguration.builder().build();
}
return new EthProtocolManager(
blockchain,
networkId,
worldStateArchive,
transactionPool,
ethereumWireProtocolConfiguration,
ethPeers,
ethMessages,
ethContext,
peerValidators,
mergePeerFilter,
synchronizerConfiguration,
ethScheduler,
forkIdManager);
}
}

View File

@@ -15,229 +15,29 @@
package org.hyperledger.besu.ethereum.eth.manager; package org.hyperledger.besu.ethereum.eth.manager;
import static com.google.common.base.Preconditions.checkArgument; import static com.google.common.base.Preconditions.checkArgument;
import static org.hyperledger.besu.ethereum.core.InMemoryKeyValueStorageProvider.createInMemoryBlockchain;
import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.mock; import static org.mockito.Mockito.mock;
import org.hyperledger.besu.config.GenesisConfigFile;
import org.hyperledger.besu.datatypes.Hash; import org.hyperledger.besu.datatypes.Hash;
import org.hyperledger.besu.ethereum.chain.Blockchain; import org.hyperledger.besu.ethereum.chain.Blockchain;
import org.hyperledger.besu.ethereum.chain.ChainHead; import org.hyperledger.besu.ethereum.chain.ChainHead;
import org.hyperledger.besu.ethereum.chain.GenesisState;
import org.hyperledger.besu.ethereum.core.BlockHeader; import org.hyperledger.besu.ethereum.core.BlockHeader;
import org.hyperledger.besu.ethereum.core.BlockchainSetupUtil;
import org.hyperledger.besu.ethereum.core.Difficulty; import org.hyperledger.besu.ethereum.core.Difficulty;
import org.hyperledger.besu.ethereum.core.ProtocolScheduleFixture;
import org.hyperledger.besu.ethereum.eth.EthProtocol; import org.hyperledger.besu.ethereum.eth.EthProtocol;
import org.hyperledger.besu.ethereum.eth.EthProtocolConfiguration;
import org.hyperledger.besu.ethereum.eth.manager.snap.SnapProtocolManager; import org.hyperledger.besu.ethereum.eth.manager.snap.SnapProtocolManager;
import org.hyperledger.besu.ethereum.eth.peervalidation.PeerValidator; import org.hyperledger.besu.ethereum.eth.peervalidation.PeerValidator;
import org.hyperledger.besu.ethereum.eth.sync.ChainHeadTracker; import org.hyperledger.besu.ethereum.eth.sync.ChainHeadTracker;
import org.hyperledger.besu.ethereum.eth.sync.SyncMode;
import org.hyperledger.besu.ethereum.eth.sync.SynchronizerConfiguration;
import org.hyperledger.besu.ethereum.eth.transactions.TransactionPool;
import org.hyperledger.besu.ethereum.forkid.ForkIdManager;
import org.hyperledger.besu.ethereum.mainnet.ProtocolSchedule;
import org.hyperledger.besu.ethereum.p2p.rlpx.wire.DefaultMessage; import org.hyperledger.besu.ethereum.p2p.rlpx.wire.DefaultMessage;
import org.hyperledger.besu.ethereum.p2p.rlpx.wire.MessageData; import org.hyperledger.besu.ethereum.p2p.rlpx.wire.MessageData;
import org.hyperledger.besu.ethereum.worldstate.WorldStateArchive;
import org.hyperledger.besu.metrics.noop.NoOpMetricsSystem;
import org.hyperledger.besu.plugin.services.storage.DataStorageFormat;
import org.hyperledger.besu.testutil.DeterministicEthScheduler; import org.hyperledger.besu.testutil.DeterministicEthScheduler;
import org.hyperledger.besu.testutil.DeterministicEthScheduler.TimeoutPolicy;
import org.hyperledger.besu.testutil.TestClock;
import java.math.BigInteger;
import java.util.Collections;
import java.util.Optional;
import java.util.OptionalLong; import java.util.OptionalLong;
import java.util.concurrent.CompletableFuture; import java.util.concurrent.CompletableFuture;
import org.apache.tuweni.bytes.Bytes;
import org.mockito.Mockito; import org.mockito.Mockito;
public class EthProtocolManagerTestUtil { public class EthProtocolManagerTestUtil {
public static EthProtocolManager create(
final ProtocolSchedule protocolSchedule,
final Blockchain blockchain,
final TimeoutPolicy timeoutPolicy,
final WorldStateArchive worldStateArchive,
final TransactionPool transactionPool,
final EthProtocolConfiguration ethereumWireProtocolConfiguration) {
return create(
protocolSchedule,
blockchain,
new DeterministicEthScheduler(timeoutPolicy),
worldStateArchive,
transactionPool,
ethereumWireProtocolConfiguration);
}
public static EthProtocolManager create(
final ProtocolSchedule protocolSchedule,
final Blockchain blockchain,
final WorldStateArchive worldStateArchive,
final TransactionPool transactionPool,
final EthProtocolConfiguration ethereumWireProtocolConfiguration,
final Optional<MergePeerFilter> mergePeerFilter) {
final EthPeers peers =
new EthPeers(
() -> protocolSchedule.getByBlockHeader(blockchain.getChainHeadHeader()),
TestClock.fixed(),
new NoOpMetricsSystem(),
EthProtocolConfiguration.DEFAULT_MAX_MESSAGE_SIZE,
Collections.emptyList(),
Bytes.random(64),
25,
25,
false,
SyncMode.FAST,
new ForkIdManager(blockchain, Collections.emptyList(), Collections.emptyList(), false));
final ChainHeadTracker chainHeadTrackerMock = getChainHeadTrackerMock();
peers.setChainHeadTracker(chainHeadTrackerMock);
final EthMessages messages = new EthMessages();
final EthScheduler ethScheduler = new DeterministicEthScheduler(TimeoutPolicy.NEVER_TIMEOUT);
final EthContext ethContext = new EthContext(peers, messages, ethScheduler);
return new EthProtocolManager(
blockchain,
BigInteger.ONE,
worldStateArchive,
transactionPool,
ethereumWireProtocolConfiguration,
peers,
messages,
ethContext,
Collections.emptyList(),
mergePeerFilter,
mock(SynchronizerConfiguration.class),
ethScheduler,
new ForkIdManager(blockchain, Collections.emptyList(), Collections.emptyList(), false));
}
public static EthProtocolManager create(
final Blockchain blockchain,
final EthScheduler ethScheduler,
final WorldStateArchive worldStateArchive,
final TransactionPool transactionPool,
final EthProtocolConfiguration ethereumWireProtocolConfiguration,
final EthPeers ethPeers,
final EthMessages ethMessages,
final EthContext ethContext) {
return create(
blockchain,
ethScheduler,
worldStateArchive,
transactionPool,
ethereumWireProtocolConfiguration,
ethPeers,
ethMessages,
ethContext,
new ForkIdManager(blockchain, Collections.emptyList(), Collections.emptyList(), false));
}
public static EthProtocolManager create(
final Blockchain blockchain,
final EthScheduler ethScheduler,
final WorldStateArchive worldStateArchive,
final TransactionPool transactionPool,
final EthProtocolConfiguration ethereumWireProtocolConfiguration,
final EthPeers ethPeers,
final EthMessages ethMessages,
final EthContext ethContext,
final ForkIdManager forkIdManager) {
ethPeers.setChainHeadTracker(getChainHeadTrackerMock());
final BigInteger networkId = BigInteger.ONE;
return new EthProtocolManager(
blockchain,
networkId,
worldStateArchive,
transactionPool,
ethereumWireProtocolConfiguration,
ethPeers,
ethMessages,
ethContext,
Collections.emptyList(),
Optional.empty(),
mock(SynchronizerConfiguration.class),
ethScheduler,
forkIdManager);
}
public static EthProtocolManager create(final Blockchain blockchain) {
return create(
ProtocolScheduleFixture.MAINNET,
blockchain,
new DeterministicEthScheduler(TimeoutPolicy.NEVER_TIMEOUT));
}
public static EthProtocolManager create(
final ProtocolSchedule protocolSchedule,
final Blockchain blockchain,
final WorldStateArchive worldStateArchive,
final TransactionPool transactionPool,
final EthProtocolConfiguration ethProtocolConfiguration) {
return create(
protocolSchedule,
blockchain,
new DeterministicEthScheduler(TimeoutPolicy.NEVER_TIMEOUT),
worldStateArchive,
transactionPool,
ethProtocolConfiguration);
}
public static EthProtocolManager create(final EthScheduler ethScheduler) {
final ProtocolSchedule protocolSchedule = ProtocolScheduleFixture.MAINNET;
final GenesisConfigFile config = GenesisConfigFile.mainnet();
final GenesisState genesisState = GenesisState.fromConfig(config, protocolSchedule);
final Blockchain blockchain = createInMemoryBlockchain(genesisState.getBlock());
return create(protocolSchedule, blockchain, ethScheduler);
}
public static EthProtocolManager create(
final ProtocolSchedule protocolSchedule,
final Blockchain blockchain,
final EthScheduler ethScheduler,
final WorldStateArchive worldStateArchive,
final TransactionPool transactionPool,
final EthProtocolConfiguration configuration) {
final EthPeers peers =
new EthPeers(
() -> protocolSchedule.getByBlockHeader(blockchain.getChainHeadHeader()),
TestClock.fixed(),
new NoOpMetricsSystem(),
EthProtocolConfiguration.DEFAULT_MAX_MESSAGE_SIZE,
Collections.emptyList(),
Bytes.random(64),
25,
25,
false,
SyncMode.FAST,
new ForkIdManager(blockchain, Collections.emptyList(), Collections.emptyList(), false));
final EthMessages messages = new EthMessages();
final ChainHeadTracker chtMock = getChainHeadTrackerMock();
peers.setChainHeadTracker(chtMock);
return create(
blockchain,
ethScheduler,
worldStateArchive,
transactionPool,
configuration,
peers,
messages,
new EthContext(peers, messages, ethScheduler));
}
public static ChainHeadTracker getChainHeadTrackerMock() { public static ChainHeadTracker getChainHeadTrackerMock() {
final ChainHeadTracker chtMock = mock(ChainHeadTracker.class); final ChainHeadTracker chtMock = mock(ChainHeadTracker.class);
final BlockHeader blockHeaderMock = mock(BlockHeader.class); final BlockHeader blockHeaderMock = mock(BlockHeader.class);
@@ -249,84 +49,6 @@ public class EthProtocolManagerTestUtil {
return chtMock; return chtMock;
} }
public static EthProtocolManager create(
final ProtocolSchedule protocolSchedule,
final Blockchain blockchain,
final EthScheduler ethScheduler,
final WorldStateArchive worldStateArchive,
final TransactionPool transactionPool,
final EthProtocolConfiguration configuration,
final ForkIdManager forkIdManager) {
final EthPeers peers =
new EthPeers(
() -> protocolSchedule.getByBlockHeader(blockchain.getChainHeadHeader()),
TestClock.fixed(),
new NoOpMetricsSystem(),
EthProtocolConfiguration.DEFAULT_MAX_MESSAGE_SIZE,
Collections.emptyList(),
Bytes.random(64),
25,
25,
false,
SyncMode.FAST,
new ForkIdManager(blockchain, Collections.emptyList(), Collections.emptyList(), false));
final EthMessages messages = new EthMessages();
return create(
blockchain,
ethScheduler,
worldStateArchive,
transactionPool,
configuration,
peers,
messages,
new EthContext(peers, messages, ethScheduler),
forkIdManager);
}
public static EthProtocolManager create(
final ProtocolSchedule protocolSchedule,
final Blockchain blockchain,
final EthScheduler ethScheduler) {
final EthPeers ethPeers =
new EthPeers(
() -> protocolSchedule.getByBlockHeader(blockchain.getChainHeadHeader()),
TestClock.fixed(),
new NoOpMetricsSystem(),
EthProtocolConfiguration.DEFAULT_MAX_MESSAGE_SIZE,
Collections.emptyList(),
Bytes.random(64),
25,
25,
false,
SyncMode.FAST,
new ForkIdManager(blockchain, Collections.emptyList(), Collections.emptyList(), false));
final ChainHeadTracker chainHeadTrackerMock = getChainHeadTrackerMock();
ethPeers.setChainHeadTracker(chainHeadTrackerMock);
final EthMessages messages = new EthMessages();
return create(
blockchain,
ethScheduler,
BlockchainSetupUtil.forTesting(DataStorageFormat.FOREST).getWorldArchive(),
mock(TransactionPool.class),
EthProtocolConfiguration.defaultConfig(),
ethPeers,
messages,
new EthContext(ethPeers, messages, ethScheduler));
}
public static EthProtocolManager create() {
return create(TimeoutPolicy.NEVER_TIMEOUT);
}
public static EthProtocolManager create(final TimeoutPolicy timeoutPolicy) {
return create(new DeterministicEthScheduler(timeoutPolicy));
}
// Utility to prevent scheduler from automatically running submitted tasks // Utility to prevent scheduler from automatically running submitted tasks
public static void disableEthSchedulerAutoRun(final EthProtocolManager ethProtocolManager) { public static void disableEthSchedulerAutoRun(final EthProtocolManager ethProtocolManager) {
final EthScheduler scheduler = ethProtocolManager.ethContext().getScheduler(); final EthScheduler scheduler = ethProtocolManager.ethContext().getScheduler();

View File

@@ -33,6 +33,7 @@ import org.hyperledger.besu.ethereum.eth.manager.EthMessages;
import org.hyperledger.besu.ethereum.eth.manager.EthPeer; import org.hyperledger.besu.ethereum.eth.manager.EthPeer;
import org.hyperledger.besu.ethereum.eth.manager.EthPeers; import org.hyperledger.besu.ethereum.eth.manager.EthPeers;
import org.hyperledger.besu.ethereum.eth.manager.EthProtocolManager; import org.hyperledger.besu.ethereum.eth.manager.EthProtocolManager;
import org.hyperledger.besu.ethereum.eth.manager.EthProtocolManagerTestBuilder;
import org.hyperledger.besu.ethereum.eth.manager.EthProtocolManagerTestUtil; import org.hyperledger.besu.ethereum.eth.manager.EthProtocolManagerTestUtil;
import org.hyperledger.besu.ethereum.eth.manager.EthScheduler; import org.hyperledger.besu.ethereum.eth.manager.EthScheduler;
import org.hyperledger.besu.ethereum.eth.manager.RespondingEthPeer; import org.hyperledger.besu.ethereum.eth.manager.RespondingEthPeer;
@@ -146,15 +147,16 @@ public abstract class AbstractMessageTaskTest<T, R> {
transactionPool.setEnabled(); transactionPool.setEnabled();
ethProtocolManager = ethProtocolManager =
EthProtocolManagerTestUtil.create( EthProtocolManagerTestBuilder.builder()
blockchain, .setProtocolSchedule(protocolSchedule)
ethScheduler, .setBlockchain(blockchain)
protocolContext.getWorldStateArchive(), .setEthScheduler(ethScheduler)
transactionPool, .setTransactionPool(transactionPool)
EthProtocolConfiguration.defaultConfig(), .setEthereumWireProtocolConfiguration(EthProtocolConfiguration.defaultConfig())
ethPeers, .setEthPeers(ethPeers)
ethMessages, .setEthMessages(ethMessages)
ethContext); .setEthContext(ethContext)
.build();
} }
protected abstract T generateDataToBeRequested(); protected abstract T generateDataToBeRequested();

View File

@@ -18,6 +18,7 @@ import static org.assertj.core.api.Assertions.assertThat;
import org.hyperledger.besu.ethereum.eth.manager.EthContext; import org.hyperledger.besu.ethereum.eth.manager.EthContext;
import org.hyperledger.besu.ethereum.eth.manager.EthProtocolManager; import org.hyperledger.besu.ethereum.eth.manager.EthProtocolManager;
import org.hyperledger.besu.ethereum.eth.manager.EthProtocolManagerTestBuilder;
import org.hyperledger.besu.ethereum.eth.manager.EthProtocolManagerTestUtil; import org.hyperledger.besu.ethereum.eth.manager.EthProtocolManagerTestUtil;
import org.hyperledger.besu.metrics.noop.NoOpMetricsSystem; import org.hyperledger.besu.metrics.noop.NoOpMetricsSystem;
import org.hyperledger.besu.plugin.services.MetricsSystem; import org.hyperledger.besu.plugin.services.MetricsSystem;
@@ -36,7 +37,7 @@ public class WaitForPeerTaskTest {
@BeforeEach @BeforeEach
public void setupTest() { public void setupTest() {
ethProtocolManager = EthProtocolManagerTestUtil.create(); ethProtocolManager = EthProtocolManagerTestBuilder.builder().build();
ethContext = ethProtocolManager.ethContext(); ethContext = ethProtocolManager.ethContext();
} }

View File

@@ -18,6 +18,7 @@ import static org.assertj.core.api.Assertions.assertThat;
import org.hyperledger.besu.ethereum.eth.manager.EthContext; import org.hyperledger.besu.ethereum.eth.manager.EthContext;
import org.hyperledger.besu.ethereum.eth.manager.EthProtocolManager; import org.hyperledger.besu.ethereum.eth.manager.EthProtocolManager;
import org.hyperledger.besu.ethereum.eth.manager.EthProtocolManagerTestBuilder;
import org.hyperledger.besu.ethereum.eth.manager.EthProtocolManagerTestUtil; import org.hyperledger.besu.ethereum.eth.manager.EthProtocolManagerTestUtil;
import org.hyperledger.besu.metrics.noop.NoOpMetricsSystem; import org.hyperledger.besu.metrics.noop.NoOpMetricsSystem;
import org.hyperledger.besu.plugin.services.MetricsSystem; import org.hyperledger.besu.plugin.services.MetricsSystem;
@@ -36,7 +37,7 @@ public class WaitForPeersTaskTest {
@BeforeEach @BeforeEach
public void setupTest() { public void setupTest() {
ethProtocolManager = EthProtocolManagerTestUtil.create(); ethProtocolManager = EthProtocolManagerTestBuilder.builder().build();
ethContext = ethProtocolManager.ethContext(); ethContext = ethProtocolManager.ethContext();
} }

View File

@@ -21,6 +21,7 @@ import org.hyperledger.besu.ethereum.core.BlockDataGenerator;
import org.hyperledger.besu.ethereum.core.BlockDataGenerator.BlockOptions; import org.hyperledger.besu.ethereum.core.BlockDataGenerator.BlockOptions;
import org.hyperledger.besu.ethereum.eth.manager.EthPeer; import org.hyperledger.besu.ethereum.eth.manager.EthPeer;
import org.hyperledger.besu.ethereum.eth.manager.EthProtocolManager; import org.hyperledger.besu.ethereum.eth.manager.EthProtocolManager;
import org.hyperledger.besu.ethereum.eth.manager.EthProtocolManagerTestBuilder;
import org.hyperledger.besu.ethereum.eth.manager.EthProtocolManagerTestUtil; import org.hyperledger.besu.ethereum.eth.manager.EthProtocolManagerTestUtil;
import org.hyperledger.besu.ethereum.eth.manager.RespondingEthPeer; import org.hyperledger.besu.ethereum.eth.manager.RespondingEthPeer;
import org.hyperledger.besu.ethereum.eth.messages.BlockHeadersMessage; import org.hyperledger.besu.ethereum.eth.messages.BlockHeadersMessage;
@@ -43,7 +44,11 @@ public abstract class AbstractPeerBlockValidatorTest {
@Test @Test
public void validatePeer_unresponsivePeer() { public void validatePeer_unresponsivePeer() {
final EthProtocolManager ethProtocolManager = final EthProtocolManager ethProtocolManager =
EthProtocolManagerTestUtil.create(DeterministicEthScheduler.TimeoutPolicy.ALWAYS_TIMEOUT); EthProtocolManagerTestBuilder.builder()
.setEthScheduler(
new DeterministicEthScheduler(
DeterministicEthScheduler.TimeoutPolicy.ALWAYS_TIMEOUT))
.build();
final long blockNumber = 500; final long blockNumber = 500;
final PeerValidator validator = createValidator(blockNumber, 0); final PeerValidator validator = createValidator(blockNumber, 0);
@@ -61,7 +66,7 @@ public abstract class AbstractPeerBlockValidatorTest {
@Test @Test
public void validatePeer_requestBlockFromPeerBeingTested() { public void validatePeer_requestBlockFromPeerBeingTested() {
final EthProtocolManager ethProtocolManager = EthProtocolManagerTestUtil.create(); final EthProtocolManager ethProtocolManager = EthProtocolManagerTestBuilder.builder().build();
final BlockDataGenerator gen = new BlockDataGenerator(1); final BlockDataGenerator gen = new BlockDataGenerator(1);
final long blockNumber = 500; final long blockNumber = 500;
final Block block = gen.block(BlockOptions.create().setBlockNumber(blockNumber)); final Block block = gen.block(BlockOptions.create().setBlockNumber(blockNumber));
@@ -97,7 +102,11 @@ public abstract class AbstractPeerBlockValidatorTest {
public void canBeValidated() { public void canBeValidated() {
final BlockDataGenerator gen = new BlockDataGenerator(1); final BlockDataGenerator gen = new BlockDataGenerator(1);
final EthProtocolManager ethProtocolManager = final EthProtocolManager ethProtocolManager =
EthProtocolManagerTestUtil.create(DeterministicEthScheduler.TimeoutPolicy.ALWAYS_TIMEOUT); EthProtocolManagerTestBuilder.builder()
.setEthScheduler(
new DeterministicEthScheduler(
DeterministicEthScheduler.TimeoutPolicy.ALWAYS_TIMEOUT))
.build();
final long blockNumber = 500; final long blockNumber = 500;
final long buffer = 10; final long buffer = 10;

View File

@@ -21,6 +21,7 @@ import org.hyperledger.besu.ethereum.core.BlockDataGenerator;
import org.hyperledger.besu.ethereum.core.BlockDataGenerator.BlockOptions; import org.hyperledger.besu.ethereum.core.BlockDataGenerator.BlockOptions;
import org.hyperledger.besu.ethereum.core.ProtocolScheduleFixture; import org.hyperledger.besu.ethereum.core.ProtocolScheduleFixture;
import org.hyperledger.besu.ethereum.eth.manager.EthProtocolManager; import org.hyperledger.besu.ethereum.eth.manager.EthProtocolManager;
import org.hyperledger.besu.ethereum.eth.manager.EthProtocolManagerTestBuilder;
import org.hyperledger.besu.ethereum.eth.manager.EthProtocolManagerTestUtil; import org.hyperledger.besu.ethereum.eth.manager.EthProtocolManagerTestUtil;
import org.hyperledger.besu.ethereum.eth.manager.RespondingEthPeer; import org.hyperledger.besu.ethereum.eth.manager.RespondingEthPeer;
import org.hyperledger.besu.ethereum.mainnet.MainnetBlockHeaderValidator; import org.hyperledger.besu.ethereum.mainnet.MainnetBlockHeaderValidator;
@@ -42,7 +43,7 @@ public class DaoForkPeerValidatorTest extends AbstractPeerBlockValidatorTest {
@Test @Test
public void validatePeer_responsivePeerOnRightSideOfFork() { public void validatePeer_responsivePeerOnRightSideOfFork() {
final EthProtocolManager ethProtocolManager = EthProtocolManagerTestUtil.create(); final EthProtocolManager ethProtocolManager = EthProtocolManagerTestBuilder.builder().build();
final BlockDataGenerator gen = new BlockDataGenerator(1); final BlockDataGenerator gen = new BlockDataGenerator(1);
final long daoBlockNumber = 500; final long daoBlockNumber = 500;
final Block daoBlock = final Block daoBlock =
@@ -73,7 +74,7 @@ public class DaoForkPeerValidatorTest extends AbstractPeerBlockValidatorTest {
@Test @Test
public void validatePeer_responsivePeerOnWrongSideOfFork() { public void validatePeer_responsivePeerOnWrongSideOfFork() {
final EthProtocolManager ethProtocolManager = EthProtocolManagerTestUtil.create(); final EthProtocolManager ethProtocolManager = EthProtocolManagerTestBuilder.builder().build();
final BlockDataGenerator gen = new BlockDataGenerator(1); final BlockDataGenerator gen = new BlockDataGenerator(1);
final long daoBlockNumber = 500; final long daoBlockNumber = 500;
final Block daoBlock = final Block daoBlock =
@@ -101,7 +102,7 @@ public class DaoForkPeerValidatorTest extends AbstractPeerBlockValidatorTest {
@Test @Test
public void validatePeer_responsivePeerDoesNotHaveBlockWhenPastForkHeight() { public void validatePeer_responsivePeerDoesNotHaveBlockWhenPastForkHeight() {
final EthProtocolManager ethProtocolManager = EthProtocolManagerTestUtil.create(); final EthProtocolManager ethProtocolManager = EthProtocolManagerTestBuilder.builder().build();
final long daoBlockNumber = 500; final long daoBlockNumber = 500;
final PeerValidator validator = final PeerValidator validator =

View File

@@ -25,6 +25,7 @@ import static org.mockito.Mockito.when;
import org.hyperledger.besu.ethereum.eth.manager.EthPeer; import org.hyperledger.besu.ethereum.eth.manager.EthPeer;
import org.hyperledger.besu.ethereum.eth.manager.EthProtocolManager; import org.hyperledger.besu.ethereum.eth.manager.EthProtocolManager;
import org.hyperledger.besu.ethereum.eth.manager.EthProtocolManagerTestBuilder;
import org.hyperledger.besu.ethereum.eth.manager.EthProtocolManagerTestUtil; import org.hyperledger.besu.ethereum.eth.manager.EthProtocolManagerTestUtil;
import org.hyperledger.besu.ethereum.p2p.rlpx.wire.messages.DisconnectMessage.DisconnectReason; import org.hyperledger.besu.ethereum.p2p.rlpx.wire.messages.DisconnectMessage.DisconnectReason;
@@ -39,7 +40,7 @@ public class PeerValidatorRunnerTest {
public void checkPeer_schedulesFutureCheckWhenPeerNotReady() { public void checkPeer_schedulesFutureCheckWhenPeerNotReady() {
final PeerValidator validator = mock(PeerValidator.class); final PeerValidator validator = mock(PeerValidator.class);
final EthProtocolManager ethProtocolManager = EthProtocolManagerTestUtil.create(); final EthProtocolManager ethProtocolManager = EthProtocolManagerTestBuilder.builder().build();
EthProtocolManagerTestUtil.disableEthSchedulerAutoRun(ethProtocolManager); EthProtocolManagerTestUtil.disableEthSchedulerAutoRun(ethProtocolManager);
final EthPeer peer = final EthPeer peer =
EthProtocolManagerTestUtil.peerBuilder() EthProtocolManagerTestUtil.peerBuilder()
@@ -78,7 +79,7 @@ public class PeerValidatorRunnerTest {
public void checkPeer_doesNotScheduleFutureCheckWhenPeerNotReadyAndDisconnected() { public void checkPeer_doesNotScheduleFutureCheckWhenPeerNotReadyAndDisconnected() {
final PeerValidator validator = mock(PeerValidator.class); final PeerValidator validator = mock(PeerValidator.class);
final EthProtocolManager ethProtocolManager = EthProtocolManagerTestUtil.create(); final EthProtocolManager ethProtocolManager = EthProtocolManagerTestBuilder.builder().build();
EthProtocolManagerTestUtil.disableEthSchedulerAutoRun(ethProtocolManager); EthProtocolManagerTestUtil.disableEthSchedulerAutoRun(ethProtocolManager);
final EthPeer peer = final EthPeer peer =
EthProtocolManagerTestUtil.peerBuilder() EthProtocolManagerTestUtil.peerBuilder()
@@ -105,7 +106,7 @@ public class PeerValidatorRunnerTest {
public void checkPeer_handlesInvalidPeer() { public void checkPeer_handlesInvalidPeer() {
final PeerValidator validator = mock(PeerValidator.class); final PeerValidator validator = mock(PeerValidator.class);
final EthProtocolManager ethProtocolManager = EthProtocolManagerTestUtil.create(); final EthProtocolManager ethProtocolManager = EthProtocolManagerTestBuilder.builder().build();
EthProtocolManagerTestUtil.disableEthSchedulerAutoRun(ethProtocolManager); EthProtocolManagerTestUtil.disableEthSchedulerAutoRun(ethProtocolManager);
final EthPeer peer = final EthPeer peer =
EthProtocolManagerTestUtil.peerBuilder() EthProtocolManagerTestUtil.peerBuilder()
@@ -138,7 +139,7 @@ public class PeerValidatorRunnerTest {
public void checkPeer_handlesValidPeer() { public void checkPeer_handlesValidPeer() {
final PeerValidator validator = mock(PeerValidator.class); final PeerValidator validator = mock(PeerValidator.class);
final EthProtocolManager ethProtocolManager = EthProtocolManagerTestUtil.create(); final EthProtocolManager ethProtocolManager = EthProtocolManagerTestBuilder.builder().build();
EthProtocolManagerTestUtil.disableEthSchedulerAutoRun(ethProtocolManager); EthProtocolManagerTestUtil.disableEthSchedulerAutoRun(ethProtocolManager);
final EthPeer peer = final EthPeer peer =
EthProtocolManagerTestUtil.peerBuilder() EthProtocolManagerTestUtil.peerBuilder()

View File

@@ -22,6 +22,7 @@ import org.hyperledger.besu.ethereum.core.BlockDataGenerator;
import org.hyperledger.besu.ethereum.core.BlockDataGenerator.BlockOptions; import org.hyperledger.besu.ethereum.core.BlockDataGenerator.BlockOptions;
import org.hyperledger.besu.ethereum.core.ProtocolScheduleFixture; import org.hyperledger.besu.ethereum.core.ProtocolScheduleFixture;
import org.hyperledger.besu.ethereum.eth.manager.EthProtocolManager; import org.hyperledger.besu.ethereum.eth.manager.EthProtocolManager;
import org.hyperledger.besu.ethereum.eth.manager.EthProtocolManagerTestBuilder;
import org.hyperledger.besu.ethereum.eth.manager.EthProtocolManagerTestUtil; import org.hyperledger.besu.ethereum.eth.manager.EthProtocolManagerTestUtil;
import org.hyperledger.besu.ethereum.eth.manager.RespondingEthPeer; import org.hyperledger.besu.ethereum.eth.manager.RespondingEthPeer;
import org.hyperledger.besu.metrics.noop.NoOpMetricsSystem; import org.hyperledger.besu.metrics.noop.NoOpMetricsSystem;
@@ -41,7 +42,10 @@ public class RequiredBlocksPeerValidatorTest extends AbstractPeerBlockValidatorT
@Test @Test
public void validatePeer_responsivePeerWithRequiredBlock() { public void validatePeer_responsivePeerWithRequiredBlock() {
final EthProtocolManager ethProtocolManager = EthProtocolManagerTestUtil.create(); final EthProtocolManager ethProtocolManager =
EthProtocolManagerTestBuilder.builder()
.setProtocolSchedule(ProtocolScheduleFixture.MAINNET)
.build();
final BlockDataGenerator gen = new BlockDataGenerator(1); final BlockDataGenerator gen = new BlockDataGenerator(1);
final long requiredBlockNumber = 500; final long requiredBlockNumber = 500;
final Block requiredBlock = final Block requiredBlock =
@@ -73,7 +77,7 @@ public class RequiredBlocksPeerValidatorTest extends AbstractPeerBlockValidatorT
@Test @Test
public void validatePeer_responsivePeerWithBadRequiredBlock() { public void validatePeer_responsivePeerWithBadRequiredBlock() {
final EthProtocolManager ethProtocolManager = EthProtocolManagerTestUtil.create(); final EthProtocolManager ethProtocolManager = EthProtocolManagerTestBuilder.builder().build();
final BlockDataGenerator gen = new BlockDataGenerator(1); final BlockDataGenerator gen = new BlockDataGenerator(1);
final long requiredBlockNumber = 500; final long requiredBlockNumber = 500;
final Block requiredBlock = final Block requiredBlock =
@@ -105,7 +109,7 @@ public class RequiredBlocksPeerValidatorTest extends AbstractPeerBlockValidatorT
@Test @Test
public void validatePeer_responsivePeerDoesNotHaveBlockWhenPastForkHeight() { public void validatePeer_responsivePeerDoesNotHaveBlockWhenPastForkHeight() {
final EthProtocolManager ethProtocolManager = EthProtocolManagerTestUtil.create(); final EthProtocolManager ethProtocolManager = EthProtocolManagerTestBuilder.builder().build();
final PeerValidator validator = final PeerValidator validator =
new RequiredBlocksPeerValidator( new RequiredBlocksPeerValidator(

View File

@@ -45,6 +45,7 @@ import org.hyperledger.besu.ethereum.eth.manager.EthContext;
import org.hyperledger.besu.ethereum.eth.manager.EthMessages; import org.hyperledger.besu.ethereum.eth.manager.EthMessages;
import org.hyperledger.besu.ethereum.eth.manager.EthPeers; import org.hyperledger.besu.ethereum.eth.manager.EthPeers;
import org.hyperledger.besu.ethereum.eth.manager.EthProtocolManager; import org.hyperledger.besu.ethereum.eth.manager.EthProtocolManager;
import org.hyperledger.besu.ethereum.eth.manager.EthProtocolManagerTestBuilder;
import org.hyperledger.besu.ethereum.eth.manager.EthProtocolManagerTestUtil; import org.hyperledger.besu.ethereum.eth.manager.EthProtocolManagerTestUtil;
import org.hyperledger.besu.ethereum.eth.manager.EthScheduler; import org.hyperledger.besu.ethereum.eth.manager.EthScheduler;
import org.hyperledger.besu.ethereum.eth.manager.RespondingEthPeer; import org.hyperledger.besu.ethereum.eth.manager.RespondingEthPeer;
@@ -110,12 +111,13 @@ public abstract class AbstractBlockPropagationManagerTest {
tempProtocolContext.getConsensusContext(ConsensusContext.class), tempProtocolContext.getConsensusContext(ConsensusContext.class),
new BadBlockManager()); new BadBlockManager());
ethProtocolManager = ethProtocolManager =
EthProtocolManagerTestUtil.create( EthProtocolManagerTestBuilder.builder()
protocolSchedule, .setProtocolSchedule(protocolSchedule)
blockchain, .setBlockchain(blockchain)
blockchainUtil.getWorldArchive(), .setWorldStateArchive(blockchainUtil.getWorldArchive())
blockchainUtil.getTransactionPool(), .setTransactionPool(blockchainUtil.getTransactionPool())
EthProtocolConfiguration.defaultConfig()); .setEthereumWireProtocolConfiguration(EthProtocolConfiguration.defaultConfig())
.build();
syncConfig = SynchronizerConfiguration.builder().blockPropagationRange(-3, 5).build(); syncConfig = SynchronizerConfiguration.builder().blockPropagationRange(-3, 5).build();
syncState = new SyncState(blockchain, ethProtocolManager.ethContext().getEthPeers()); syncState = new SyncState(blockchain, ethProtocolManager.ethContext().getEthPeers());
blockBroadcaster = mock(BlockBroadcaster.class); blockBroadcaster = mock(BlockBroadcaster.class);

View File

@@ -27,7 +27,7 @@ import org.hyperledger.besu.ethereum.core.MiningConfiguration;
import org.hyperledger.besu.ethereum.difficulty.fixed.FixedDifficultyProtocolSchedule; import org.hyperledger.besu.ethereum.difficulty.fixed.FixedDifficultyProtocolSchedule;
import org.hyperledger.besu.ethereum.eth.manager.ChainState; import org.hyperledger.besu.ethereum.eth.manager.ChainState;
import org.hyperledger.besu.ethereum.eth.manager.EthProtocolManager; import org.hyperledger.besu.ethereum.eth.manager.EthProtocolManager;
import org.hyperledger.besu.ethereum.eth.manager.EthProtocolManagerTestUtil; import org.hyperledger.besu.ethereum.eth.manager.EthProtocolManagerTestBuilder;
import org.hyperledger.besu.ethereum.eth.manager.RespondingEthPeer; import org.hyperledger.besu.ethereum.eth.manager.RespondingEthPeer;
import org.hyperledger.besu.ethereum.eth.manager.RespondingEthPeer.Responder; import org.hyperledger.besu.ethereum.eth.manager.RespondingEthPeer.Responder;
import org.hyperledger.besu.ethereum.mainnet.ProtocolSchedule; import org.hyperledger.besu.ethereum.mainnet.ProtocolSchedule;
@@ -76,7 +76,7 @@ public class ChainHeadTrackerTest {
public void setup(final DataStorageFormat storageFormat) { public void setup(final DataStorageFormat storageFormat) {
blockchainSetupUtil = BlockchainSetupUtil.forTesting(storageFormat); blockchainSetupUtil = BlockchainSetupUtil.forTesting(storageFormat);
blockchain = blockchainSetupUtil.getBlockchain(); blockchain = blockchainSetupUtil.getBlockchain();
ethProtocolManager = EthProtocolManagerTestUtil.create(blockchain); ethProtocolManager = EthProtocolManagerTestBuilder.builder().setBlockchain(blockchain).build();
respondingPeer = respondingPeer =
RespondingEthPeer.builder() RespondingEthPeer.builder()
.ethProtocolManager(ethProtocolManager) .ethProtocolManager(ethProtocolManager)

View File

@@ -24,6 +24,7 @@ import org.hyperledger.besu.ethereum.core.BlockHeader;
import org.hyperledger.besu.ethereum.core.BlockchainSetupUtil; import org.hyperledger.besu.ethereum.core.BlockchainSetupUtil;
import org.hyperledger.besu.ethereum.eth.manager.EthPeer; import org.hyperledger.besu.ethereum.eth.manager.EthPeer;
import org.hyperledger.besu.ethereum.eth.manager.EthProtocolManager; import org.hyperledger.besu.ethereum.eth.manager.EthProtocolManager;
import org.hyperledger.besu.ethereum.eth.manager.EthProtocolManagerTestBuilder;
import org.hyperledger.besu.ethereum.eth.manager.EthProtocolManagerTestUtil; import org.hyperledger.besu.ethereum.eth.manager.EthProtocolManagerTestUtil;
import org.hyperledger.besu.ethereum.eth.manager.RespondingEthPeer; import org.hyperledger.besu.ethereum.eth.manager.RespondingEthPeer;
import org.hyperledger.besu.ethereum.eth.sync.range.RangeHeaders; import org.hyperledger.besu.ethereum.eth.sync.range.RangeHeaders;
@@ -65,7 +66,7 @@ public class DownloadHeadersStepTest {
@BeforeEach @BeforeEach
public void setUp() { public void setUp() {
ethProtocolManager = EthProtocolManagerTestUtil.create(blockchain); ethProtocolManager = EthProtocolManagerTestBuilder.builder().setBlockchain(blockchain).build();
downloader = downloader =
new DownloadHeadersStep( new DownloadHeadersStep(
protocolSchedule, protocolSchedule,

View File

@@ -26,6 +26,7 @@ import org.hyperledger.besu.ethereum.core.BlockchainSetupUtil;
import org.hyperledger.besu.ethereum.eth.EthProtocolConfiguration; import org.hyperledger.besu.ethereum.eth.EthProtocolConfiguration;
import org.hyperledger.besu.ethereum.eth.manager.EthContext; import org.hyperledger.besu.ethereum.eth.manager.EthContext;
import org.hyperledger.besu.ethereum.eth.manager.EthProtocolManager; import org.hyperledger.besu.ethereum.eth.manager.EthProtocolManager;
import org.hyperledger.besu.ethereum.eth.manager.EthProtocolManagerTestBuilder;
import org.hyperledger.besu.ethereum.eth.manager.EthProtocolManagerTestUtil; import org.hyperledger.besu.ethereum.eth.manager.EthProtocolManagerTestUtil;
import org.hyperledger.besu.ethereum.eth.manager.RespondingEthPeer; import org.hyperledger.besu.ethereum.eth.manager.RespondingEthPeer;
import org.hyperledger.besu.ethereum.eth.manager.RespondingEthPeer.Responder; import org.hyperledger.besu.ethereum.eth.manager.RespondingEthPeer.Responder;
@@ -36,6 +37,7 @@ import org.hyperledger.besu.ethereum.mainnet.ProtocolSchedule;
import org.hyperledger.besu.metrics.noop.NoOpMetricsSystem; import org.hyperledger.besu.metrics.noop.NoOpMetricsSystem;
import org.hyperledger.besu.plugin.services.MetricsSystem; import org.hyperledger.besu.plugin.services.MetricsSystem;
import org.hyperledger.besu.plugin.services.storage.DataStorageFormat; import org.hyperledger.besu.plugin.services.storage.DataStorageFormat;
import org.hyperledger.besu.testutil.DeterministicEthScheduler;
import java.util.List; import java.util.List;
import java.util.concurrent.CompletableFuture; import java.util.concurrent.CompletableFuture;
@@ -73,13 +75,14 @@ public class RangeHeadersFetcherTest {
@BeforeEach @BeforeEach
public void setUpTest() { public void setUpTest() {
ethProtocolManager = ethProtocolManager =
EthProtocolManagerTestUtil.create( EthProtocolManagerTestBuilder.builder()
protocolSchedule, .setProtocolSchedule(protocolSchedule)
blockchain, .setBlockchain(blockchain)
() -> false, .setEthScheduler(new DeterministicEthScheduler(() -> false))
protocolContext.getWorldStateArchive(), .setWorldStateArchive(protocolContext.getWorldStateArchive())
transactionPool, .setTransactionPool(transactionPool)
EthProtocolConfiguration.defaultConfig()); .setEthereumWireProtocolConfiguration(EthProtocolConfiguration.defaultConfig())
.build();
responder = responder =
RespondingEthPeer.blockchainResponder( RespondingEthPeer.blockchainResponder(
blockchain, protocolContext.getWorldStateArchive(), transactionPool); blockchain, protocolContext.getWorldStateArchive(), transactionPool);

View File

@@ -40,6 +40,7 @@ import org.hyperledger.besu.ethereum.core.MiningConfiguration;
import org.hyperledger.besu.ethereum.core.TransactionReceipt; import org.hyperledger.besu.ethereum.core.TransactionReceipt;
import org.hyperledger.besu.ethereum.eth.manager.EthContext; import org.hyperledger.besu.ethereum.eth.manager.EthContext;
import org.hyperledger.besu.ethereum.eth.manager.EthProtocolManager; import org.hyperledger.besu.ethereum.eth.manager.EthProtocolManager;
import org.hyperledger.besu.ethereum.eth.manager.EthProtocolManagerTestBuilder;
import org.hyperledger.besu.ethereum.eth.manager.EthProtocolManagerTestUtil; import org.hyperledger.besu.ethereum.eth.manager.EthProtocolManagerTestUtil;
import org.hyperledger.besu.ethereum.eth.manager.RespondingEthPeer; import org.hyperledger.besu.ethereum.eth.manager.RespondingEthPeer;
import org.hyperledger.besu.ethereum.eth.sync.state.SyncState; import org.hyperledger.besu.ethereum.eth.sync.state.SyncState;
@@ -144,7 +145,11 @@ public class BackwardSyncContextTest {
} }
} }
when(protocolContext.getBlockchain()).thenReturn(localBlockchain); when(protocolContext.getBlockchain()).thenReturn(localBlockchain);
EthProtocolManager ethProtocolManager = EthProtocolManagerTestUtil.create(); EthProtocolManager ethProtocolManager =
EthProtocolManagerTestBuilder.builder()
.setProtocolSchedule(protocolSchedule)
.setBlockchain(localBlockchain)
.build();
peer = EthProtocolManagerTestUtil.createPeer(ethProtocolManager); peer = EthProtocolManagerTestUtil.createPeer(ethProtocolManager);
EthContext ethContext = ethProtocolManager.ethContext(); EthContext ethContext = ethProtocolManager.ethContext();

View File

@@ -33,7 +33,7 @@ import org.hyperledger.besu.ethereum.core.MiningConfiguration;
import org.hyperledger.besu.ethereum.core.TransactionReceipt; import org.hyperledger.besu.ethereum.core.TransactionReceipt;
import org.hyperledger.besu.ethereum.eth.manager.EthContext; import org.hyperledger.besu.ethereum.eth.manager.EthContext;
import org.hyperledger.besu.ethereum.eth.manager.EthProtocolManager; import org.hyperledger.besu.ethereum.eth.manager.EthProtocolManager;
import org.hyperledger.besu.ethereum.eth.manager.EthProtocolManagerTestUtil; import org.hyperledger.besu.ethereum.eth.manager.EthProtocolManagerTestBuilder;
import org.hyperledger.besu.ethereum.eth.manager.RespondingEthPeer; import org.hyperledger.besu.ethereum.eth.manager.RespondingEthPeer;
import org.hyperledger.besu.ethereum.eth.manager.exceptions.MaxRetriesReachedException; import org.hyperledger.besu.ethereum.eth.manager.exceptions.MaxRetriesReachedException;
import org.hyperledger.besu.ethereum.mainnet.MainnetBlockHeaderFunctions; import org.hyperledger.besu.ethereum.mainnet.MainnetBlockHeaderFunctions;
@@ -130,7 +130,8 @@ public class BackwardSyncStepTest {
when(context.getProtocolSchedule()).thenReturn(protocolSchedule); when(context.getProtocolSchedule()).thenReturn(protocolSchedule);
when(context.getBatchSize()).thenReturn(5); when(context.getBatchSize()).thenReturn(5);
EthProtocolManager ethProtocolManager = EthProtocolManagerTestUtil.create(ethScheduler); EthProtocolManager ethProtocolManager =
EthProtocolManagerTestBuilder.builder().setEthScheduler(ethScheduler).build();
peer = peer =
RespondingEthPeer.builder() RespondingEthPeer.builder()

View File

@@ -90,7 +90,7 @@ public class ChainForTestCreator {
blockHeader.getExcessBlobGas().orElse(null), blockHeader.getExcessBlobGas().orElse(null),
blockHeader.getParentBeaconBlockRoot().orElse(null), blockHeader.getParentBeaconBlockRoot().orElse(null),
blockHeader.getRequestsHash().orElse(null), blockHeader.getRequestsHash().orElse(null),
blockHeader.getTargetBlobCount().orElse(null), blockHeader.getTargetBlobsPerBlock().orElse(null),
new MainnetBlockHeaderFunctions()); new MainnetBlockHeaderFunctions());
} }

View File

@@ -32,6 +32,7 @@ import org.hyperledger.besu.ethereum.core.MiningConfiguration;
import org.hyperledger.besu.ethereum.core.TransactionReceipt; import org.hyperledger.besu.ethereum.core.TransactionReceipt;
import org.hyperledger.besu.ethereum.eth.manager.EthContext; import org.hyperledger.besu.ethereum.eth.manager.EthContext;
import org.hyperledger.besu.ethereum.eth.manager.EthProtocolManager; import org.hyperledger.besu.ethereum.eth.manager.EthProtocolManager;
import org.hyperledger.besu.ethereum.eth.manager.EthProtocolManagerTestBuilder;
import org.hyperledger.besu.ethereum.eth.manager.EthProtocolManagerTestUtil; import org.hyperledger.besu.ethereum.eth.manager.EthProtocolManagerTestUtil;
import org.hyperledger.besu.ethereum.eth.manager.RespondingEthPeer; import org.hyperledger.besu.ethereum.eth.manager.RespondingEthPeer;
import org.hyperledger.besu.ethereum.mainnet.MainnetBlockHeaderFunctions; import org.hyperledger.besu.ethereum.mainnet.MainnetBlockHeaderFunctions;
@@ -127,7 +128,7 @@ public class ForwardSyncStepTest {
when(context.getProtocolContext().getBlockchain()).thenReturn(localBlockchain); when(context.getProtocolContext().getBlockchain()).thenReturn(localBlockchain);
when(context.getProtocolSchedule()).thenReturn(protocolSchedule); when(context.getProtocolSchedule()).thenReturn(protocolSchedule);
when(context.getBatchSize()).thenReturn(2); when(context.getBatchSize()).thenReturn(2);
EthProtocolManager ethProtocolManager = EthProtocolManagerTestUtil.create(); EthProtocolManager ethProtocolManager = EthProtocolManagerTestBuilder.builder().build();
peer = EthProtocolManagerTestUtil.createPeer(ethProtocolManager); peer = EthProtocolManagerTestUtil.createPeer(ethProtocolManager);
EthContext ethContext = ethProtocolManager.ethContext(); EthContext ethContext = ethProtocolManager.ethContext();

View File

@@ -28,6 +28,7 @@ import org.hyperledger.besu.ethereum.core.Difficulty;
import org.hyperledger.besu.ethereum.core.TransactionReceipt; import org.hyperledger.besu.ethereum.core.TransactionReceipt;
import org.hyperledger.besu.ethereum.eth.manager.EthContext; import org.hyperledger.besu.ethereum.eth.manager.EthContext;
import org.hyperledger.besu.ethereum.eth.manager.EthProtocolManager; import org.hyperledger.besu.ethereum.eth.manager.EthProtocolManager;
import org.hyperledger.besu.ethereum.eth.manager.EthProtocolManagerTestBuilder;
import org.hyperledger.besu.ethereum.eth.manager.EthProtocolManagerTestUtil; import org.hyperledger.besu.ethereum.eth.manager.EthProtocolManagerTestUtil;
import org.hyperledger.besu.ethereum.eth.manager.EthScheduler; import org.hyperledger.besu.ethereum.eth.manager.EthScheduler;
import org.hyperledger.besu.ethereum.eth.manager.RespondingEthPeer; import org.hyperledger.besu.ethereum.eth.manager.RespondingEthPeer;
@@ -121,10 +122,11 @@ public class CheckPointSyncChainDownloaderTest {
protocolSchedule = localBlockchainSetup.getProtocolSchedule(); protocolSchedule = localBlockchainSetup.getProtocolSchedule();
protocolContext = localBlockchainSetup.getProtocolContext(); protocolContext = localBlockchainSetup.getProtocolContext();
ethProtocolManager = ethProtocolManager =
EthProtocolManagerTestUtil.create( EthProtocolManagerTestBuilder.builder()
protocolSchedule, .setProtocolSchedule(protocolSchedule)
localBlockchain, .setBlockchain(localBlockchain)
new EthScheduler(1, 1, 1, 1, new NoOpMetricsSystem())); .setEthScheduler(new EthScheduler(1, 1, 1, 1, new NoOpMetricsSystem()))
.build();
ethContext = ethProtocolManager.ethContext(); ethContext = ethProtocolManager.ethContext();
final int blockNumber = 10; final int blockNumber = 10;

View File

@@ -31,6 +31,7 @@ import org.hyperledger.besu.ethereum.core.Transaction;
import org.hyperledger.besu.ethereum.core.TransactionReceipt; import org.hyperledger.besu.ethereum.core.TransactionReceipt;
import org.hyperledger.besu.ethereum.eth.EthProtocolConfiguration; import org.hyperledger.besu.ethereum.eth.EthProtocolConfiguration;
import org.hyperledger.besu.ethereum.eth.manager.EthProtocolManager; import org.hyperledger.besu.ethereum.eth.manager.EthProtocolManager;
import org.hyperledger.besu.ethereum.eth.manager.EthProtocolManagerTestBuilder;
import org.hyperledger.besu.ethereum.eth.manager.EthProtocolManagerTestUtil; import org.hyperledger.besu.ethereum.eth.manager.EthProtocolManagerTestUtil;
import org.hyperledger.besu.ethereum.eth.manager.RespondingEthPeer; import org.hyperledger.besu.ethereum.eth.manager.RespondingEthPeer;
import org.hyperledger.besu.ethereum.eth.manager.peertask.PeerTaskExecutor; import org.hyperledger.besu.ethereum.eth.manager.peertask.PeerTaskExecutor;
@@ -42,6 +43,7 @@ import org.hyperledger.besu.ethereum.eth.transactions.TransactionPool;
import org.hyperledger.besu.ethereum.mainnet.ProtocolSchedule; import org.hyperledger.besu.ethereum.mainnet.ProtocolSchedule;
import org.hyperledger.besu.metrics.noop.NoOpMetricsSystem; import org.hyperledger.besu.metrics.noop.NoOpMetricsSystem;
import org.hyperledger.besu.plugin.services.storage.DataStorageFormat; import org.hyperledger.besu.plugin.services.storage.DataStorageFormat;
import org.hyperledger.besu.testutil.DeterministicEthScheduler;
import java.util.HashMap; import java.util.HashMap;
import java.util.List; import java.util.List;
@@ -78,13 +80,14 @@ public class DownloadReceiptsStepTest {
peerTaskExecutor = mock(PeerTaskExecutor.class); peerTaskExecutor = mock(PeerTaskExecutor.class);
TransactionPool transactionPool = mock(TransactionPool.class); TransactionPool transactionPool = mock(TransactionPool.class);
ethProtocolManager = ethProtocolManager =
EthProtocolManagerTestUtil.create( EthProtocolManagerTestBuilder.builder()
ProtocolScheduleFixture.MAINNET, .setProtocolSchedule(ProtocolScheduleFixture.MAINNET)
blockchain, .setBlockchain(blockchain)
() -> false, .setEthScheduler(new DeterministicEthScheduler(() -> false))
protocolContext.getWorldStateArchive(), .setWorldStateArchive(protocolContext.getWorldStateArchive())
transactionPool, .setTransactionPool(transactionPool)
EthProtocolConfiguration.defaultConfig()); .setEthereumWireProtocolConfiguration(EthProtocolConfiguration.defaultConfig())
.build();
} }
@Test @Test

View File

@@ -32,6 +32,7 @@ import org.hyperledger.besu.ethereum.eth.manager.EthContext;
import org.hyperledger.besu.ethereum.eth.manager.EthPeer; import org.hyperledger.besu.ethereum.eth.manager.EthPeer;
import org.hyperledger.besu.ethereum.eth.manager.EthPeers; import org.hyperledger.besu.ethereum.eth.manager.EthPeers;
import org.hyperledger.besu.ethereum.eth.manager.EthProtocolManager; import org.hyperledger.besu.ethereum.eth.manager.EthProtocolManager;
import org.hyperledger.besu.ethereum.eth.manager.EthProtocolManagerTestBuilder;
import org.hyperledger.besu.ethereum.eth.manager.EthProtocolManagerTestUtil; import org.hyperledger.besu.ethereum.eth.manager.EthProtocolManagerTestUtil;
import org.hyperledger.besu.ethereum.eth.manager.RespondingEthPeer; import org.hyperledger.besu.ethereum.eth.manager.RespondingEthPeer;
import org.hyperledger.besu.ethereum.eth.manager.peertask.PeerTaskExecutor; import org.hyperledger.besu.ethereum.eth.manager.peertask.PeerTaskExecutor;
@@ -45,6 +46,7 @@ import org.hyperledger.besu.ethereum.worldstate.WorldStateStorageCoordinator;
import org.hyperledger.besu.metrics.noop.NoOpMetricsSystem; import org.hyperledger.besu.metrics.noop.NoOpMetricsSystem;
import org.hyperledger.besu.plugin.services.MetricsSystem; import org.hyperledger.besu.plugin.services.MetricsSystem;
import org.hyperledger.besu.plugin.services.storage.DataStorageFormat; import org.hyperledger.besu.plugin.services.storage.DataStorageFormat;
import org.hyperledger.besu.testutil.DeterministicEthScheduler;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.List; import java.util.List;
@@ -93,13 +95,15 @@ public class FastSyncActionsTest {
blockchainSetupUtil.importAllBlocks(); blockchainSetupUtil.importAllBlocks();
blockchain = blockchainSetupUtil.getBlockchain(); blockchain = blockchainSetupUtil.getBlockchain();
ethProtocolManager = ethProtocolManager =
EthProtocolManagerTestUtil.create( EthProtocolManagerTestBuilder.builder()
ProtocolScheduleFixture.MAINNET, .setProtocolSchedule(ProtocolScheduleFixture.MAINNET)
blockchain, .setBlockchain(blockchain)
() -> timeoutCount.getAndDecrement() > 0, .setEthScheduler(
blockchainSetupUtil.getWorldArchive(), new DeterministicEthScheduler(() -> timeoutCount.getAndDecrement() > 0))
blockchainSetupUtil.getTransactionPool(), .setWorldStateArchive(blockchainSetupUtil.getWorldArchive())
EthProtocolConfiguration.defaultConfig()); .setTransactionPool(blockchainSetupUtil.getTransactionPool())
.setEthereumWireProtocolConfiguration(EthProtocolConfiguration.defaultConfig())
.build();
ethContext = ethProtocolManager.ethContext(); ethContext = ethProtocolManager.ethContext();
ethPeers = ethContext.getEthPeers(); ethPeers = ethContext.getEthPeers();
syncState = new SyncState(blockchain, ethPeers); syncState = new SyncState(blockchain, ethPeers);

View File

@@ -26,6 +26,7 @@ import org.hyperledger.besu.ethereum.chain.MutableBlockchain;
import org.hyperledger.besu.ethereum.core.BlockchainSetupUtil; import org.hyperledger.besu.ethereum.core.BlockchainSetupUtil;
import org.hyperledger.besu.ethereum.eth.manager.EthContext; import org.hyperledger.besu.ethereum.eth.manager.EthContext;
import org.hyperledger.besu.ethereum.eth.manager.EthProtocolManager; import org.hyperledger.besu.ethereum.eth.manager.EthProtocolManager;
import org.hyperledger.besu.ethereum.eth.manager.EthProtocolManagerTestBuilder;
import org.hyperledger.besu.ethereum.eth.manager.EthProtocolManagerTestUtil; import org.hyperledger.besu.ethereum.eth.manager.EthProtocolManagerTestUtil;
import org.hyperledger.besu.ethereum.eth.manager.EthScheduler; import org.hyperledger.besu.ethereum.eth.manager.EthScheduler;
import org.hyperledger.besu.ethereum.eth.manager.RespondingEthPeer; import org.hyperledger.besu.ethereum.eth.manager.RespondingEthPeer;
@@ -87,10 +88,11 @@ public class FastSyncChainDownloaderTest {
protocolSchedule = localBlockchainSetup.getProtocolSchedule(); protocolSchedule = localBlockchainSetup.getProtocolSchedule();
protocolContext = localBlockchainSetup.getProtocolContext(); protocolContext = localBlockchainSetup.getProtocolContext();
ethProtocolManager = ethProtocolManager =
EthProtocolManagerTestUtil.create( EthProtocolManagerTestBuilder.builder()
protocolSchedule, .setProtocolSchedule(protocolSchedule)
localBlockchain, .setBlockchain(localBlockchain)
new EthScheduler(1, 1, 1, 1, new NoOpMetricsSystem())); .setEthScheduler(new EthScheduler(1, 1, 1, 1, new NoOpMetricsSystem()))
.build();
ethContext = ethProtocolManager.ethContext(); ethContext = ethProtocolManager.ethContext();
syncState = new SyncState(protocolContext.getBlockchain(), ethContext.getEthPeers()); syncState = new SyncState(protocolContext.getBlockchain(), ethContext.getEthPeers());

View File

@@ -26,6 +26,7 @@ import org.hyperledger.besu.ethereum.core.BlockHeaderTestFixture;
import org.hyperledger.besu.ethereum.core.BlockchainSetupUtil; import org.hyperledger.besu.ethereum.core.BlockchainSetupUtil;
import org.hyperledger.besu.ethereum.eth.EthProtocolConfiguration; import org.hyperledger.besu.ethereum.eth.EthProtocolConfiguration;
import org.hyperledger.besu.ethereum.eth.manager.EthProtocolManager; import org.hyperledger.besu.ethereum.eth.manager.EthProtocolManager;
import org.hyperledger.besu.ethereum.eth.manager.EthProtocolManagerTestBuilder;
import org.hyperledger.besu.ethereum.eth.manager.EthProtocolManagerTestUtil; import org.hyperledger.besu.ethereum.eth.manager.EthProtocolManagerTestUtil;
import org.hyperledger.besu.ethereum.eth.manager.RespondingEthPeer; import org.hyperledger.besu.ethereum.eth.manager.RespondingEthPeer;
import org.hyperledger.besu.ethereum.eth.manager.RespondingEthPeer.Responder; import org.hyperledger.besu.ethereum.eth.manager.RespondingEthPeer.Responder;
@@ -35,6 +36,7 @@ import org.hyperledger.besu.ethereum.mainnet.ProtocolSchedule;
import org.hyperledger.besu.metrics.noop.NoOpMetricsSystem; import org.hyperledger.besu.metrics.noop.NoOpMetricsSystem;
import org.hyperledger.besu.plugin.services.MetricsSystem; import org.hyperledger.besu.plugin.services.MetricsSystem;
import org.hyperledger.besu.plugin.services.storage.DataStorageFormat; import org.hyperledger.besu.plugin.services.storage.DataStorageFormat;
import org.hyperledger.besu.testutil.DeterministicEthScheduler;
import java.util.Optional; import java.util.Optional;
import java.util.concurrent.CompletableFuture; import java.util.concurrent.CompletableFuture;
@@ -79,13 +81,14 @@ public class PivotBlockConfirmerTest {
protocolSchedule = blockchainSetupUtil.getProtocolSchedule(); protocolSchedule = blockchainSetupUtil.getProtocolSchedule();
protocolContext = blockchainSetupUtil.getProtocolContext(); protocolContext = blockchainSetupUtil.getProtocolContext();
ethProtocolManager = ethProtocolManager =
EthProtocolManagerTestUtil.create( EthProtocolManagerTestBuilder.builder()
protocolSchedule, .setProtocolSchedule(protocolSchedule)
blockchain, .setBlockchain(blockchain)
timeout::get, .setEthScheduler(new DeterministicEthScheduler(timeout::get))
blockchainSetupUtil.getWorldArchive(), .setWorldStateArchive(blockchainSetupUtil.getWorldArchive())
transactionPool, .setTransactionPool(transactionPool)
EthProtocolConfiguration.defaultConfig()); .setEthereumWireProtocolConfiguration(EthProtocolConfiguration.defaultConfig())
.build();
pivotBlockConfirmer = createPivotBlockConfirmer(3, 2); pivotBlockConfirmer = createPivotBlockConfirmer(3, 2);
} }

View File

@@ -28,6 +28,7 @@ import org.hyperledger.besu.ethereum.core.BlockchainSetupUtil;
import org.hyperledger.besu.ethereum.core.Difficulty; import org.hyperledger.besu.ethereum.core.Difficulty;
import org.hyperledger.besu.ethereum.eth.EthProtocolConfiguration; import org.hyperledger.besu.ethereum.eth.EthProtocolConfiguration;
import org.hyperledger.besu.ethereum.eth.manager.EthProtocolManager; import org.hyperledger.besu.ethereum.eth.manager.EthProtocolManager;
import org.hyperledger.besu.ethereum.eth.manager.EthProtocolManagerTestBuilder;
import org.hyperledger.besu.ethereum.eth.manager.EthProtocolManagerTestUtil; import org.hyperledger.besu.ethereum.eth.manager.EthProtocolManagerTestUtil;
import org.hyperledger.besu.ethereum.eth.manager.RespondingEthPeer; import org.hyperledger.besu.ethereum.eth.manager.RespondingEthPeer;
import org.hyperledger.besu.ethereum.eth.manager.RespondingEthPeer.Responder; import org.hyperledger.besu.ethereum.eth.manager.RespondingEthPeer.Responder;
@@ -37,6 +38,7 @@ import org.hyperledger.besu.ethereum.mainnet.ProtocolSchedule;
import org.hyperledger.besu.metrics.noop.NoOpMetricsSystem; import org.hyperledger.besu.metrics.noop.NoOpMetricsSystem;
import org.hyperledger.besu.plugin.services.MetricsSystem; import org.hyperledger.besu.plugin.services.MetricsSystem;
import org.hyperledger.besu.plugin.services.storage.DataStorageFormat; import org.hyperledger.besu.plugin.services.storage.DataStorageFormat;
import org.hyperledger.besu.testutil.DeterministicEthScheduler;
import org.hyperledger.besu.util.ExceptionUtils; import org.hyperledger.besu.util.ExceptionUtils;
import java.util.Optional; import java.util.Optional;
@@ -82,13 +84,14 @@ public class PivotBlockRetrieverTest {
protocolContext = blockchainSetupUtil.getProtocolContext(); protocolContext = blockchainSetupUtil.getProtocolContext();
transactionPool = blockchainSetupUtil.getTransactionPool(); transactionPool = blockchainSetupUtil.getTransactionPool();
ethProtocolManager = ethProtocolManager =
EthProtocolManagerTestUtil.create( EthProtocolManagerTestBuilder.builder()
protocolSchedule, .setProtocolSchedule(protocolSchedule)
blockchain, .setBlockchain(blockchain)
timeout::get, .setEthScheduler(new DeterministicEthScheduler(timeout::get))
blockchainSetupUtil.getWorldArchive(), .setWorldStateArchive(blockchainSetupUtil.getWorldArchive())
transactionPool, .setTransactionPool(transactionPool)
EthProtocolConfiguration.defaultConfig()); .setEthereumWireProtocolConfiguration(EthProtocolConfiguration.defaultConfig())
.build();
pivotBlockRetriever = createPivotBlockRetriever(3, 1, 1); pivotBlockRetriever = createPivotBlockRetriever(3, 1, 1);
} }

View File

@@ -36,6 +36,7 @@ import org.hyperledger.besu.ethereum.core.MutableWorldState;
import org.hyperledger.besu.ethereum.core.ProtocolScheduleFixture; import org.hyperledger.besu.ethereum.core.ProtocolScheduleFixture;
import org.hyperledger.besu.ethereum.eth.manager.EthContext; import org.hyperledger.besu.ethereum.eth.manager.EthContext;
import org.hyperledger.besu.ethereum.eth.manager.EthProtocolManager; import org.hyperledger.besu.ethereum.eth.manager.EthProtocolManager;
import org.hyperledger.besu.ethereum.eth.manager.EthProtocolManagerTestBuilder;
import org.hyperledger.besu.ethereum.eth.manager.EthProtocolManagerTestUtil; import org.hyperledger.besu.ethereum.eth.manager.EthProtocolManagerTestUtil;
import org.hyperledger.besu.ethereum.eth.manager.EthScheduler; import org.hyperledger.besu.ethereum.eth.manager.EthScheduler;
import org.hyperledger.besu.ethereum.eth.manager.RespondingEthPeer; import org.hyperledger.besu.ethereum.eth.manager.RespondingEthPeer;
@@ -114,7 +115,9 @@ class FastWorldStateDownloaderTest {
.build()); .build());
final EthProtocolManager ethProtocolManager = final EthProtocolManager ethProtocolManager =
EthProtocolManagerTestUtil.create(new EthScheduler(1, 1, 1, 1, new NoOpMetricsSystem())); EthProtocolManagerTestBuilder.builder()
.setEthScheduler(new EthScheduler(1, 1, 1, 1, new NoOpMetricsSystem()))
.build();
@AfterEach @AfterEach
public void tearDown() throws Exception { public void tearDown() throws Exception {
@@ -238,7 +241,10 @@ class FastWorldStateDownloaderTest {
void canRecoverFromTimeouts() { void canRecoverFromTimeouts() {
final DeterministicEthScheduler.TimeoutPolicy timeoutPolicy = final DeterministicEthScheduler.TimeoutPolicy timeoutPolicy =
DeterministicEthScheduler.TimeoutPolicy.timeoutXTimes(2); DeterministicEthScheduler.TimeoutPolicy.timeoutXTimes(2);
final EthProtocolManager ethProtocolManager = EthProtocolManagerTestUtil.create(timeoutPolicy); final EthProtocolManager ethProtocolManager =
EthProtocolManagerTestBuilder.builder()
.setEthScheduler(new DeterministicEthScheduler(timeoutPolicy))
.build();
final MockExecutorService serviceExecutor = final MockExecutorService serviceExecutor =
((DeterministicEthScheduler) ethProtocolManager.ethContext().getScheduler()) ((DeterministicEthScheduler) ethProtocolManager.ethContext().getScheduler())
.mockServiceExecutor(); .mockServiceExecutor();
@@ -382,7 +388,7 @@ class FastWorldStateDownloaderTest {
@SuppressWarnings("unchecked") @SuppressWarnings("unchecked")
private void testCancellation(final boolean shouldCancelFuture) { private void testCancellation(final boolean shouldCancelFuture) {
final EthProtocolManager ethProtocolManager = EthProtocolManagerTestUtil.create(); final EthProtocolManager ethProtocolManager = EthProtocolManagerTestBuilder.builder().build();
// Prevent the persistence service from running // Prevent the persistence service from running
final MockExecutorService serviceExecutor = final MockExecutorService serviceExecutor =
((DeterministicEthScheduler) ethProtocolManager.ethContext().getScheduler()) ((DeterministicEthScheduler) ethProtocolManager.ethContext().getScheduler())
@@ -661,7 +667,9 @@ class FastWorldStateDownloaderTest {
@Timeout(value = 60) @Timeout(value = 60)
void stalledDownloader() { void stalledDownloader() {
final EthProtocolManager ethProtocolManager = final EthProtocolManager ethProtocolManager =
EthProtocolManagerTestUtil.create(new EthScheduler(1, 1, 1, 1, new NoOpMetricsSystem())); EthProtocolManagerTestBuilder.builder()
.setEthScheduler(new EthScheduler(1, 1, 1, 1, new NoOpMetricsSystem()))
.build();
// Setup "remote" state // Setup "remote" state
final ForestWorldStateKeyValueStorage remoteStorage = final ForestWorldStateKeyValueStorage remoteStorage =

View File

@@ -24,6 +24,7 @@ import org.hyperledger.besu.ethereum.core.Difficulty;
import org.hyperledger.besu.ethereum.eth.EthProtocolConfiguration; import org.hyperledger.besu.ethereum.eth.EthProtocolConfiguration;
import org.hyperledger.besu.ethereum.eth.manager.EthContext; import org.hyperledger.besu.ethereum.eth.manager.EthContext;
import org.hyperledger.besu.ethereum.eth.manager.EthProtocolManager; import org.hyperledger.besu.ethereum.eth.manager.EthProtocolManager;
import org.hyperledger.besu.ethereum.eth.manager.EthProtocolManagerTestBuilder;
import org.hyperledger.besu.ethereum.eth.manager.EthProtocolManagerTestUtil; import org.hyperledger.besu.ethereum.eth.manager.EthProtocolManagerTestUtil;
import org.hyperledger.besu.ethereum.eth.manager.EthScheduler; import org.hyperledger.besu.ethereum.eth.manager.EthScheduler;
import org.hyperledger.besu.ethereum.eth.manager.RespondingEthPeer; import org.hyperledger.besu.ethereum.eth.manager.RespondingEthPeer;
@@ -66,13 +67,14 @@ public class FullSyncChainDownloaderForkTest {
protocolSchedule = localBlockchainSetup.getProtocolSchedule(); protocolSchedule = localBlockchainSetup.getProtocolSchedule();
protocolContext = localBlockchainSetup.getProtocolContext(); protocolContext = localBlockchainSetup.getProtocolContext();
ethProtocolManager = ethProtocolManager =
EthProtocolManagerTestUtil.create( EthProtocolManagerTestBuilder.builder()
protocolSchedule, .setProtocolSchedule(protocolSchedule)
localBlockchain, .setBlockchain(localBlockchain)
new EthScheduler(1, 1, 1, 1, new NoOpMetricsSystem()), .setEthScheduler(new EthScheduler(1, 1, 1, 1, new NoOpMetricsSystem()))
localBlockchainSetup.getWorldArchive(), .setWorldStateArchive(localBlockchainSetup.getWorldArchive())
localBlockchainSetup.getTransactionPool(), .setTransactionPool(localBlockchainSetup.getTransactionPool())
EthProtocolConfiguration.defaultConfig()); .setEthereumWireProtocolConfiguration(EthProtocolConfiguration.defaultConfig())
.build();
ethContext = ethProtocolManager.ethContext(); ethContext = ethProtocolManager.ethContext();
syncState = new SyncState(protocolContext.getBlockchain(), ethContext.getEthPeers()); syncState = new SyncState(protocolContext.getBlockchain(), ethContext.getEthPeers());
} }

View File

@@ -31,6 +31,7 @@ import org.hyperledger.besu.ethereum.core.TransactionReceipt;
import org.hyperledger.besu.ethereum.eth.EthProtocolConfiguration; import org.hyperledger.besu.ethereum.eth.EthProtocolConfiguration;
import org.hyperledger.besu.ethereum.eth.manager.EthContext; import org.hyperledger.besu.ethereum.eth.manager.EthContext;
import org.hyperledger.besu.ethereum.eth.manager.EthProtocolManager; import org.hyperledger.besu.ethereum.eth.manager.EthProtocolManager;
import org.hyperledger.besu.ethereum.eth.manager.EthProtocolManagerTestBuilder;
import org.hyperledger.besu.ethereum.eth.manager.EthProtocolManagerTestUtil; import org.hyperledger.besu.ethereum.eth.manager.EthProtocolManagerTestUtil;
import org.hyperledger.besu.ethereum.eth.manager.EthScheduler; import org.hyperledger.besu.ethereum.eth.manager.EthScheduler;
import org.hyperledger.besu.ethereum.eth.manager.RespondingEthPeer; import org.hyperledger.besu.ethereum.eth.manager.RespondingEthPeer;
@@ -96,13 +97,14 @@ public class FullSyncChainDownloaderTest {
protocolSchedule = localBlockchainSetup.getProtocolSchedule(); protocolSchedule = localBlockchainSetup.getProtocolSchedule();
protocolContext = localBlockchainSetup.getProtocolContext(); protocolContext = localBlockchainSetup.getProtocolContext();
ethProtocolManager = ethProtocolManager =
EthProtocolManagerTestUtil.create( EthProtocolManagerTestBuilder.builder()
protocolSchedule, .setProtocolSchedule(protocolSchedule)
localBlockchain, .setBlockchain(localBlockchain)
new EthScheduler(1, 1, 1, 1, new NoOpMetricsSystem()), .setEthScheduler(new EthScheduler(1, 1, 1, 1, new NoOpMetricsSystem()))
localBlockchainSetup.getWorldArchive(), .setWorldStateArchive(localBlockchainSetup.getWorldArchive())
localBlockchainSetup.getTransactionPool(), .setTransactionPool(localBlockchainSetup.getTransactionPool())
EthProtocolConfiguration.defaultConfig()); .setEthereumWireProtocolConfiguration(EthProtocolConfiguration.defaultConfig())
.build();
ethContext = ethProtocolManager.ethContext(); ethContext = ethProtocolManager.ethContext();
syncState = new SyncState(protocolContext.getBlockchain(), ethContext.getEthPeers()); syncState = new SyncState(protocolContext.getBlockchain(), ethContext.getEthPeers());
} }

View File

@@ -24,6 +24,7 @@ import org.hyperledger.besu.ethereum.core.Difficulty;
import org.hyperledger.besu.ethereum.eth.EthProtocolConfiguration; import org.hyperledger.besu.ethereum.eth.EthProtocolConfiguration;
import org.hyperledger.besu.ethereum.eth.manager.EthContext; import org.hyperledger.besu.ethereum.eth.manager.EthContext;
import org.hyperledger.besu.ethereum.eth.manager.EthProtocolManager; import org.hyperledger.besu.ethereum.eth.manager.EthProtocolManager;
import org.hyperledger.besu.ethereum.eth.manager.EthProtocolManagerTestBuilder;
import org.hyperledger.besu.ethereum.eth.manager.EthProtocolManagerTestUtil; import org.hyperledger.besu.ethereum.eth.manager.EthProtocolManagerTestUtil;
import org.hyperledger.besu.ethereum.eth.manager.EthScheduler; import org.hyperledger.besu.ethereum.eth.manager.EthScheduler;
import org.hyperledger.besu.ethereum.eth.manager.RespondingEthPeer; import org.hyperledger.besu.ethereum.eth.manager.RespondingEthPeer;
@@ -80,13 +81,14 @@ public class FullSyncChainDownloaderTotalTerminalDifficultyTest {
protocolSchedule = localBlockchainSetup.getProtocolSchedule(); protocolSchedule = localBlockchainSetup.getProtocolSchedule();
protocolContext = localBlockchainSetup.getProtocolContext(); protocolContext = localBlockchainSetup.getProtocolContext();
ethProtocolManager = ethProtocolManager =
EthProtocolManagerTestUtil.create( EthProtocolManagerTestBuilder.builder()
protocolSchedule, .setProtocolSchedule(protocolSchedule)
localBlockchain, .setBlockchain(localBlockchain)
new EthScheduler(1, 1, 1, 1, new NoOpMetricsSystem()), .setEthScheduler(new EthScheduler(1, 1, 1, 1, new NoOpMetricsSystem()))
localBlockchainSetup.getWorldArchive(), .setWorldStateArchive(localBlockchainSetup.getWorldArchive())
localBlockchainSetup.getTransactionPool(), .setTransactionPool(localBlockchainSetup.getTransactionPool())
EthProtocolConfiguration.defaultConfig()); .setEthereumWireProtocolConfiguration(EthProtocolConfiguration.defaultConfig())
.build();
ethContext = ethProtocolManager.ethContext(); ethContext = ethProtocolManager.ethContext();
syncState = new SyncState(protocolContext.getBlockchain(), ethContext.getEthPeers()); syncState = new SyncState(protocolContext.getBlockchain(), ethContext.getEthPeers());
} }

View File

@@ -22,6 +22,7 @@ import org.hyperledger.besu.ethereum.core.BlockchainSetupUtil;
import org.hyperledger.besu.ethereum.eth.EthProtocolConfiguration; import org.hyperledger.besu.ethereum.eth.EthProtocolConfiguration;
import org.hyperledger.besu.ethereum.eth.manager.EthContext; import org.hyperledger.besu.ethereum.eth.manager.EthContext;
import org.hyperledger.besu.ethereum.eth.manager.EthProtocolManager; import org.hyperledger.besu.ethereum.eth.manager.EthProtocolManager;
import org.hyperledger.besu.ethereum.eth.manager.EthProtocolManagerTestBuilder;
import org.hyperledger.besu.ethereum.eth.manager.EthProtocolManagerTestUtil; import org.hyperledger.besu.ethereum.eth.manager.EthProtocolManagerTestUtil;
import org.hyperledger.besu.ethereum.eth.manager.EthScheduler; import org.hyperledger.besu.ethereum.eth.manager.EthScheduler;
import org.hyperledger.besu.ethereum.eth.manager.RespondingEthPeer; import org.hyperledger.besu.ethereum.eth.manager.RespondingEthPeer;
@@ -71,13 +72,14 @@ public class FullSyncDownloaderTest {
protocolSchedule = localBlockchainSetup.getProtocolSchedule(); protocolSchedule = localBlockchainSetup.getProtocolSchedule();
protocolContext = localBlockchainSetup.getProtocolContext(); protocolContext = localBlockchainSetup.getProtocolContext();
ethProtocolManager = ethProtocolManager =
EthProtocolManagerTestUtil.create( EthProtocolManagerTestBuilder.builder()
protocolSchedule, .setProtocolSchedule(protocolSchedule)
localBlockchain, .setBlockchain(localBlockchain)
new EthScheduler(1, 1, 1, 1, new NoOpMetricsSystem()), .setEthScheduler(new EthScheduler(1, 1, 1, 1, new NoOpMetricsSystem()))
localBlockchainSetup.getWorldArchive(), .setWorldStateArchive(localBlockchainSetup.getWorldArchive())
localBlockchainSetup.getTransactionPool(), .setTransactionPool(localBlockchainSetup.getTransactionPool())
EthProtocolConfiguration.defaultConfig()); .setEthereumWireProtocolConfiguration(EthProtocolConfiguration.defaultConfig())
.build();
ethContext = ethProtocolManager.ethContext(); ethContext = ethProtocolManager.ethContext();
syncState = new SyncState(protocolContext.getBlockchain(), ethContext.getEthPeers()); syncState = new SyncState(protocolContext.getBlockchain(), ethContext.getEthPeers());
} }

View File

@@ -30,6 +30,7 @@ import org.hyperledger.besu.ethereum.core.ProtocolScheduleFixture;
import org.hyperledger.besu.ethereum.eth.EthProtocolConfiguration; import org.hyperledger.besu.ethereum.eth.EthProtocolConfiguration;
import org.hyperledger.besu.ethereum.eth.manager.EthContext; import org.hyperledger.besu.ethereum.eth.manager.EthContext;
import org.hyperledger.besu.ethereum.eth.manager.EthProtocolManager; import org.hyperledger.besu.ethereum.eth.manager.EthProtocolManager;
import org.hyperledger.besu.ethereum.eth.manager.EthProtocolManagerTestBuilder;
import org.hyperledger.besu.ethereum.eth.manager.EthProtocolManagerTestUtil; import org.hyperledger.besu.ethereum.eth.manager.EthProtocolManagerTestUtil;
import org.hyperledger.besu.ethereum.eth.manager.EthScheduler; import org.hyperledger.besu.ethereum.eth.manager.EthScheduler;
import org.hyperledger.besu.ethereum.eth.manager.RespondingEthPeer; import org.hyperledger.besu.ethereum.eth.manager.RespondingEthPeer;
@@ -81,13 +82,14 @@ public class FullSyncTargetManagerTest {
new ProtocolContext( new ProtocolContext(
localBlockchain, localWorldState, mock(ConsensusContext.class), new BadBlockManager()); localBlockchain, localWorldState, mock(ConsensusContext.class), new BadBlockManager());
ethProtocolManager = ethProtocolManager =
EthProtocolManagerTestUtil.create( EthProtocolManagerTestBuilder.builder()
protocolSchedule, .setProtocolSchedule(protocolSchedule)
localBlockchain, .setBlockchain(localBlockchain)
new EthScheduler(1, 1, 1, 1, new NoOpMetricsSystem()), .setEthScheduler(new EthScheduler(1, 1, 1, 1, new NoOpMetricsSystem()))
localWorldState, .setWorldStateArchive(localBlockchainSetup.getWorldArchive())
localBlockchainSetup.getTransactionPool(), .setTransactionPool(localBlockchainSetup.getTransactionPool())
EthProtocolConfiguration.defaultConfig()); .setEthereumWireProtocolConfiguration(EthProtocolConfiguration.defaultConfig())
.build();
final EthContext ethContext = ethProtocolManager.ethContext(); final EthContext ethContext = ethProtocolManager.ethContext();
localBlockchainSetup.importFirstBlocks(5); localBlockchainSetup.importFirstBlocks(5);
otherBlockchainSetup.importFirstBlocks(20); otherBlockchainSetup.importFirstBlocks(20);

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