From 8c451c109ac7ba6c334d56939a2e17ccc5392bc9 Mon Sep 17 00:00:00 2001 From: ahamlat Date: Wed, 18 Dec 2024 13:44:49 +0100 Subject: [PATCH 1/6] Revise the approach for setting level_compaction_dynamic_level_bytes (#8037) * Create a RocksDB opener that display a warning if it takes too much time to open the database * Change the strategy levelCompactionDynamicLevelBytes is set Signed-off-by: Ameziane H. --- CHANGELOG.md | 1 + ...imisticRocksDBColumnarKeyValueStorage.java | 2 +- .../RocksDBColumnarKeyValueStorage.java | 43 ++++- .../rocksdb/segmented/RocksDBOpener.java | 172 ++++++++++++++++++ ...ctionDBRocksDBColumnarKeyValueStorage.java | 2 +- 5 files changed, 212 insertions(+), 8 deletions(-) create mode 100644 plugins/rocksdb/src/main/java/org/hyperledger/besu/plugin/services/storage/rocksdb/segmented/RocksDBOpener.java diff --git a/CHANGELOG.md b/CHANGELOG.md index f906084db59..9f0f3d40763 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -23,6 +23,7 @@ ### Bug fixes - Fix serialization of state overrides when `movePrecompileToAddress` is present [#8204](https://github.com/hyperledger/besu/pull/8024) +- Revise the approach for setting level_compaction_dynamic_level_bytes RocksDB configuration option [#8037](https://github.com/hyperledger/besu/pull/8037) ## 24.12.2 Hotfix diff --git a/plugins/rocksdb/src/main/java/org/hyperledger/besu/plugin/services/storage/rocksdb/segmented/OptimisticRocksDBColumnarKeyValueStorage.java b/plugins/rocksdb/src/main/java/org/hyperledger/besu/plugin/services/storage/rocksdb/segmented/OptimisticRocksDBColumnarKeyValueStorage.java index d2eaa350239..1e877c1738a 100644 --- a/plugins/rocksdb/src/main/java/org/hyperledger/besu/plugin/services/storage/rocksdb/segmented/OptimisticRocksDBColumnarKeyValueStorage.java +++ b/plugins/rocksdb/src/main/java/org/hyperledger/besu/plugin/services/storage/rocksdb/segmented/OptimisticRocksDBColumnarKeyValueStorage.java @@ -57,7 +57,7 @@ public OptimisticRocksDBColumnarKeyValueStorage( try { db = - OptimisticTransactionDB.open( + RocksDBOpener.openOptimisticTransactionDBWithWarning( options, configuration.getDatabaseDir().toString(), columnDescriptors, columnHandles); initMetrics(); initColumnHandles(); diff --git a/plugins/rocksdb/src/main/java/org/hyperledger/besu/plugin/services/storage/rocksdb/segmented/RocksDBColumnarKeyValueStorage.java b/plugins/rocksdb/src/main/java/org/hyperledger/besu/plugin/services/storage/rocksdb/segmented/RocksDBColumnarKeyValueStorage.java index 0bf107ddb0e..aa508f085c1 100644 --- a/plugins/rocksdb/src/main/java/org/hyperledger/besu/plugin/services/storage/rocksdb/segmented/RocksDBColumnarKeyValueStorage.java +++ b/plugins/rocksdb/src/main/java/org/hyperledger/besu/plugin/services/storage/rocksdb/segmented/RocksDBColumnarKeyValueStorage.java @@ -51,10 +51,12 @@ import org.rocksdb.ColumnFamilyHandle; import org.rocksdb.ColumnFamilyOptions; import org.rocksdb.CompressionType; +import org.rocksdb.ConfigOptions; import org.rocksdb.DBOptions; import org.rocksdb.Env; import org.rocksdb.LRUCache; import org.rocksdb.Options; +import org.rocksdb.OptionsUtil; import org.rocksdb.ReadOptions; import org.rocksdb.RocksDB; import org.rocksdb.RocksDBException; @@ -76,9 +78,6 @@ public abstract class RocksDBColumnarKeyValueStorage implements SegmentedKeyValu /** RocksDb blockcache size when using the high spec option */ protected static final long ROCKSDB_BLOCKCACHE_SIZE_HIGH_SPEC = 1_073_741_824L; - /** RocksDb memtable size when using the high spec option */ - protected static final long ROCKSDB_MEMTABLE_SIZE_HIGH_SPEC = 536_870_912L; - /** Max total size of all WAL file, after which a flush is triggered */ protected static final long WAL_MAX_TOTAL_SIZE = 1_073_741_824L; @@ -186,15 +185,47 @@ public RocksDBColumnarKeyValueStorage( */ private ColumnFamilyDescriptor createColumnDescriptor( final SegmentIdentifier segment, final RocksDBConfiguration configuration) { - + boolean dynamicLevelBytes = true; + try { + ConfigOptions configOptions = new ConfigOptions(); + DBOptions dbOptions = new DBOptions(); + List cfDescriptors = new ArrayList<>(); + + String latestOptionsFileName = + OptionsUtil.getLatestOptionsFileName( + configuration.getDatabaseDir().toString(), Env.getDefault()); + LOG.trace("Latest OPTIONS file detected: " + latestOptionsFileName); + + String optionsFilePath = + configuration.getDatabaseDir().toString() + "/" + latestOptionsFileName; + OptionsUtil.loadOptionsFromFile(configOptions, optionsFilePath, dbOptions, cfDescriptors); + + LOG.trace("RocksDB options loaded successfully from: " + optionsFilePath); + + if (!cfDescriptors.isEmpty()) { + Optional matchedCfOptions = Optional.empty(); + for (ColumnFamilyDescriptor descriptor : cfDescriptors) { + if (Arrays.equals(descriptor.getName(), segment.getId())) { + matchedCfOptions = Optional.of(descriptor.getOptions()); + break; + } + } + if (matchedCfOptions.isPresent()) { + dynamicLevelBytes = matchedCfOptions.get().levelCompactionDynamicLevelBytes(); + LOG.trace("dynamicLevelBytes is set to an existing value : " + dynamicLevelBytes); + } + } + } catch (RocksDBException ex) { + // Options file is not found in the database + } BlockBasedTableConfig basedTableConfig = createBlockBasedTableConfig(segment, configuration); final var options = new ColumnFamilyOptions() .setTtl(0) .setCompressionType(CompressionType.LZ4_COMPRESSION) - .setTableFormatConfig(basedTableConfig); - + .setTableFormatConfig(basedTableConfig) + .setLevelCompactionDynamicLevelBytes(dynamicLevelBytes); if (segment.containsStaticData()) { options .setEnableBlobFiles(true) diff --git a/plugins/rocksdb/src/main/java/org/hyperledger/besu/plugin/services/storage/rocksdb/segmented/RocksDBOpener.java b/plugins/rocksdb/src/main/java/org/hyperledger/besu/plugin/services/storage/rocksdb/segmented/RocksDBOpener.java new file mode 100644 index 00000000000..b8c59d638d7 --- /dev/null +++ b/plugins/rocksdb/src/main/java/org/hyperledger/besu/plugin/services/storage/rocksdb/segmented/RocksDBOpener.java @@ -0,0 +1,172 @@ +/* + * 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.plugin.services.storage.rocksdb.segmented; + +import java.util.List; +import java.util.concurrent.Executors; +import java.util.concurrent.ScheduledExecutorService; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicBoolean; + +import org.rocksdb.ColumnFamilyDescriptor; +import org.rocksdb.ColumnFamilyHandle; +import org.rocksdb.DBOptions; +import org.rocksdb.OptimisticTransactionDB; +import org.rocksdb.RocksDBException; +import org.rocksdb.TransactionDB; +import org.rocksdb.TransactionDBOptions; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +/** + * Utility class for opening RocksDB instances with a warning mechanism. + * + *

This class provides methods to open RocksDB databases ({@link OptimisticTransactionDB} and + * {@link TransactionDB}) while monitoring the operation's duration. If the database takes longer + * than a predefined delay (default: 60 seconds) to open, a warning message is logged. This warning + * helps identify potential delays caused by factors such as RocksDB compaction. + */ +public class RocksDBOpener { + + /** + * Default delay (in seconds) after which a warning is logged if the database opening operation + * has not completed. + */ + public static final int DEFAULT_DELAY = 60; + + /** + * Warning message logged when the database opening operation takes longer than the predefined + * delay. + */ + public static final String WARN_MESSAGE = + "Opening RocksDB database is taking longer than 60 seconds... " + + "This may be due to prolonged RocksDB compaction. Please wait until the end of the compaction. " + + "No action is needed from the user."; + + private static final Logger LOG = LoggerFactory.getLogger(RocksDBOpener.class); + + /** + * Default constructor. + * + *

This is a utility class and is not meant to be instantiated directly. + */ + private RocksDBOpener() { + // Default constructor for RocksDBOpener + } + + /** + * Opens an {@link OptimisticTransactionDB} instance with a warning mechanism. + * + *

If the database opening operation takes longer than {@link #DEFAULT_DELAY} seconds, a + * warning message is logged indicating a possible delay caused by compaction. + * + * @param options the {@link DBOptions} instance used to configure the database. + * @param dbPath the file path to the RocksDB database directory. + * @param columnDescriptors a list of {@link ColumnFamilyDescriptor} objects for the column + * families to open. + * @param columnHandles a list of {@link ColumnFamilyHandle} objects to be populated with the + * opened column families. + * @return an instance of {@link OptimisticTransactionDB}. + * @throws RocksDBException if the database cannot be opened. + */ + public static OptimisticTransactionDB openOptimisticTransactionDBWithWarning( + final DBOptions options, + final String dbPath, + final List columnDescriptors, + final List columnHandles) + throws RocksDBException { + return openDBWithWarning( + () -> OptimisticTransactionDB.open(options, dbPath, columnDescriptors, columnHandles)); + } + + /** + * Opens a {@link TransactionDB} instance with a warning mechanism. + * + *

If the database opening operation takes longer than {@link #DEFAULT_DELAY} seconds, a + * warning message is logged indicating a possible delay caused by compaction. + * + * @param options the {@link DBOptions} instance used to configure the database. + * @param transactionDBOptions the {@link TransactionDBOptions} for transaction-specific + * configuration. + * @param dbPath the file path to the RocksDB database directory. + * @param columnDescriptors a list of {@link ColumnFamilyDescriptor} objects for the column + * families to open. + * @param columnHandles a list of {@link ColumnFamilyHandle} objects to be populated with the + * opened column families. + * @return an instance of {@link TransactionDB}. + * @throws RocksDBException if the database cannot be opened. + */ + public static TransactionDB openTransactionDBWithWarning( + final DBOptions options, + final TransactionDBOptions transactionDBOptions, + final String dbPath, + final List columnDescriptors, + final List columnHandles) + throws RocksDBException { + return openDBWithWarning( + () -> + TransactionDB.open( + options, transactionDBOptions, dbPath, columnDescriptors, columnHandles)); + } + + /** + * A generic method to open a RocksDB database with a warning mechanism. + * + *

If the operation takes longer than {@link #DEFAULT_DELAY} seconds, a warning message is + * logged. + * + * @param dbOperation a lambda or method reference representing the database opening logic. + * @param the type of the database being opened (e.g., {@link OptimisticTransactionDB} or + * {@link TransactionDB}). + * @return an instance of the database being opened. + * @throws RocksDBException if the database cannot be opened. + */ + private static T openDBWithWarning(final DBOperation dbOperation) throws RocksDBException { + AtomicBoolean operationCompleted = new AtomicBoolean(false); + ScheduledExecutorService scheduler = Executors.newSingleThreadScheduledExecutor(); + scheduler.schedule( + () -> { + if (!operationCompleted.get()) { + LOG.warn(WARN_MESSAGE); + } + }, + DEFAULT_DELAY, + TimeUnit.SECONDS); + + try { + T db = dbOperation.open(); + operationCompleted.set(true); + return db; + } finally { + scheduler.shutdown(); + } + } + + /** + * Functional interface representing a database opening operation. + * + * @param the type of the database being opened. + */ + @FunctionalInterface + private interface DBOperation { + /** + * Opens the database. + * + * @return the opened database instance. + * @throws RocksDBException if an error occurs while opening the database. + */ + T open() throws RocksDBException; + } +} diff --git a/plugins/rocksdb/src/main/java/org/hyperledger/besu/plugin/services/storage/rocksdb/segmented/TransactionDBRocksDBColumnarKeyValueStorage.java b/plugins/rocksdb/src/main/java/org/hyperledger/besu/plugin/services/storage/rocksdb/segmented/TransactionDBRocksDBColumnarKeyValueStorage.java index 60879b658e6..035adbfa589 100644 --- a/plugins/rocksdb/src/main/java/org/hyperledger/besu/plugin/services/storage/rocksdb/segmented/TransactionDBRocksDBColumnarKeyValueStorage.java +++ b/plugins/rocksdb/src/main/java/org/hyperledger/besu/plugin/services/storage/rocksdb/segmented/TransactionDBRocksDBColumnarKeyValueStorage.java @@ -56,7 +56,7 @@ public TransactionDBRocksDBColumnarKeyValueStorage( try { db = - TransactionDB.open( + RocksDBOpener.openTransactionDBWithWarning( options, txOptions, configuration.getDatabaseDir().toString(), From d3773d9e336cc7a0af7f1290301e7481f97a9c58 Mon Sep 17 00:00:00 2001 From: daniellehrner Date: Wed, 18 Dec 2024 18:28:08 +0100 Subject: [PATCH 2/6] Pectra Devnet-5: 7702 & 7251: address & code changes (#8029) * update 7251 address, update 7251 & 7702 code Signed-off-by: Daniel Lehrner * spotless Signed-off-by: Daniel Lehrner * Update EIP-7251: Set MAX_CONSOLIDATIONS=2 Signed-off-by: Daniel Lehrner --------- Signed-off-by: Daniel Lehrner --- .../requests/RequestContractAddresses.java | 2 +- .../t8n/prague-withdrawal-request.json | 41 ++++++++++--------- 2 files changed, 22 insertions(+), 21 deletions(-) diff --git a/ethereum/core/src/main/java/org/hyperledger/besu/ethereum/mainnet/requests/RequestContractAddresses.java b/ethereum/core/src/main/java/org/hyperledger/besu/ethereum/mainnet/requests/RequestContractAddresses.java index ef76961ba2b..ebc48a10fb9 100644 --- a/ethereum/core/src/main/java/org/hyperledger/besu/ethereum/mainnet/requests/RequestContractAddresses.java +++ b/ethereum/core/src/main/java/org/hyperledger/besu/ethereum/mainnet/requests/RequestContractAddresses.java @@ -25,7 +25,7 @@ public class RequestContractAddresses { public static final Address DEFAULT_WITHDRAWAL_REQUEST_CONTRACT_ADDRESS = Address.fromHexString("0x0c15F14308530b7CDB8460094BbB9cC28b9AaaAA"); public static final Address DEFAULT_CONSOLIDATION_REQUEST_CONTRACT_ADDRESS = - Address.fromHexString("0x01ABEA29659E5E97C95107F20BB753CD3E09BBBB"); + Address.fromHexString("0x00431F263cE400f4455c2dCf564e53007Ca4bbBb"); public static final Address DEFAULT_DEPOSIT_CONTRACT_ADDRESS = Address.fromHexString("0x00000000219ab540356cbb839cbe05303d7705fa"); diff --git a/ethereum/evmtool/src/test/resources/org/hyperledger/besu/evmtool/t8n/prague-withdrawal-request.json b/ethereum/evmtool/src/test/resources/org/hyperledger/besu/evmtool/t8n/prague-withdrawal-request.json index 91588037fd2..615161c88d8 100644 --- a/ethereum/evmtool/src/test/resources/org/hyperledger/besu/evmtool/t8n/prague-withdrawal-request.json +++ b/ethereum/evmtool/src/test/resources/org/hyperledger/besu/evmtool/t8n/prague-withdrawal-request.json @@ -55,13 +55,14 @@ "comment": "This is the runtime bytecode for the Withdrawal Request Smart Contract.", "nonce": "0x01", "balance": "0x00", - "code": "0x3373fffffffffffffffffffffffffffffffffffffffe1460c7573615156028575f545f5260205ff35b36603814156101f05760115f54807fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff146101f057600182026001905f5b5f821115608057810190830284830290049160010191906065565b9093900434106101f057600154600101600155600354806003026004013381556001015f35815560010160203590553360601b5f5260385f601437604c5fa0600101600355005b6003546002548082038060101160db575060105b5f5b81811461017f5780604c02838201600302600401805490600101805490600101549160601b83528260140152807fffffffffffffffffffffffffffffffff0000000000000000000000000000000016826034015260401c906044018160381c81600701538160301c81600601538160281c81600501538160201c81600401538160181c81600301538160101c81600201538160081c81600101535360010160dd565b9101809214610191579060025561019c565b90505f6002555f6003555b5f54807fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff14156101c957505f5b6001546002828201116101de5750505f6101e4565b01600290035b5f555f600155604c025ff35b5f5ffd", + "code": "0x3373fffffffffffffffffffffffffffffffffffffffe1460cb5760115f54807fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff146101f457600182026001905f5b5f82111560685781019083028483029004916001019190604d565b909390049250505036603814608857366101f457346101f4575f5260205ff35b34106101f457600154600101600155600354806003026004013381556001015f35815560010160203590553360601b5f5260385f601437604c5fa0600101600355005b6003546002548082038060101160df575060105b5f5b8181146101835782810160030260040181604c02815460601b8152601401816001015481526020019060020154807fffffffffffffffffffffffffffffffff00000000000000000000000000000000168252906010019060401c908160381c81600701538160301c81600601538160281c81600501538160201c81600401538160181c81600301538160101c81600201538160081c81600101535360010160e1565b910180921461019557906002556101a0565b90505f6002555f6003555b5f54807fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff14156101cd57505f5b6001546002828201116101e25750505f6101e8565b01600290035b5f555f600155604c025ff35b5f5ffd", "storage": {} }, - "0x01abea29659e5e97c95107f20bb753cd3e09bbbb": { + "0x00431f263ce400f4455c2dcf564e53007ca4bbbb": { + "comment": "Increase the MAX_EFFECTIVE_BALANCE", "nonce": "0x01", "balance": "0x00", - "code": "0x3373fffffffffffffffffffffffffffffffffffffffe1460cf573615156028575f545f5260205ff35b366060141561019a5760115f54807fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff1461019a57600182026001905f5b5f821115608057810190830284830290049160010191906065565b90939004341061019a57600154600101600155600354806004026004013381556001015f358155600101602035815560010160403590553360601b5f5260605f60143760745fa0600101600355005b6003546002548082038060011160e3575060015b5f5b8181146101295780607402838201600402600401805490600101805490600101805490600101549260601b84529083601401528260340152906054015260010160e5565b910180921461013b5790600255610146565b90505f6002555f6003555b5f54807fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff141561017357505f5b6001546001828201116101885750505f61018e565b01600190035b5f555f6001556074025ff35b5f5ffd", + "code": "0x3373fffffffffffffffffffffffffffffffffffffffe1460d35760115f54807fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff1461019a57600182026001905f5b5f82111560685781019083028483029004916001019190604d565b9093900492505050366060146088573661019a573461019a575f5260205ff35b341061019a57600154600101600155600354806004026004013381556001015f358155600101602035815560010160403590553360601b5f5260605f60143760745fa0600101600355005b6003546002548082038060021160e7575060025b5f5b8181146101295782810160040260040181607402815460601b815260140181600101548152602001816002015481526020019060030154905260010160e9565b910180921461013b5790600255610146565b90505f6002555f6003555b5f54807fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff141561017357505f5b6001546001828201116101885750505f61018e565b01600190035b5f555f6001556074025ff35b5f5ffd", "storage": {} }, "0x0aae40965e6800cd9b1f4b05ff21581047e3f91e": { @@ -183,13 +184,21 @@ "balance": "0x0", "nonce": "0x1" }, - "0x01abea29659e5e97c95107f20bb753cd3e09bbbb": { - "code": "0x3373fffffffffffffffffffffffffffffffffffffffe1460cf573615156028575f545f5260205ff35b366060141561019a5760115f54807fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff1461019a57600182026001905f5b5f821115608057810190830284830290049160010191906065565b90939004341061019a57600154600101600155600354806004026004013381556001015f358155600101602035815560010160403590553360601b5f5260605f60143760745fa0600101600355005b6003546002548082038060011160e3575060015b5f5b8181146101295780607402838201600402600401805490600101805490600101805490600101549260601b84529083601401528260340152906054015260010160e5565b910180921461013b5790600255610146565b90505f6002555f6003555b5f54807fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff141561017357505f5b6001546001828201116101885750505f61018e565b01600190035b5f555f6001556074025ff35b5f5ffd", + "0x00431f263ce400f4455c2dcf564e53007ca4bbbb": { + "code": "0x3373fffffffffffffffffffffffffffffffffffffffe1460d35760115f54807fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff1461019a57600182026001905f5b5f82111560685781019083028483029004916001019190604d565b9093900492505050366060146088573661019a573461019a575f5260205ff35b341061019a57600154600101600155600354806004026004013381556001015f358155600101602035815560010160403590553360601b5f5260605f60143760745fa0600101600355005b6003546002548082038060021160e7575060025b5f5b8181146101295782810160040260040181607402815460601b815260140181600101548152602001816002015481526020019060030154905260010160e9565b910180921461013b5790600255610146565b90505f6002555f6003555b5f54807fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff141561017357505f5b6001546001828201116101885750505f61018e565b01600190035b5f555f6001556074025ff35b5f5ffd", "balance": "0x0", "nonce": "0x1" }, + "0x0aae40965e6800cd9b1f4b05ff21581047e3f91e":{ + "code":"0x3373fffffffffffffffffffffffffffffffffffffffe1460575767ffffffffffffffff5f3511605357600143035f3511604b575f35612000014311604b57611fff5f3516545f5260205ff35b5f5f5260205ff35b5f5ffd5b5f35611fff60014303165500", + "storage":{ + "0x0000000000000000000000000000000000000000000000000000000000000000":"0x10715cfbefdb8a0cb2f7d7ca5ee6d1ea65515ecb41cff0a22d1e11716a9d27fb" + }, + "balance":"0x0", + "nonce":"0x1" + }, "0x0c15f14308530b7cdb8460094bbb9cc28b9aaaaa": { - "code": "0x3373fffffffffffffffffffffffffffffffffffffffe1460c7573615156028575f545f5260205ff35b36603814156101f05760115f54807fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff146101f057600182026001905f5b5f821115608057810190830284830290049160010191906065565b9093900434106101f057600154600101600155600354806003026004013381556001015f35815560010160203590553360601b5f5260385f601437604c5fa0600101600355005b6003546002548082038060101160db575060105b5f5b81811461017f5780604c02838201600302600401805490600101805490600101549160601b83528260140152807fffffffffffffffffffffffffffffffff0000000000000000000000000000000016826034015260401c906044018160381c81600701538160301c81600601538160281c81600501538160201c81600401538160181c81600301538160101c81600201538160081c81600101535360010160dd565b9101809214610191579060025561019c565b90505f6002555f6003555b5f54807fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff14156101c957505f5b6001546002828201116101de5750505f6101e4565b01600290035b5f555f600155604c025ff35b5f5ffd", + "code": "0x3373fffffffffffffffffffffffffffffffffffffffe1460cb5760115f54807fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff146101f457600182026001905f5b5f82111560685781019083028483029004916001019190604d565b909390049250505036603814608857366101f457346101f4575f5260205ff35b34106101f457600154600101600155600354806003026004013381556001015f35815560010160203590553360601b5f5260385f601437604c5fa0600101600355005b6003546002548082038060101160df575060105b5f5b8181146101835782810160030260040181604c02815460601b8152601401816001015481526020019060020154807fffffffffffffffffffffffffffffffff00000000000000000000000000000000168252906010019060401c908160381c81600701538160301c81600601538160281c81600501538160201c81600401538160181c81600301538160101c81600201538160081c81600101535360010160e1565b910180921461019557906002556101a0565b90505f6002555f6003555b5f54807fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff14156101cd57505f5b6001546002828201116101e25750505f6101e8565b01600290035b5f555f600155604c025ff35b5f5ffd", "storage": { "0x0000000000000000000000000000000000000000000000000000000000000004": "0x0000000000000000000000000000000000000000000000000000000000001000", "0x0000000000000000000000000000000000000000000000000000000000000006": "0x0000000000000000000000000000000100000000000000000000000000000000" @@ -197,16 +206,8 @@ "balance": "0x1", "nonce": "0x1" }, - "0x0aae40965e6800cd9b1f4b05ff21581047e3f91e": { - "code": "0x3373fffffffffffffffffffffffffffffffffffffffe1460575767ffffffffffffffff5f3511605357600143035f3511604b575f35612000014311604b57611fff5f3516545f5260205ff35b5f5f5260205ff35b5f5ffd5b5f35611fff60014303165500", - "storage": { - "0x0000000000000000000000000000000000000000000000000000000000000000": "0x10715cfbefdb8a0cb2f7d7ca5ee6d1ea65515ecb41cff0a22d1e11716a9d27fb" - }, - "balance": "0x0", - "nonce": "0x1" - }, "0xa94f5374fce5edbc8e2a8697c15331677e6ebf0b": { - "balance": "0xad78ebc5ac61f2afcb", + "balance": "0xad78ebc5ac61f2b034", "nonce": "0x1" } }, @@ -218,16 +219,16 @@ "0x00000000000000000000000000000000000010000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000010000000000000000", "0x" ], - "stateRoot": "0x85f165ac5a1420cd8931904750ffa7d8e271a53590776045731a7a31bd28fb35", + "stateRoot": "0x575019750f84d65daf5469b26d05ad8e4335c63011dbca71ca97420cbd80d579", "txRoot": "0x0d36638e52999b7beafa00eb94f7ca23139774cd14229c011d0edc1fc66125c9", - "receiptsRoot": "0x74c42177b19a4db67c4bf4eb40d7e0a31102f8e918db6b60276994d95834b8f9", + "receiptsRoot": "0x2af83312a6aa55bd8f169e65eec48f92d6d6dc3398bc038d7ccfab5d9aa26b3f", "logsHash": "0xac344ad50aad544ec284bf76ac9b939f93e00f8fe16097a151df14bde2065f83", "logsBloom": "0x00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000001000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000002000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000002000000000000000000000000000", "receipts": [ { "root": "0x", "status": "0x1", - "cumulativeGasUsed": "0x1e6e3", + "cumulativeGasUsed": "0x1e6d4", "logsBloom": "0x00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000001000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000002000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000002000000000000000000000000000", "logs": [ { @@ -244,13 +245,13 @@ ], "transactionHash": "0xa888ec4587b7ba70d0127004a96fbb0a83ccb611e61405094e6514b970bf37f6", "contractAddress": "0x0000000000000000000000000000000000000000", - "gasUsed": "0x1e6e3", + "gasUsed": "0x1e6d4", "blockHash": "0x0000000000000000000000000000000000000000000000000000000000000000", "transactionIndex": "0x0" } ], "currentDifficulty": null, - "gasUsed": "0x1e6e3", + "gasUsed": "0x1e6d4", "currentBaseFee": "0x7", "withdrawalsRoot": "0x56e81f171bcc55a6ff8345e692c0f86e5b48e01b996cadc001622fb5e363b421", "currentExcessBlobGas": "0x0", From 3b4136dac5ef6bbff8eb039a9459af221fbc89cc Mon Sep 17 00:00:00 2001 From: Justin Florentine Date: Wed, 18 Dec 2024 17:39:00 -0500 Subject: [PATCH 3/6] rename GenesisConfigFile because it's not a file at all (#8050) Signed-off-by: jflo --- .../condition/clique/CliqueConditions.java | 6 +- .../dsl/node/ThreadBesuNodeRunner.java | 10 +-- .../org/hyperledger/besu/cli/BesuCommand.java | 18 ++-- .../besu/cli/config/EthNetworkConfig.java | 28 +++---- .../operator/GenerateBlockchainConfig.java | 4 +- .../besu/controller/BesuController.java | 24 +++--- .../controller/BesuControllerBuilder.java | 15 ++-- ...onsensusScheduleBesuControllerBuilder.java | 8 +- .../TransitionBesuControllerBuilder.java | 8 +- .../besu/util/EphemeryGenesisUpdater.java | 16 ++-- .../besu/FlexGroupPrivacyTest.java | 4 +- .../besu/ForkIdsNetworkConfigTest.java | 17 ++-- .../hyperledger/besu/PrivacyReorgTest.java | 10 +-- .../org/hyperledger/besu/PrivacyTest.java | 4 +- .../java/org/hyperledger/besu/RunnerTest.java | 19 ++--- .../chainimport/JsonBlockImporterTest.java | 18 ++-- .../hyperledger/besu/cli/BesuCommandTest.java | 36 ++++---- .../cli/CascadingDefaultProviderTest.java | 7 +- .../besu/cli/config/EthNetworkConfigTest.java | 8 +- .../besu/components/GenesisConfigModule.java | 10 +-- .../AbstractBftBesuControllerBuilderTest.java | 20 ++--- .../besu/controller/BesuControllerTest.java | 27 +++--- .../CliqueBesuControllerBuilderTest.java | 18 ++-- ...nsusScheduleBesuControllerBuilderTest.java | 8 +- .../IbftBesuControllerBuilderTest.java | 4 +- .../MergeBesuControllerBuilderTest.java | 21 +++-- .../QbftBesuControllerBuilderTest.java | 4 +- .../TransitionControllerBuilderTest.java | 10 +-- .../besu/util/EphemeryGenesisUpdaterTest.java | 24 +++--- ...esisConfigFile.java => GenesisConfig.java} | 32 ++++---- .../besu/config/CliqueConfigOptionsTest.java | 2 +- .../besu/config/GenesisConfigOptionsTest.java | 8 +- ...igFileTest.java => GenesisConfigTest.java} | 72 ++++++++-------- .../besu/config/JsonBftConfigOptionsTest.java | 2 +- .../clique/CliqueProtocolScheduleTest.java | 8 +- .../blockcreation/CliqueBlockCreatorTest.java | 6 +- .../CliqueMinerExecutorTest.java | 4 +- .../blockcreation/BftBlockCreatorTest.java | 5 +- .../merge/MergeProtocolScheduleTest.java | 12 +-- .../blockcreation/MergeCoordinatorTest.java | 4 +- .../MergeGenesisConfigHelper.java | 14 ++-- .../merge/blockcreation/MergeReorgTest.java | 6 +- .../qbft/support/TestContextBuilder.java | 4 +- .../api/jsonrpc/BlockchainImporter.java | 4 +- .../AbstractBlockCreatorTest.java | 8 +- .../AbstractBlockTransactionSelectorTest.java | 13 ++- ...FeeMarketBlockTransactionSelectorTest.java | 8 +- ...FeeMarketBlockTransactionSelectorTest.java | 8 +- .../blockcreation/PoWBlockCreatorTest.java | 38 ++++----- .../vm/TraceTransactionIntegrationTest.java | 5 +- .../operations/OperationBenchmarkHelper.java | 4 +- .../besu/ethereum/chain/GenesisState.java | 82 +++++++++---------- .../mainnet/feemarket/LondonFeeMarket.java | 5 +- .../ethereum/core/BlockchainSetupUtil.java | 16 ++-- .../core/ExecutionContextTestFixture.java | 22 ++--- .../core/ProtocolScheduleFixture.java | 4 +- .../fixed/FixedProtocolScheduleTest.java | 4 +- ...AbstractBlockProcessorIntegrationTest.java | 6 +- .../mainnet/MainnetProtocolScheduleTest.java | 8 +- .../bonsai/AbstractIsolationTests.java | 8 +- .../EthProtocolManagerTestBuilder.java | 15 ++-- .../eth/messages/BlockBodiesMessageTest.java | 4 +- .../eth/messages/BlockHeadersMessageTest.java | 4 +- .../eth/sync/ChainHeadTrackerTest.java | 4 +- .../AbstractTransactionPoolTestBase.java | 4 +- .../ethereum/eth/transactions/TestNode.java | 8 +- .../besu/evmtool/EvmToolCommand.java | 6 +- .../besu/evmtool/GenesisFileModule.java | 14 ++-- ...rtContractPermissioningControllerTest.java | 4 +- ...rtContractPermissioningControllerTest.java | 5 +- .../mainnet/DifficultyCalculatorTests.java | 4 +- 71 files changed, 439 insertions(+), 461 deletions(-) rename config/src/main/java/org/hyperledger/besu/config/{GenesisConfigFile.java => GenesisConfig.java} (89%) rename config/src/test/java/org/hyperledger/besu/config/{GenesisConfigFileTest.java => GenesisConfigTest.java} (89%) diff --git a/acceptance-tests/dsl/src/main/java/org/hyperledger/besu/tests/acceptance/dsl/condition/clique/CliqueConditions.java b/acceptance-tests/dsl/src/main/java/org/hyperledger/besu/tests/acceptance/dsl/condition/clique/CliqueConditions.java index 750e587f6e3..4490a2b2a2e 100644 --- a/acceptance-tests/dsl/src/main/java/org/hyperledger/besu/tests/acceptance/dsl/condition/clique/CliqueConditions.java +++ b/acceptance-tests/dsl/src/main/java/org/hyperledger/besu/tests/acceptance/dsl/condition/clique/CliqueConditions.java @@ -19,7 +19,7 @@ import static org.hyperledger.besu.tests.acceptance.dsl.transaction.clique.CliqueTransactions.LATEST; import org.hyperledger.besu.config.CliqueConfigOptions; -import org.hyperledger.besu.config.GenesisConfigFile; +import org.hyperledger.besu.config.GenesisConfig; import org.hyperledger.besu.datatypes.Address; import org.hyperledger.besu.tests.acceptance.dsl.condition.Condition; import org.hyperledger.besu.tests.acceptance.dsl.condition.blockchain.ExpectBlockNotCreated; @@ -89,9 +89,9 @@ public Condition awaitSignerSetChange(final Node node) { private int cliqueBlockPeriod(final BesuNode node) { final String config = node.getGenesisConfigProvider().create(emptyList()).get(); - final GenesisConfigFile genesisConfigFile = GenesisConfigFile.fromConfig(config); + final GenesisConfig genesisConfig = GenesisConfig.fromConfig(config); final CliqueConfigOptions cliqueConfigOptions = - genesisConfigFile.getConfigOptions().getCliqueConfigOptions(); + genesisConfig.getConfigOptions().getCliqueConfigOptions(); return cliqueConfigOptions.getBlockPeriodSeconds(); } diff --git a/acceptance-tests/dsl/src/main/java/org/hyperledger/besu/tests/acceptance/dsl/node/ThreadBesuNodeRunner.java b/acceptance-tests/dsl/src/main/java/org/hyperledger/besu/tests/acceptance/dsl/node/ThreadBesuNodeRunner.java index 3f0e0848c70..c18f71c4b09 100644 --- a/acceptance-tests/dsl/src/main/java/org/hyperledger/besu/tests/acceptance/dsl/node/ThreadBesuNodeRunner.java +++ b/acceptance-tests/dsl/src/main/java/org/hyperledger/besu/tests/acceptance/dsl/node/ThreadBesuNodeRunner.java @@ -25,7 +25,7 @@ import org.hyperledger.besu.cli.config.EthNetworkConfig; import org.hyperledger.besu.cli.config.NetworkName; import org.hyperledger.besu.components.BesuComponent; -import org.hyperledger.besu.config.GenesisConfigFile; +import org.hyperledger.besu.config.GenesisConfig; import org.hyperledger.besu.controller.BesuController; import org.hyperledger.besu.controller.BesuControllerBuilder; import org.hyperledger.besu.crypto.KeyPairUtil; @@ -155,8 +155,8 @@ public void startNode(final BesuNode node) { networkConfigBuilder.setBootNodes(bootnodes); node.getConfiguration() .getGenesisConfig() - .map(GenesisConfigFile::fromConfig) - .ifPresent(networkConfigBuilder::setGenesisConfigFile); + .map(GenesisConfig::fromConfig) + .ifPresent(networkConfigBuilder::setGenesisConfig); final EthNetworkConfig ethNetworkConfig = networkConfigBuilder.build(); final BesuControllerBuilder builder = component.besuControllerBuilder(); builder.isRevertReasonEnabled(node.isRevertReasonEnabled()); @@ -166,9 +166,7 @@ public void startNode(final BesuNode node) { builder.nodeKey(new NodeKey(new KeyPairSecurityModule(KeyPairUtil.loadKeyPair(dataDir)))); builder.privacyParameters(node.getPrivacyParameters()); - node.getGenesisConfig() - .map(GenesisConfigFile::fromConfig) - .ifPresent(builder::genesisConfigFile); + node.getGenesisConfig().map(GenesisConfig::fromConfig).ifPresent(builder::genesisConfig); final BesuController besuController = component.besuController(); diff --git a/besu/src/main/java/org/hyperledger/besu/cli/BesuCommand.java b/besu/src/main/java/org/hyperledger/besu/cli/BesuCommand.java index 21cb787f52b..5f7047dcae3 100644 --- a/besu/src/main/java/org/hyperledger/besu/cli/BesuCommand.java +++ b/besu/src/main/java/org/hyperledger/besu/cli/BesuCommand.java @@ -85,7 +85,7 @@ import org.hyperledger.besu.cli.util.VersionProvider; import org.hyperledger.besu.components.BesuComponent; import org.hyperledger.besu.config.CheckpointConfigOptions; -import org.hyperledger.besu.config.GenesisConfigFile; +import org.hyperledger.besu.config.GenesisConfig; import org.hyperledger.besu.config.GenesisConfigOptions; import org.hyperledger.besu.config.MergeConfiguration; import org.hyperledger.besu.controller.BesuController; @@ -332,8 +332,8 @@ public class BesuCommand implements DefaultCommandValues, Runnable { new PreSynchronizationTaskRunner(); private final Set allocatedPorts = new HashSet<>(); - private final Supplier genesisConfigFileSupplier = - Suppliers.memoize(this::readGenesisConfigFile); + private final Supplier genesisConfigSupplier = + Suppliers.memoize(this::readGenesisConfig); private final Supplier genesisConfigOptionsSupplier = Suppliers.memoize(this::readGenesisConfigOptions); private final Supplier miningParametersSupplier = @@ -1587,21 +1587,21 @@ private void validateChainDataPruningParams() { } } - private GenesisConfigFile readGenesisConfigFile() { - GenesisConfigFile effectiveGenesisFile; + private GenesisConfig readGenesisConfig() { + GenesisConfig effectiveGenesisFile; effectiveGenesisFile = network.equals(EPHEMERY) ? EphemeryGenesisUpdater.updateGenesis(genesisConfigOverrides) : genesisFile != null - ? GenesisConfigFile.fromSource(genesisConfigSource(genesisFile)) - : GenesisConfigFile.fromResource( + ? GenesisConfig.fromSource(genesisConfigSource(genesisFile)) + : GenesisConfig.fromResource( Optional.ofNullable(network).orElse(MAINNET).getGenesisFile()); return effectiveGenesisFile.withOverrides(genesisConfigOverrides); } private GenesisConfigOptions readGenesisConfigOptions() { try { - return genesisConfigFileSupplier.get().getConfigOptions(); + return genesisConfigSupplier.get().getConfigOptions(); } catch (final Exception e) { throw new ParameterException( this.commandLine, "Unable to load genesis file. " + e.getCause()); @@ -2337,7 +2337,7 @@ private EthNetworkConfig updateNetworkConfig(final NetworkName network) { builder.setDnsDiscoveryUrl(null); } - builder.setGenesisConfigFile(genesisConfigFileSupplier.get()); + builder.setGenesisConfig(genesisConfigSupplier.get()); if (networkId != null) { builder.setNetworkId(networkId); diff --git a/besu/src/main/java/org/hyperledger/besu/cli/config/EthNetworkConfig.java b/besu/src/main/java/org/hyperledger/besu/cli/config/EthNetworkConfig.java index dab3a4c227c..0a8d86c795a 100644 --- a/besu/src/main/java/org/hyperledger/besu/cli/config/EthNetworkConfig.java +++ b/besu/src/main/java/org/hyperledger/besu/cli/config/EthNetworkConfig.java @@ -14,7 +14,7 @@ */ package org.hyperledger.besu.cli.config; -import org.hyperledger.besu.config.GenesisConfigFile; +import org.hyperledger.besu.config.GenesisConfig; import org.hyperledger.besu.config.GenesisConfigOptions; import org.hyperledger.besu.ethereum.p2p.peers.EnodeURLImpl; import org.hyperledger.besu.plugin.data.EnodeURL; @@ -33,13 +33,13 @@ /** * The Eth network config. * - * @param genesisConfigFile Genesis Config File + * @param genesisConfig Genesis Config File * @param networkId Network Id * @param bootNodes Boot Nodes * @param dnsDiscoveryUrl DNS Discovery URL */ public record EthNetworkConfig( - GenesisConfigFile genesisConfigFile, + GenesisConfig genesisConfig, BigInteger networkId, List bootNodes, String dnsDiscoveryUrl) { @@ -47,7 +47,7 @@ public record EthNetworkConfig( /** * Validate parameters on new record creation * - * @param genesisConfigFile the genesis config + * @param genesisConfig the genesis config * @param networkId the network id * @param bootNodes the boot nodes * @param dnsDiscoveryUrl the dns discovery url @@ -55,7 +55,7 @@ public record EthNetworkConfig( @SuppressWarnings( "MethodInputParametersMustBeFinal") // needed since record constructors are not yet supported public EthNetworkConfig { - Objects.requireNonNull(genesisConfigFile); + Objects.requireNonNull(genesisConfig); Objects.requireNonNull(bootNodes); } @@ -67,8 +67,8 @@ public record EthNetworkConfig( */ public static EthNetworkConfig getNetworkConfig(final NetworkName networkName) { final URL genesisSource = jsonConfigSource(networkName.getGenesisFile()); - final GenesisConfigFile genesisConfigFile = GenesisConfigFile.fromSource(genesisSource); - final GenesisConfigOptions genesisConfigOptions = genesisConfigFile.getConfigOptions(); + final GenesisConfig genesisConfig = GenesisConfig.fromSource(genesisSource); + final GenesisConfigOptions genesisConfigOptions = genesisConfig.getConfigOptions(); final Optional> rawBootNodes = genesisConfigOptions.getDiscoveryOptions().getBootNodes(); final List bootNodes = @@ -79,7 +79,7 @@ public static EthNetworkConfig getNetworkConfig(final NetworkName networkName) { .orElse(Collections.emptyList()); return new EthNetworkConfig( - genesisConfigFile, + genesisConfig, networkName.getNetworkId(), bootNodes, genesisConfigOptions.getDiscoveryOptions().getDiscoveryDnsUrl().orElse(null)); @@ -108,7 +108,7 @@ public static String jsonConfig(final NetworkName network) { public static class Builder { private String dnsDiscoveryUrl; - private GenesisConfigFile genesisConfigFile; + private GenesisConfig genesisConfig; private BigInteger networkId; private List bootNodes; @@ -118,7 +118,7 @@ public static class Builder { * @param ethNetworkConfig the eth network config */ public Builder(final EthNetworkConfig ethNetworkConfig) { - this.genesisConfigFile = ethNetworkConfig.genesisConfigFile; + this.genesisConfig = ethNetworkConfig.genesisConfig; this.networkId = ethNetworkConfig.networkId; this.bootNodes = ethNetworkConfig.bootNodes; this.dnsDiscoveryUrl = ethNetworkConfig.dnsDiscoveryUrl; @@ -127,11 +127,11 @@ public Builder(final EthNetworkConfig ethNetworkConfig) { /** * Sets genesis config file. * - * @param genesisConfigFile the genesis config + * @param genesisConfig the genesis config * @return this builder */ - public Builder setGenesisConfigFile(final GenesisConfigFile genesisConfigFile) { - this.genesisConfigFile = genesisConfigFile; + public Builder setGenesisConfig(final GenesisConfig genesisConfig) { + this.genesisConfig = genesisConfig; return this; } @@ -174,7 +174,7 @@ public Builder setDnsDiscoveryUrl(final String dnsDiscoveryUrl) { * @return the eth network config */ public EthNetworkConfig build() { - return new EthNetworkConfig(genesisConfigFile, networkId, bootNodes, dnsDiscoveryUrl); + return new EthNetworkConfig(genesisConfig, networkId, bootNodes, dnsDiscoveryUrl); } } } diff --git a/besu/src/main/java/org/hyperledger/besu/cli/subcommands/operator/GenerateBlockchainConfig.java b/besu/src/main/java/org/hyperledger/besu/cli/subcommands/operator/GenerateBlockchainConfig.java index d71cf652a5f..368f6da3800 100644 --- a/besu/src/main/java/org/hyperledger/besu/cli/subcommands/operator/GenerateBlockchainConfig.java +++ b/besu/src/main/java/org/hyperledger/besu/cli/subcommands/operator/GenerateBlockchainConfig.java @@ -19,7 +19,7 @@ import org.hyperledger.besu.cli.DefaultCommandValues; import org.hyperledger.besu.cli.util.VersionProvider; -import org.hyperledger.besu.config.GenesisConfigFile; +import org.hyperledger.besu.config.GenesisConfig; import org.hyperledger.besu.config.GenesisConfigOptions; import org.hyperledger.besu.config.JsonGenesisConfigOptions; import org.hyperledger.besu.config.JsonUtil; @@ -286,7 +286,7 @@ private void parseConfig() throws IOException { /** Sets the selected signature algorithm instance in SignatureAlgorithmFactory. */ private void processEcCurve() { - GenesisConfigOptions options = GenesisConfigFile.fromConfig(genesisConfig).getConfigOptions(); + GenesisConfigOptions options = GenesisConfig.fromConfig(genesisConfig).getConfigOptions(); Optional ecCurve = options.getEcCurve(); if (ecCurve.isEmpty()) { diff --git a/besu/src/main/java/org/hyperledger/besu/controller/BesuController.java b/besu/src/main/java/org/hyperledger/besu/controller/BesuController.java index 25a306d3a29..700b414edce 100644 --- a/besu/src/main/java/org/hyperledger/besu/controller/BesuController.java +++ b/besu/src/main/java/org/hyperledger/besu/controller/BesuController.java @@ -15,7 +15,7 @@ package org.hyperledger.besu.controller; import org.hyperledger.besu.cli.config.EthNetworkConfig; -import org.hyperledger.besu.config.GenesisConfigFile; +import org.hyperledger.besu.config.GenesisConfig; import org.hyperledger.besu.config.GenesisConfigOptions; import org.hyperledger.besu.config.PowAlgorithm; import org.hyperledger.besu.config.QbftConfigOptions; @@ -334,24 +334,24 @@ public Builder() {} */ public BesuControllerBuilder fromEthNetworkConfig( final EthNetworkConfig ethNetworkConfig, final SyncMode syncMode) { - return fromGenesisFile(ethNetworkConfig.genesisConfigFile(), syncMode) + return fromGenesisFile(ethNetworkConfig.genesisConfig(), syncMode) .networkId(ethNetworkConfig.networkId()); } /** * From genesis config besu controller builder. * - * @param genesisConfigFile the genesis config file + * @param genesisConfig the genesis config file * @param syncMode the sync mode * @return the besu controller builder */ public BesuControllerBuilder fromGenesisFile( - final GenesisConfigFile genesisConfigFile, final SyncMode syncMode) { + final GenesisConfig genesisConfig, final SyncMode syncMode) { final BesuControllerBuilder builder; - final var configOptions = genesisConfigFile.getConfigOptions(); + final var configOptions = genesisConfig.getConfigOptions(); if (configOptions.isConsensusMigration()) { - return createConsensusScheduleBesuControllerBuilder(genesisConfigFile); + return createConsensusScheduleBesuControllerBuilder(genesisConfig); } if (configOptions.getPowAlgorithm() != PowAlgorithm.UNSUPPORTED) { @@ -373,22 +373,22 @@ public BesuControllerBuilder fromGenesisFile( if (configOptions.getTerminalTotalDifficulty().isPresent()) { // Enable start with vanilla MergeBesuControllerBuilder for PoS checkpoint block if (syncMode == SyncMode.CHECKPOINT && isCheckpointPoSBlock(configOptions)) { - return new MergeBesuControllerBuilder().genesisConfigFile(genesisConfigFile); + return new MergeBesuControllerBuilder().genesisConfig(genesisConfig); } else { // TODO this should be changed to vanilla MergeBesuControllerBuilder and the Transition* // series of classes removed after we successfully transition to PoS // https://github.com/hyperledger/besu/issues/2897 return new TransitionBesuControllerBuilder(builder, new MergeBesuControllerBuilder()) - .genesisConfigFile(genesisConfigFile); + .genesisConfig(genesisConfig); } - } else return builder.genesisConfigFile(genesisConfigFile); + } else return builder.genesisConfig(genesisConfig); } private BesuControllerBuilder createConsensusScheduleBesuControllerBuilder( - final GenesisConfigFile genesisConfigFile) { + final GenesisConfig genesisConfig) { final Map besuControllerBuilderSchedule = new HashMap<>(); - final var configOptions = genesisConfigFile.getConfigOptions(); + final var configOptions = genesisConfig.getConfigOptions(); final BesuControllerBuilder originalControllerBuilder; if (configOptions.isIbft2()) { @@ -407,7 +407,7 @@ private BesuControllerBuilder createConsensusScheduleBesuControllerBuilder( besuControllerBuilderSchedule.put(qbftBlock, new QbftBesuControllerBuilder()); return new ConsensusScheduleBesuControllerBuilder(besuControllerBuilderSchedule) - .genesisConfigFile(genesisConfigFile); + .genesisConfig(genesisConfig); } private Long readQbftStartBlockConfig(final QbftConfigOptions qbftConfigOptions) { diff --git a/besu/src/main/java/org/hyperledger/besu/controller/BesuControllerBuilder.java b/besu/src/main/java/org/hyperledger/besu/controller/BesuControllerBuilder.java index 258cf95ca35..9498f7b2d92 100644 --- a/besu/src/main/java/org/hyperledger/besu/controller/BesuControllerBuilder.java +++ b/besu/src/main/java/org/hyperledger/besu/controller/BesuControllerBuilder.java @@ -18,7 +18,7 @@ import org.hyperledger.besu.components.BesuComponent; import org.hyperledger.besu.config.CheckpointConfigOptions; -import org.hyperledger.besu.config.GenesisConfigFile; +import org.hyperledger.besu.config.GenesisConfig; import org.hyperledger.besu.config.GenesisConfigOptions; import org.hyperledger.besu.consensus.merge.MergeContext; import org.hyperledger.besu.consensus.merge.UnverifiedForkchoiceSupplier; @@ -127,7 +127,7 @@ public abstract class BesuControllerBuilder implements MiningParameterOverrides private static final Logger LOG = LoggerFactory.getLogger(BesuControllerBuilder.class); /** The genesis file */ - protected GenesisConfigFile genesisConfigFile; + protected GenesisConfig genesisConfig; /** The genesis config options; */ protected GenesisConfigOptions genesisConfigOptions; @@ -250,8 +250,8 @@ public BesuControllerBuilder storageProvider(final StorageProvider storageProvid * @param genesisConfig the genesis config * @return the besu controller builder */ - public BesuControllerBuilder genesisConfigFile(final GenesisConfigFile genesisConfig) { - this.genesisConfigFile = genesisConfig; + public BesuControllerBuilder genesisConfig(final GenesisConfig genesisConfig) { + this.genesisConfig = genesisConfig; this.genesisConfigOptions = genesisConfig.getConfigOptions(); return this; } @@ -559,7 +559,7 @@ public BesuControllerBuilder isParallelTxProcessingEnabled( * @return the besu controller */ public BesuController build() { - checkNotNull(genesisConfigFile, "Missing genesis config file"); + checkNotNull(genesisConfig, "Missing genesis config file"); checkNotNull(genesisConfigOptions, "Missing genesis config options"); checkNotNull(syncConfig, "Missing sync config"); checkNotNull(ethereumWireProtocolConfiguration, "Missing ethereum protocol configuration"); @@ -840,11 +840,10 @@ private GenesisState getGenesisState( return maybeGenesisStateRoot .map( genesisStateRoot -> - GenesisState.fromStorage(genesisStateRoot, genesisConfigFile, protocolSchedule)) + GenesisState.fromStorage(genesisStateRoot, genesisConfig, protocolSchedule)) .orElseGet( () -> - GenesisState.fromConfig( - dataStorageConfiguration, genesisConfigFile, protocolSchedule)); + GenesisState.fromConfig(dataStorageConfiguration, genesisConfig, protocolSchedule)); } private TrieLogPruner createTrieLogPruner( diff --git a/besu/src/main/java/org/hyperledger/besu/controller/ConsensusScheduleBesuControllerBuilder.java b/besu/src/main/java/org/hyperledger/besu/controller/ConsensusScheduleBesuControllerBuilder.java index 31f84b6ae04..0b7299cedb5 100644 --- a/besu/src/main/java/org/hyperledger/besu/controller/ConsensusScheduleBesuControllerBuilder.java +++ b/besu/src/main/java/org/hyperledger/besu/controller/ConsensusScheduleBesuControllerBuilder.java @@ -16,7 +16,7 @@ import static org.hyperledger.besu.ethereum.core.BlockHeader.GENESIS_BLOCK_NUMBER; -import org.hyperledger.besu.config.GenesisConfigFile; +import org.hyperledger.besu.config.GenesisConfig; import org.hyperledger.besu.consensus.common.CombinedProtocolScheduleFactory; import org.hyperledger.besu.consensus.common.ForkSpec; import org.hyperledger.besu.consensus.common.ForksSchedule; @@ -264,9 +264,9 @@ public BesuControllerBuilder storageProvider(final StorageProvider storageProvid } @Override - public BesuControllerBuilder genesisConfigFile(final GenesisConfigFile genesisConfig) { - besuControllerBuilderSchedule.values().forEach(b -> b.genesisConfigFile(genesisConfig)); - return super.genesisConfigFile(genesisConfig); + public BesuControllerBuilder genesisConfig(final GenesisConfig genesisConfig) { + besuControllerBuilderSchedule.values().forEach(b -> b.genesisConfig(genesisConfig)); + return super.genesisConfig(genesisConfig); } @Override diff --git a/besu/src/main/java/org/hyperledger/besu/controller/TransitionBesuControllerBuilder.java b/besu/src/main/java/org/hyperledger/besu/controller/TransitionBesuControllerBuilder.java index 4f078fda286..9d37f594e8a 100644 --- a/besu/src/main/java/org/hyperledger/besu/controller/TransitionBesuControllerBuilder.java +++ b/besu/src/main/java/org/hyperledger/besu/controller/TransitionBesuControllerBuilder.java @@ -14,7 +14,7 @@ */ package org.hyperledger.besu.controller; -import org.hyperledger.besu.config.GenesisConfigFile; +import org.hyperledger.besu.config.GenesisConfig; import org.hyperledger.besu.consensus.merge.MergeContext; import org.hyperledger.besu.consensus.merge.PostMergeContext; import org.hyperledger.besu.consensus.merge.TransitionBackwardSyncContext; @@ -301,9 +301,9 @@ public BesuControllerBuilder evmConfiguration(final EvmConfiguration evmConfigur } @Override - public BesuControllerBuilder genesisConfigFile(final GenesisConfigFile genesisConfig) { - super.genesisConfigFile(genesisConfig); - return propagateConfig(z -> z.genesisConfigFile(genesisConfig)); + public BesuControllerBuilder genesisConfig(final GenesisConfig genesisConfig) { + super.genesisConfig(genesisConfig); + return propagateConfig(z -> z.genesisConfig(genesisConfig)); } @Override diff --git a/besu/src/main/java/org/hyperledger/besu/util/EphemeryGenesisUpdater.java b/besu/src/main/java/org/hyperledger/besu/util/EphemeryGenesisUpdater.java index 0b970a6809c..c022f84adae 100644 --- a/besu/src/main/java/org/hyperledger/besu/util/EphemeryGenesisUpdater.java +++ b/besu/src/main/java/org/hyperledger/besu/util/EphemeryGenesisUpdater.java @@ -16,7 +16,7 @@ import static org.hyperledger.besu.cli.config.NetworkName.EPHEMERY; -import org.hyperledger.besu.config.GenesisConfigFile; +import org.hyperledger.besu.config.GenesisConfig; import java.io.IOException; import java.math.BigInteger; @@ -46,16 +46,16 @@ public EphemeryGenesisUpdater() {} * @return the updated GenesisConfigFile * @throws RuntimeException if an error occurs during the update process */ - public static GenesisConfigFile updateGenesis(final Map overrides) + public static GenesisConfig updateGenesis(final Map overrides) throws RuntimeException { - GenesisConfigFile genesisConfigFile; + GenesisConfig genesisConfig; try { if (EPHEMERY.getGenesisFile() == null) { throw new IOException("Genesis file or config options are null"); } - genesisConfigFile = GenesisConfigFile.fromResource(EPHEMERY.getGenesisFile()); - long genesisTimestamp = genesisConfigFile.getTimestamp(); - Optional genesisChainId = genesisConfigFile.getConfigOptions().getChainId(); + genesisConfig = GenesisConfig.fromResource(EPHEMERY.getGenesisFile()); + long genesisTimestamp = genesisConfig.getTimestamp(); + Optional genesisChainId = genesisConfig.getConfigOptions().getChainId(); long currentTimestamp = Instant.now().getEpochSecond(); long periodsSinceGenesis = ChronoUnit.DAYS.between(Instant.ofEpochSecond(genesisTimestamp), Instant.now()) @@ -71,9 +71,9 @@ public static GenesisConfigFile updateGenesis(final Map override if (currentTimestamp > (genesisTimestamp + PERIOD_IN_SECONDS)) { overrides.put("chainId", String.valueOf(updatedChainId)); overrides.put("timestamp", String.valueOf(updatedTimestamp)); - genesisConfigFile = genesisConfigFile.withOverrides(overrides); + genesisConfig = genesisConfig.withOverrides(overrides); } - return genesisConfigFile.withOverrides(overrides); + return genesisConfig.withOverrides(overrides); } catch (IOException e) { throw new RuntimeException("Error updating ephemery genesis: " + e.getMessage(), e); } diff --git a/besu/src/test/java/org/hyperledger/besu/FlexGroupPrivacyTest.java b/besu/src/test/java/org/hyperledger/besu/FlexGroupPrivacyTest.java index bad87162fd2..5298633ff9b 100644 --- a/besu/src/test/java/org/hyperledger/besu/FlexGroupPrivacyTest.java +++ b/besu/src/test/java/org/hyperledger/besu/FlexGroupPrivacyTest.java @@ -22,7 +22,7 @@ import org.hyperledger.besu.components.MockBesuCommandModule; import org.hyperledger.besu.components.NoOpMetricsSystemModule; import org.hyperledger.besu.components.PrivacyTestModule; -import org.hyperledger.besu.config.GenesisConfigFile; +import org.hyperledger.besu.config.GenesisConfig; import org.hyperledger.besu.controller.BesuController; import org.hyperledger.besu.cryptoservices.NodeKeyUtils; import org.hyperledger.besu.datatypes.Address; @@ -146,7 +146,7 @@ BesuController provideBesuController( @Named("dataDir") final Path dataDir) { return new BesuController.Builder() - .fromGenesisFile(GenesisConfigFile.mainnet(), SyncMode.FULL) + .fromGenesisFile(GenesisConfig.mainnet(), SyncMode.FULL) .synchronizerConfiguration(SynchronizerConfiguration.builder().build()) .ethProtocolConfiguration(EthProtocolConfiguration.defaultConfig()) .storageProvider(new InMemoryKeyValueStorageProvider()) diff --git a/besu/src/test/java/org/hyperledger/besu/ForkIdsNetworkConfigTest.java b/besu/src/test/java/org/hyperledger/besu/ForkIdsNetworkConfigTest.java index 87bab916f23..e4ac7d5b5fc 100644 --- a/besu/src/test/java/org/hyperledger/besu/ForkIdsNetworkConfigTest.java +++ b/besu/src/test/java/org/hyperledger/besu/ForkIdsNetworkConfigTest.java @@ -20,7 +20,7 @@ import static org.mockito.Mockito.when; import org.hyperledger.besu.cli.config.NetworkName; -import org.hyperledger.besu.config.GenesisConfigFile; +import org.hyperledger.besu.config.GenesisConfig; import org.hyperledger.besu.config.GenesisConfigOptions; import org.hyperledger.besu.consensus.merge.MergeProtocolSchedule; import org.hyperledger.besu.consensus.merge.PostMergeContext; @@ -133,10 +133,9 @@ public static Collection parameters() { @ParameterizedTest @MethodSource("parameters") public void testForkId(final NetworkName chainName, final List expectedForkIds) { - final GenesisConfigFile genesisConfigFile = - GenesisConfigFile.fromResource(chainName.getGenesisFile()); - final MilestoneStreamingTransitionProtocolSchedule schedule = createSchedule(genesisConfigFile); - final GenesisState genesisState = GenesisState.fromConfig(genesisConfigFile, schedule); + final GenesisConfig genesisConfig = GenesisConfig.fromResource(chainName.getGenesisFile()); + final MilestoneStreamingTransitionProtocolSchedule schedule = createSchedule(genesisConfig); + final GenesisState genesisState = GenesisState.fromConfig(genesisConfig, schedule); final Blockchain mockBlockchain = mock(Blockchain.class); final BlockHeader mockBlockHeader = mock(BlockHeader.class); @@ -150,8 +149,8 @@ public void testForkId(final NetworkName chainName, final List expectedF final ForkIdManager forkIdManager = new ForkIdManager( mockBlockchain, - genesisConfigFile.getForkBlockNumbers(), - genesisConfigFile.getForkTimestamps(), + genesisConfig.getForkBlockNumbers(), + genesisConfig.getForkTimestamps(), false); final List actualForkIds = @@ -167,8 +166,8 @@ public void testForkId(final NetworkName chainName, final List expectedF } private static MilestoneStreamingTransitionProtocolSchedule createSchedule( - final GenesisConfigFile genesisConfigFile) { - final GenesisConfigOptions configOptions = genesisConfigFile.getConfigOptions(); + final GenesisConfig genesisConfig) { + final GenesisConfigOptions configOptions = genesisConfig.getConfigOptions(); MilestoneStreamingProtocolSchedule preMergeProtocolSchedule = new MilestoneStreamingProtocolSchedule( (DefaultProtocolSchedule) diff --git a/besu/src/test/java/org/hyperledger/besu/PrivacyReorgTest.java b/besu/src/test/java/org/hyperledger/besu/PrivacyReorgTest.java index beff4b8586b..6ddaa618635 100644 --- a/besu/src/test/java/org/hyperledger/besu/PrivacyReorgTest.java +++ b/besu/src/test/java/org/hyperledger/besu/PrivacyReorgTest.java @@ -27,7 +27,7 @@ import org.hyperledger.besu.components.MockBesuCommandModule; import org.hyperledger.besu.components.NoOpMetricsSystemModule; import org.hyperledger.besu.components.PrivacyTestModule; -import org.hyperledger.besu.config.GenesisConfigFile; +import org.hyperledger.besu.config.GenesisConfig; import org.hyperledger.besu.controller.BesuController; import org.hyperledger.besu.crypto.KeyPair; import org.hyperledger.besu.crypto.SignatureAlgorithm; @@ -535,7 +535,7 @@ static class PrivacyReorgTestBesuControllerModule { @SuppressWarnings("CloseableProvides") BesuController provideBesuController( final PrivacyParameters privacyParameters, - final GenesisConfigFile genesisConfigFile, + final GenesisConfig genesisConfig, final PrivacyReorgTestComponent context, final @Named("dataDir") Path dataDir) { @@ -543,7 +543,7 @@ BesuController provideBesuController( // named privacyReorgParams BesuController retval = new BesuController.Builder() - .fromGenesisFile(genesisConfigFile, SyncMode.FULL) + .fromGenesisFile(genesisConfig, SyncMode.FULL) .synchronizerConfiguration(SynchronizerConfiguration.builder().build()) .ethProtocolConfiguration(EthProtocolConfiguration.defaultConfig()) .storageProvider(new InMemoryKeyValueStorageProvider()) @@ -568,8 +568,8 @@ BesuController provideBesuController( @Module static class PrivacyReorgTestGenesisConfigModule { @Provides - GenesisConfigFile providePrivacyReorgGenesisConfigFile() { - return GenesisConfigFile.fromResource("/privacy_reorg_genesis.json"); + GenesisConfig providePrivacyReorgGenesisConfig() { + return GenesisConfig.fromResource("/privacy_reorg_genesis.json"); } } } diff --git a/besu/src/test/java/org/hyperledger/besu/PrivacyTest.java b/besu/src/test/java/org/hyperledger/besu/PrivacyTest.java index 3e905d94416..32f2b1f6176 100644 --- a/besu/src/test/java/org/hyperledger/besu/PrivacyTest.java +++ b/besu/src/test/java/org/hyperledger/besu/PrivacyTest.java @@ -23,7 +23,7 @@ import org.hyperledger.besu.components.NoOpMetricsSystemModule; import org.hyperledger.besu.components.PrivacyParametersModule; import org.hyperledger.besu.components.PrivacyTestModule; -import org.hyperledger.besu.config.GenesisConfigFile; +import org.hyperledger.besu.config.GenesisConfig; import org.hyperledger.besu.controller.BesuController; import org.hyperledger.besu.cryptoservices.NodeKeyUtils; import org.hyperledger.besu.datatypes.Address; @@ -121,7 +121,7 @@ BesuController provideBesuController( @Named("dataDir") final Path dataDir) { return new BesuController.Builder() - .fromGenesisFile(GenesisConfigFile.mainnet(), SyncMode.FULL) + .fromGenesisFile(GenesisConfig.mainnet(), SyncMode.FULL) .synchronizerConfiguration(SynchronizerConfiguration.builder().build()) .ethProtocolConfiguration(EthProtocolConfiguration.defaultConfig()) .storageProvider(new InMemoryKeyValueStorageProvider()) diff --git a/besu/src/test/java/org/hyperledger/besu/RunnerTest.java b/besu/src/test/java/org/hyperledger/besu/RunnerTest.java index cf995c25e07..2fc89285668 100644 --- a/besu/src/test/java/org/hyperledger/besu/RunnerTest.java +++ b/besu/src/test/java/org/hyperledger/besu/RunnerTest.java @@ -26,7 +26,7 @@ import org.hyperledger.besu.cli.config.EthNetworkConfig; import org.hyperledger.besu.components.BesuComponent; -import org.hyperledger.besu.config.GenesisConfigFile; +import org.hyperledger.besu.config.GenesisConfig; import org.hyperledger.besu.config.JsonUtil; import org.hyperledger.besu.config.MergeConfiguration; import org.hyperledger.besu.controller.BesuController; @@ -181,9 +181,7 @@ public void fastSyncFromGenesisUsingPeerTaskSystem() throws Exception { } private void syncFromGenesis( - final SyncMode mode, - final GenesisConfigFile genesisConfig, - final boolean isPeerTaskSystemEnabled) + final SyncMode mode, final GenesisConfig genesisConfig, final boolean isPeerTaskSystemEnabled) throws Exception { final Path dataDirAhead = Files.createTempDirectory(temp, "db-ahead"); final Path dbAhead = dataDirAhead.resolve("database"); @@ -270,7 +268,7 @@ private void syncFromGenesis( final EnodeURL aheadEnode = runnerAhead.getLocalEnode().get(); final EthNetworkConfig behindEthNetworkConfiguration = new EthNetworkConfig( - GenesisConfigFile.fromResource(DEV.getGenesisFile()), + GenesisConfig.fromResource(DEV.getGenesisFile()), DEV.getNetworkId(), Collections.singletonList(aheadEnode), null); @@ -395,11 +393,10 @@ private Request getRequest(final String method, final String baseUrl) { .build(); } - private GenesisConfigFile getFastSyncGenesis() throws IOException { + private GenesisConfig getFastSyncGenesis() throws IOException { final ObjectNode jsonNode = (ObjectNode) - new ObjectMapper() - .readTree(GenesisConfigFile.class.getResource(MAINNET.getGenesisFile())); + new ObjectMapper().readTree(GenesisConfig.class.getResource(MAINNET.getGenesisFile())); final Optional configNode = JsonUtil.getObjectNode(jsonNode, "config"); configNode.ifPresent( (node) -> { @@ -408,7 +405,7 @@ private GenesisConfigFile getFastSyncGenesis() throws IOException { // remove merge terminal difficulty for fast sync in the absence of a CL mock node.remove("terminalTotalDifficulty"); }); - return GenesisConfigFile.fromConfig(jsonNode); + return GenesisConfig.fromConfig(jsonNode); } private StorageProvider createKeyValueStorageProvider( @@ -482,7 +479,7 @@ private static void setupState( } private BesuController getController( - final GenesisConfigFile genesisConfig, + final GenesisConfig genesisConfig, final SynchronizerConfiguration syncConfig, final Path dataDir, final NodeKey nodeKey, @@ -490,7 +487,7 @@ private BesuController getController( final ObservableMetricsSystem metricsSystem, final MiningConfiguration miningConfiguration) { return new MainnetBesuControllerBuilder() - .genesisConfigFile(genesisConfig) + .genesisConfig(genesisConfig) .synchronizerConfiguration(syncConfig) .ethProtocolConfiguration(EthProtocolConfiguration.defaultConfig()) .dataDirectory(dataDir) diff --git a/besu/src/test/java/org/hyperledger/besu/chainimport/JsonBlockImporterTest.java b/besu/src/test/java/org/hyperledger/besu/chainimport/JsonBlockImporterTest.java index 383ef1a3a1a..1b1c914d411 100644 --- a/besu/src/test/java/org/hyperledger/besu/chainimport/JsonBlockImporterTest.java +++ b/besu/src/test/java/org/hyperledger/besu/chainimport/JsonBlockImporterTest.java @@ -21,7 +21,7 @@ import org.hyperledger.besu.components.BesuCommandModule; import org.hyperledger.besu.components.BesuComponent; import org.hyperledger.besu.components.BesuPluginContextModule; -import org.hyperledger.besu.config.GenesisConfigFile; +import org.hyperledger.besu.config.GenesisConfig; import org.hyperledger.besu.config.JsonUtil; import org.hyperledger.besu.controller.BesuController; import org.hyperledger.besu.cryptoservices.NodeKeyUtils; @@ -78,14 +78,14 @@ public abstract class JsonBlockImporterTest { @TempDir public Path dataDir; protected String consensusEngine; - protected GenesisConfigFile genesisConfigFile; + protected GenesisConfig genesisConfig; protected boolean isEthash; protected void setup(final String consensusEngine) throws IOException { this.consensusEngine = consensusEngine; final String genesisData = getFileContents("genesis.json"); - this.genesisConfigFile = GenesisConfigFile.fromConfig(genesisData); - this.isEthash = genesisConfigFile.getConfigOptions().isEthHash(); + this.genesisConfig = GenesisConfig.fromConfig(genesisData); + this.isEthash = genesisConfig.getConfigOptions().isEthHash(); } public static class SingletonTests extends JsonBlockImporterTest { @@ -106,7 +106,7 @@ public void importChain_unsupportedConsensusAlgorithm() throws IOException { .isInstanceOf(IllegalArgumentException.class) .hasMessage( "Unable to create block using current consensus engine: " - + genesisConfigFile.getConfigOptions().getConsensusEngine()); + + genesisConfig.getConfigOptions().getConsensusEngine()); } } @@ -419,7 +419,7 @@ public void importChain_specialFields(final String consensusEngine) throws IOExc .isInstanceOf(IllegalArgumentException.class) .hasMessage( "Some fields (coinbase, extraData) are unsupported by the current consensus engine: " - + genesisConfigFile.getConfigOptions().getConsensusEngine()); + + genesisConfig.getConfigOptions().getConsensusEngine()); } } @@ -448,12 +448,12 @@ protected String getFileContents(final String folder, final String filename) thr } protected BesuController createController() throws IOException { - return createController(genesisConfigFile); + return createController(genesisConfig); } - protected BesuController createController(final GenesisConfigFile genesisConfigFile) { + protected BesuController createController(final GenesisConfig genesisConfig) { return new BesuController.Builder() - .fromGenesisFile(genesisConfigFile, SyncMode.FAST) + .fromGenesisFile(genesisConfig, SyncMode.FAST) .synchronizerConfiguration(SynchronizerConfiguration.builder().build()) .ethProtocolConfiguration(EthProtocolConfiguration.defaultConfig()) .storageProvider(new InMemoryKeyValueStorageProvider()) diff --git a/besu/src/test/java/org/hyperledger/besu/cli/BesuCommandTest.java b/besu/src/test/java/org/hyperledger/besu/cli/BesuCommandTest.java index eb789478b9a..a8bcde0e27d 100644 --- a/besu/src/test/java/org/hyperledger/besu/cli/BesuCommandTest.java +++ b/besu/src/test/java/org/hyperledger/besu/cli/BesuCommandTest.java @@ -46,7 +46,7 @@ import org.hyperledger.besu.BesuInfo; import org.hyperledger.besu.cli.config.EthNetworkConfig; import org.hyperledger.besu.cli.config.NetworkName; -import org.hyperledger.besu.config.GenesisConfigFile; +import org.hyperledger.besu.config.GenesisConfig; import org.hyperledger.besu.config.MergeConfiguration; import org.hyperledger.besu.crypto.SignatureAlgorithmFactory; import org.hyperledger.besu.datatypes.Hash; @@ -188,11 +188,10 @@ public void testGenesisOverrideOptions() throws Exception { assertThat(config.networkId()).isEqualTo(BigInteger.valueOf(1)); // assert that shanghaiTime override is applied - final GenesisConfigFile actualGenesisConfigFile = (config.genesisConfigFile()); - assertThat(actualGenesisConfigFile).isNotNull(); - assertThat(actualGenesisConfigFile.getConfigOptions().getShanghaiTime()).isNotEmpty(); - assertThat(actualGenesisConfigFile.getConfigOptions().getShanghaiTime().getAsLong()) - .isEqualTo(123); + final GenesisConfig actualGenesisConfig = (config.genesisConfig()); + assertThat(actualGenesisConfig).isNotNull(); + assertThat(actualGenesisConfig.getConfigOptions().getShanghaiTime()).isNotEmpty(); + assertThat(actualGenesisConfig.getConfigOptions().getShanghaiTime().getAsLong()).isEqualTo(123); assertThat(commandOutput.toString(UTF_8)).isEmpty(); assertThat(commandErrorOutput.toString(UTF_8)).isEmpty(); @@ -217,11 +216,10 @@ public void testGenesisOverrideOptionsWithCustomGenesis() throws Exception { assertThat(config.networkId()).isEqualTo(BigInteger.valueOf(3141592)); // then assert that the shanghaiTime is applied - final GenesisConfigFile actualGenesisConfigFile = (config.genesisConfigFile()); - assertThat(actualGenesisConfigFile).isNotNull(); - assertThat(actualGenesisConfigFile.getConfigOptions().getShanghaiTime()).isNotEmpty(); - assertThat(actualGenesisConfigFile.getConfigOptions().getShanghaiTime().getAsLong()) - .isEqualTo(123); + final GenesisConfig actualGenesisConfig = (config.genesisConfig()); + assertThat(actualGenesisConfig).isNotNull(); + assertThat(actualGenesisConfig.getConfigOptions().getShanghaiTime()).isNotEmpty(); + assertThat(actualGenesisConfig.getConfigOptions().getShanghaiTime().getAsLong()).isEqualTo(123); assertThat(commandOutput.toString(UTF_8)).isEmpty(); assertThat(commandErrorOutput.toString(UTF_8)).isEmpty(); @@ -262,7 +260,7 @@ public void callingBesuCommandWithoutOptionsMustSyncWithDefaultValues() { verify(mockRunnerBuilder) .ethNetworkConfig( new EthNetworkConfig( - GenesisConfigFile.fromResource(MAINNET.getGenesisFile()), + GenesisConfig.fromResource(MAINNET.getGenesisFile()), MAINNET.getNetworkId(), MAINNET_BOOTSTRAP_NODES, MAINNET_DISCOVERY_URL)); @@ -470,8 +468,8 @@ public void genesisPathOptionMustBeUsed() throws Exception { verify(mockControllerBuilderFactory).fromEthNetworkConfig(networkArg.capture(), any()); verify(mockControllerBuilder).build(); - assertThat(networkArg.getValue().genesisConfigFile()) - .isEqualTo(GenesisConfigFile.fromConfig(encodeJsonGenesis(GENESIS_VALID_JSON))); + assertThat(networkArg.getValue().genesisConfig()) + .isEqualTo(GenesisConfig.fromConfig(encodeJsonGenesis(GENESIS_VALID_JSON))); assertThat(commandOutput.toString(UTF_8)).isEmpty(); assertThat(commandErrorOutput.toString(UTF_8)).isEmpty(); @@ -636,8 +634,8 @@ public void defaultNetworkIdAndBootnodesForCustomNetworkOptions() throws Excepti verify(mockControllerBuilderFactory).fromEthNetworkConfig(networkArg.capture(), any()); verify(mockControllerBuilder).build(); - assertThat(networkArg.getValue().genesisConfigFile()) - .isEqualTo(GenesisConfigFile.fromConfig(encodeJsonGenesis(GENESIS_VALID_JSON))); + assertThat(networkArg.getValue().genesisConfig()) + .isEqualTo(GenesisConfig.fromConfig(encodeJsonGenesis(GENESIS_VALID_JSON))); assertThat(networkArg.getValue().bootNodes()).isEmpty(); assertThat(networkArg.getValue().networkId()).isEqualTo(GENESIS_CONFIG_TEST_CHAINID); @@ -657,8 +655,8 @@ public void defaultNetworkIdForInvalidGenesisMustBeMainnetNetworkId() throws Exc verify(mockControllerBuilderFactory).fromEthNetworkConfig(networkArg.capture(), any()); verify(mockControllerBuilder).build(); - assertThat(networkArg.getValue().genesisConfigFile()) - .isEqualTo(GenesisConfigFile.fromConfig(encodeJsonGenesis(GENESIS_INVALID_DATA))); + assertThat(networkArg.getValue().genesisConfig()) + .isEqualTo(GenesisConfig.fromConfig(encodeJsonGenesis(GENESIS_INVALID_DATA))); assertThat(commandOutput.toString(UTF_8)).isEmpty(); assertThat(commandErrorOutput.toString(UTF_8)).isEmpty(); @@ -672,7 +670,7 @@ public void predefinedNetworkIdsMustBeEqualToChainIds() { // in this network genesis file. final var genesisConfig = - EthNetworkConfig.getNetworkConfig(MAINNET).genesisConfigFile().getConfigOptions(); + EthNetworkConfig.getNetworkConfig(MAINNET).genesisConfig().getConfigOptions(); assertThat(genesisConfig.getChainId().isPresent()).isTrue(); assertThat(genesisConfig.getChainId().get()) .isEqualTo(EthNetworkConfig.getNetworkConfig(MAINNET).networkId()); diff --git a/besu/src/test/java/org/hyperledger/besu/cli/CascadingDefaultProviderTest.java b/besu/src/test/java/org/hyperledger/besu/cli/CascadingDefaultProviderTest.java index c1428388149..c2c10ef73c7 100644 --- a/besu/src/test/java/org/hyperledger/besu/cli/CascadingDefaultProviderTest.java +++ b/besu/src/test/java/org/hyperledger/besu/cli/CascadingDefaultProviderTest.java @@ -28,7 +28,7 @@ import static org.mockito.Mockito.verify; import org.hyperledger.besu.cli.config.EthNetworkConfig; -import org.hyperledger.besu.config.GenesisConfigFile; +import org.hyperledger.besu.config.GenesisConfig; import org.hyperledger.besu.datatypes.Address; import org.hyperledger.besu.ethereum.api.graphql.GraphQLConfiguration; import org.hyperledger.besu.ethereum.api.jsonrpc.JsonRpcConfiguration; @@ -128,8 +128,7 @@ public void overrideDefaultValuesIfKeyIsPresentInConfigFile(final @TempDir File final EthNetworkConfig networkConfig = new EthNetworkConfig.Builder(EthNetworkConfig.getNetworkConfig(MAINNET)) .setNetworkId(BigInteger.valueOf(42)) - .setGenesisConfigFile( - GenesisConfigFile.fromConfig(encodeJsonGenesis(GENESIS_VALID_JSON))) + .setGenesisConfig(GenesisConfig.fromConfig(encodeJsonGenesis(GENESIS_VALID_JSON))) .setBootNodes(nodes) .setDnsDiscoveryUrl(null) .build(); @@ -166,7 +165,7 @@ public void noOverrideDefaultValuesIfKeyIsNotPresentInConfigFile() { verify(mockRunnerBuilder) .ethNetworkConfig( new EthNetworkConfig( - GenesisConfigFile.fromResource(MAINNET.getGenesisFile()), + GenesisConfig.fromResource(MAINNET.getGenesisFile()), MAINNET.getNetworkId(), MAINNET_BOOTSTRAP_NODES, MAINNET_DISCOVERY_URL)); diff --git a/besu/src/test/java/org/hyperledger/besu/cli/config/EthNetworkConfigTest.java b/besu/src/test/java/org/hyperledger/besu/cli/config/EthNetworkConfigTest.java index 3af43eb4e5f..768ca09e971 100644 --- a/besu/src/test/java/org/hyperledger/besu/cli/config/EthNetworkConfigTest.java +++ b/besu/src/test/java/org/hyperledger/besu/cli/config/EthNetworkConfigTest.java @@ -21,7 +21,7 @@ import static org.hyperledger.besu.ethereum.p2p.config.DefaultDiscoveryConfiguration.SEPOLIA_BOOTSTRAP_NODES; import static org.hyperledger.besu.ethereum.p2p.config.DefaultDiscoveryConfiguration.SEPOLIA_DISCOVERY_URL; -import org.hyperledger.besu.config.GenesisConfigFile; +import org.hyperledger.besu.config.GenesisConfig; import java.math.BigInteger; @@ -77,8 +77,8 @@ public void testBuilderWithNetworkId() { EthNetworkConfig config = new EthNetworkConfig.Builder(EthNetworkConfig.getNetworkConfig(MAINNET)) .setNetworkId(BigInteger.valueOf(42)) - .setGenesisConfigFile( - GenesisConfigFile.fromConfig( + .setGenesisConfig( + GenesisConfig.fromConfig( """ { "config":{ @@ -87,7 +87,7 @@ public void testBuilderWithNetworkId() { } """)) .build(); - assertThat(config.genesisConfigFile().getConfigOptions().getChainId()) + assertThat(config.genesisConfig().getConfigOptions().getChainId()) .contains(BigInteger.valueOf(1234567)); assertThat(config.dnsDiscoveryUrl()).isNotNull(); assertThat(config.bootNodes()).isNotEmpty(); diff --git a/besu/src/test/java/org/hyperledger/besu/components/GenesisConfigModule.java b/besu/src/test/java/org/hyperledger/besu/components/GenesisConfigModule.java index ae82b8b9288..c43d49cd8ef 100644 --- a/besu/src/test/java/org/hyperledger/besu/components/GenesisConfigModule.java +++ b/besu/src/test/java/org/hyperledger/besu/components/GenesisConfigModule.java @@ -14,7 +14,7 @@ */ package org.hyperledger.besu.components; -import org.hyperledger.besu.config.GenesisConfigFile; +import org.hyperledger.besu.config.GenesisConfig; import javax.inject.Named; @@ -26,13 +26,13 @@ public class GenesisConfigModule { @Named("default") @Provides - GenesisConfigFile provideDefaultGenesisConfigFile() { - return GenesisConfigFile.DEFAULT; + GenesisConfig provideDefaultGenesisConfig() { + return GenesisConfig.DEFAULT; } @Named("mainnet") @Provides - GenesisConfigFile provideMainnetGenesisConfigFile() { - return GenesisConfigFile.mainnet(); + GenesisConfig provideMainnetGenesisConfig() { + return GenesisConfig.mainnet(); } } diff --git a/besu/src/test/java/org/hyperledger/besu/controller/AbstractBftBesuControllerBuilderTest.java b/besu/src/test/java/org/hyperledger/besu/controller/AbstractBftBesuControllerBuilderTest.java index 26364087492..b1cf3dd776d 100644 --- a/besu/src/test/java/org/hyperledger/besu/controller/AbstractBftBesuControllerBuilderTest.java +++ b/besu/src/test/java/org/hyperledger/besu/controller/AbstractBftBesuControllerBuilderTest.java @@ -21,7 +21,7 @@ import org.hyperledger.besu.components.BesuComponent; import org.hyperledger.besu.config.CheckpointConfigOptions; -import org.hyperledger.besu.config.GenesisConfigFile; +import org.hyperledger.besu.config.GenesisConfig; import org.hyperledger.besu.config.GenesisConfigOptions; import org.hyperledger.besu.cryptoservices.NodeKey; import org.hyperledger.besu.cryptoservices.NodeKeyUtils; @@ -75,7 +75,7 @@ public abstract class AbstractBftBesuControllerBuilderTest { protected BesuControllerBuilder bftBesuControllerBuilder; - @Mock protected GenesisConfigFile genesisConfigFile; + @Mock protected GenesisConfig genesisConfig; @Mock protected GenesisConfigOptions genesisConfigOptions; @Mock private SynchronizerConfiguration synchronizerConfiguration; @Mock private EthProtocolConfiguration ethProtocolConfiguration; @@ -102,11 +102,11 @@ public void setup() throws JsonProcessingException { final WorldStateStorageCoordinator worldStateStorageCoordinator = new WorldStateStorageCoordinator(worldStateKeyValueStorage); - lenient().when(genesisConfigFile.getParentHash()).thenReturn(Hash.ZERO.toHexString()); - lenient().when(genesisConfigFile.getDifficulty()).thenReturn(Bytes.of(0).toHexString()); - lenient().when(genesisConfigFile.getMixHash()).thenReturn(Hash.ZERO.toHexString()); - lenient().when(genesisConfigFile.getNonce()).thenReturn(Long.toHexString(1)); - lenient().when(genesisConfigFile.getConfigOptions()).thenReturn(genesisConfigOptions); + lenient().when(genesisConfig.getParentHash()).thenReturn(Hash.ZERO.toHexString()); + lenient().when(genesisConfig.getDifficulty()).thenReturn(Bytes.of(0).toHexString()); + lenient().when(genesisConfig.getMixHash()).thenReturn(Hash.ZERO.toHexString()); + lenient().when(genesisConfig.getNonce()).thenReturn(Long.toHexString(1)); + lenient().when(genesisConfig.getConfigOptions()).thenReturn(genesisConfigOptions); lenient().when(genesisConfigOptions.getCheckpointOptions()).thenReturn(checkpointConfigOptions); lenient() .when(storageProvider.createBlockchainStorage(any(), any(), any())) @@ -139,11 +139,11 @@ public void setup() throws JsonProcessingException { .when(synchronizerConfiguration.getBlockPropagationRange()) .thenReturn(Range.closed(1L, 2L)); - setupBftGenesisConfigFile(); + setupBftGenesisConfig(); bftBesuControllerBuilder = createBftControllerBuilder() - .genesisConfigFile(genesisConfigFile) + .genesisConfig(genesisConfig) .synchronizerConfiguration(synchronizerConfiguration) .ethProtocolConfiguration(ethProtocolConfiguration) .networkId(networkId) @@ -163,7 +163,7 @@ public void setup() throws JsonProcessingException { .apiConfiguration(ImmutableApiConfiguration.builder().build()); } - protected abstract void setupBftGenesisConfigFile() throws JsonProcessingException; + protected abstract void setupBftGenesisConfig() throws JsonProcessingException; protected abstract BesuControllerBuilder createBftControllerBuilder(); diff --git a/besu/src/test/java/org/hyperledger/besu/controller/BesuControllerTest.java b/besu/src/test/java/org/hyperledger/besu/controller/BesuControllerTest.java index 94c68f7cbe2..1f6927ca995 100644 --- a/besu/src/test/java/org/hyperledger/besu/controller/BesuControllerTest.java +++ b/besu/src/test/java/org/hyperledger/besu/controller/BesuControllerTest.java @@ -20,7 +20,7 @@ import static org.mockito.Mockito.lenient; import static org.mockito.Mockito.when; -import org.hyperledger.besu.config.GenesisConfigFile; +import org.hyperledger.besu.config.GenesisConfig; import org.hyperledger.besu.config.GenesisConfigOptions; import org.hyperledger.besu.config.QbftConfigOptions; import org.hyperledger.besu.ethereum.eth.sync.SyncMode; @@ -39,20 +39,20 @@ @ExtendWith(MockitoExtension.class) public class BesuControllerTest { - @Mock GenesisConfigFile genesisConfigFile; + @Mock GenesisConfig genesisConfig; @Mock GenesisConfigOptions genesisConfigOptions; @Mock QbftConfigOptions qbftConfigOptions; @BeforeEach public void setUp() { - lenient().when(genesisConfigFile.getConfigOptions()).thenReturn(genesisConfigOptions); + lenient().when(genesisConfig.getConfigOptions()).thenReturn(genesisConfigOptions); } @Test public void missingQbftStartBlock() { mockGenesisConfigForMigration("ibft2", OptionalLong.empty()); assertThatThrownBy( - () -> new BesuController.Builder().fromGenesisFile(genesisConfigFile, SyncMode.FULL)) + () -> new BesuController.Builder().fromGenesisFile(genesisConfig, SyncMode.FULL)) .isInstanceOf(IllegalStateException.class) .hasMessage("Missing QBFT startBlock config in genesis file"); } @@ -61,7 +61,7 @@ public void missingQbftStartBlock() { public void invalidQbftStartBlock() { mockGenesisConfigForMigration("ibft2", OptionalLong.of(-1L)); assertThatThrownBy( - () -> new BesuController.Builder().fromGenesisFile(genesisConfigFile, SyncMode.FULL)) + () -> new BesuController.Builder().fromGenesisFile(genesisConfig, SyncMode.FULL)) .isInstanceOf(IllegalStateException.class) .hasMessage("Invalid QBFT startBlock config in genesis file"); } @@ -72,7 +72,7 @@ public void invalidConsensusCombination() { // explicitly not setting isIbft2() for genesisConfigOptions assertThatThrownBy( - () -> new BesuController.Builder().fromGenesisFile(genesisConfigFile, SyncMode.FULL)) + () -> new BesuController.Builder().fromGenesisFile(genesisConfig, SyncMode.FULL)) .isInstanceOf(IllegalStateException.class) .hasMessage( "Invalid genesis migration config. Migration is supported from IBFT (legacy) or IBFT2 to QBFT)"); @@ -84,7 +84,7 @@ public void createConsensusScheduleBesuControllerBuilderWhenMigratingFromIbft2To mockGenesisConfigForMigration("ibft2", OptionalLong.of(qbftStartBlock)); final BesuControllerBuilder besuControllerBuilder = - new BesuController.Builder().fromGenesisFile(genesisConfigFile, SyncMode.FULL); + new BesuController.Builder().fromGenesisFile(genesisConfig, SyncMode.FULL); assertThat(besuControllerBuilder).isInstanceOf(ConsensusScheduleBesuControllerBuilder.class); @@ -118,8 +118,8 @@ private void mockGenesisConfigForMigration( @Test public void postMergeCheckpointSyncUsesMergeControllerBuilder() { - final GenesisConfigFile postMergeGenesisFile = - GenesisConfigFile.fromResource("/valid_post_merge_near_head_checkpoint.json"); + final GenesisConfig postMergeGenesisFile = + GenesisConfig.fromResource("/valid_post_merge_near_head_checkpoint.json"); final BesuControllerBuilder besuControllerBuilder = new BesuController.Builder().fromGenesisFile(postMergeGenesisFile, SyncMode.CHECKPOINT); @@ -130,8 +130,8 @@ public void postMergeCheckpointSyncUsesMergeControllerBuilder() { @Test public void postMergeCheckpointSyncWithTotalDifficultyEqualsTTDUsesTransitionControllerBuilder() throws IOException { - final GenesisConfigFile mergeAtGenesisFile = - GenesisConfigFile.fromResource( + final GenesisConfig mergeAtGenesisFile = + GenesisConfig.fromResource( "/invalid_post_merge_checkpoint_total_difficulty_same_as_TTD.json"); final BesuControllerBuilder besuControllerBuilder = @@ -143,8 +143,7 @@ public void postMergeCheckpointSyncWithTotalDifficultyEqualsTTDUsesTransitionCon @Test public void preMergeCheckpointSyncUsesTransitionControllerBuilder() { final BesuControllerBuilder besuControllerBuilder = - new BesuController.Builder() - .fromGenesisFile(GenesisConfigFile.mainnet(), SyncMode.CHECKPOINT); + new BesuController.Builder().fromGenesisFile(GenesisConfig.mainnet(), SyncMode.CHECKPOINT); assertThat(besuControllerBuilder).isInstanceOf(TransitionBesuControllerBuilder.class); } @@ -152,7 +151,7 @@ public void preMergeCheckpointSyncUsesTransitionControllerBuilder() { @Test public void nonCheckpointSyncUsesTransitionControllerBuild() { final BesuControllerBuilder besuControllerBuilder = - new BesuController.Builder().fromGenesisFile(GenesisConfigFile.mainnet(), SyncMode.SNAP); + new BesuController.Builder().fromGenesisFile(GenesisConfig.mainnet(), SyncMode.SNAP); assertThat(besuControllerBuilder).isInstanceOf(TransitionBesuControllerBuilder.class); } diff --git a/besu/src/test/java/org/hyperledger/besu/controller/CliqueBesuControllerBuilderTest.java b/besu/src/test/java/org/hyperledger/besu/controller/CliqueBesuControllerBuilderTest.java index f05ea666a0d..b9c919d18f0 100644 --- a/besu/src/test/java/org/hyperledger/besu/controller/CliqueBesuControllerBuilderTest.java +++ b/besu/src/test/java/org/hyperledger/besu/controller/CliqueBesuControllerBuilderTest.java @@ -22,7 +22,7 @@ import org.hyperledger.besu.components.BesuComponent; import org.hyperledger.besu.config.CheckpointConfigOptions; -import org.hyperledger.besu.config.GenesisConfigFile; +import org.hyperledger.besu.config.GenesisConfig; import org.hyperledger.besu.config.GenesisConfigOptions; import org.hyperledger.besu.config.ImmutableCliqueConfigOptions; import org.hyperledger.besu.config.TransitionsConfigOptions; @@ -80,7 +80,7 @@ public class CliqueBesuControllerBuilderTest { private BesuControllerBuilder cliqueBesuControllerBuilder; - @Mock private GenesisConfigFile genesisConfigFile; + @Mock private GenesisConfig genesisConfig; @Mock private GenesisConfigOptions genesisConfigOptions; @Mock private SynchronizerConfiguration synchronizerConfiguration; @Mock private EthProtocolConfiguration ethProtocolConfiguration; @@ -108,14 +108,14 @@ public void setup() throws JsonProcessingException { final WorldStateStorageCoordinator worldStateStorageCoordinator = new WorldStateStorageCoordinator(worldStateKeyValueStorage); - lenient().when(genesisConfigFile.getParentHash()).thenReturn(Hash.ZERO.toHexString()); - lenient().when(genesisConfigFile.getDifficulty()).thenReturn(Bytes.of(0).toHexString()); - when(genesisConfigFile.getExtraData()) + lenient().when(genesisConfig.getParentHash()).thenReturn(Hash.ZERO.toHexString()); + lenient().when(genesisConfig.getDifficulty()).thenReturn(Bytes.of(0).toHexString()); + when(genesisConfig.getExtraData()) .thenReturn( "0x0000000000000000000000000000000000000000000000000000000000000000b9b81ee349c3807e46bc71aa2632203c5b4620340000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000"); - lenient().when(genesisConfigFile.getMixHash()).thenReturn(Hash.ZERO.toHexString()); - lenient().when(genesisConfigFile.getNonce()).thenReturn(Long.toHexString(1)); - lenient().when(genesisConfigFile.getConfigOptions()).thenReturn(genesisConfigOptions); + lenient().when(genesisConfig.getMixHash()).thenReturn(Hash.ZERO.toHexString()); + lenient().when(genesisConfig.getNonce()).thenReturn(Long.toHexString(1)); + lenient().when(genesisConfig.getConfigOptions()).thenReturn(genesisConfigOptions); lenient().when(genesisConfigOptions.getCheckpointOptions()).thenReturn(checkpointConfigOptions); lenient() .when(storageProvider.createBlockchainStorage(any(), any(), any())) @@ -176,7 +176,7 @@ public void setup() throws JsonProcessingException { cliqueBesuControllerBuilder = new CliqueBesuControllerBuilder() - .genesisConfigFile(genesisConfigFile) + .genesisConfig(genesisConfig) .synchronizerConfiguration(synchronizerConfiguration) .ethProtocolConfiguration(ethProtocolConfiguration) .networkId(networkId) diff --git a/besu/src/test/java/org/hyperledger/besu/controller/ConsensusScheduleBesuControllerBuilderTest.java b/besu/src/test/java/org/hyperledger/besu/controller/ConsensusScheduleBesuControllerBuilderTest.java index 4e38e03c062..4a4ae8530e3 100644 --- a/besu/src/test/java/org/hyperledger/besu/controller/ConsensusScheduleBesuControllerBuilderTest.java +++ b/besu/src/test/java/org/hyperledger/besu/controller/ConsensusScheduleBesuControllerBuilderTest.java @@ -20,7 +20,7 @@ import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; -import org.hyperledger.besu.config.GenesisConfigFile; +import org.hyperledger.besu.config.GenesisConfig; import org.hyperledger.besu.config.StubGenesisConfigOptions; import org.hyperledger.besu.consensus.common.ForkSpec; import org.hyperledger.besu.consensus.common.ForksSchedule; @@ -60,7 +60,7 @@ public class ConsensusScheduleBesuControllerBuilderTest { private @Mock BiFunction< NavigableSet>, Optional, ProtocolSchedule> combinedProtocolScheduleFactory; - private @Mock GenesisConfigFile genesisConfigFile; + private @Mock GenesisConfig genesisConfig; private @Mock BesuControllerBuilder besuControllerBuilder1; private @Mock BesuControllerBuilder besuControllerBuilder2; private @Mock BesuControllerBuilder besuControllerBuilder3; @@ -103,8 +103,8 @@ public void mustCreateCombinedProtocolScheduleUsingProtocolSchedulesOrderedByBlo final ConsensusScheduleBesuControllerBuilder consensusScheduleBesuControllerBuilder = new ConsensusScheduleBesuControllerBuilder( besuControllerBuilderSchedule, combinedProtocolScheduleFactory); - when(genesisConfigFile.getConfigOptions()).thenReturn(genesisConfigOptions); - consensusScheduleBesuControllerBuilder.genesisConfigFile(genesisConfigFile); + when(genesisConfig.getConfigOptions()).thenReturn(genesisConfigOptions); + consensusScheduleBesuControllerBuilder.genesisConfig(genesisConfig); consensusScheduleBesuControllerBuilder.createProtocolSchedule(); final NavigableSet> expectedProtocolSchedulesSpecs = diff --git a/besu/src/test/java/org/hyperledger/besu/controller/IbftBesuControllerBuilderTest.java b/besu/src/test/java/org/hyperledger/besu/controller/IbftBesuControllerBuilderTest.java index 055e136c8ca..1a2f45eac8b 100644 --- a/besu/src/test/java/org/hyperledger/besu/controller/IbftBesuControllerBuilderTest.java +++ b/besu/src/test/java/org/hyperledger/besu/controller/IbftBesuControllerBuilderTest.java @@ -33,7 +33,7 @@ public class IbftBesuControllerBuilderTest extends AbstractBftBesuControllerBuilderTest { @Override - public void setupBftGenesisConfigFile() throws JsonProcessingException { + public void setupBftGenesisConfig() throws JsonProcessingException { // Ibft prepForBuild setup lenient() @@ -56,7 +56,7 @@ public void setupBftGenesisConfigFile() throws JsonProcessingException { .when(genesisConfigOptions.getTransitions()) .thenReturn(new TransitionsConfigOptions(jsonTransitions)); - when(genesisConfigFile.getExtraData()) + when(genesisConfig.getExtraData()) .thenReturn( "0xf83ea00000000000000000000000000000000000000000000000000000000000000000d594c2ab482b506de561668e07f04547232a72897daf808400000000c0"); } diff --git a/besu/src/test/java/org/hyperledger/besu/controller/MergeBesuControllerBuilderTest.java b/besu/src/test/java/org/hyperledger/besu/controller/MergeBesuControllerBuilderTest.java index 7c4a370beb0..ce2dab822ff 100644 --- a/besu/src/test/java/org/hyperledger/besu/controller/MergeBesuControllerBuilderTest.java +++ b/besu/src/test/java/org/hyperledger/besu/controller/MergeBesuControllerBuilderTest.java @@ -25,7 +25,7 @@ import org.hyperledger.besu.components.BesuComponent; import org.hyperledger.besu.config.CheckpointConfigOptions; -import org.hyperledger.besu.config.GenesisConfigFile; +import org.hyperledger.besu.config.GenesisConfig; import org.hyperledger.besu.config.GenesisConfigOptions; import org.hyperledger.besu.consensus.merge.MergeContext; import org.hyperledger.besu.cryptoservices.NodeKey; @@ -89,7 +89,7 @@ public class MergeBesuControllerBuilderTest { private MergeBesuControllerBuilder besuControllerBuilder; private static final NodeKey nodeKey = NodeKeyUtils.generate(); - @Mock GenesisConfigFile genesisConfigFile; + @Mock GenesisConfig genesisConfig; @Mock GenesisConfigOptions genesisConfigOptions; @Mock SynchronizerConfiguration synchronizerConfiguration; @Mock EthProtocolConfiguration ethProtocolConfiguration; @@ -121,12 +121,12 @@ public void setup() { final WorldStateStorageCoordinator worldStateStorageCoordinator = new WorldStateStorageCoordinator(worldStateKeyValueStorage); - lenient().when(genesisConfigFile.getParentHash()).thenReturn(Hash.ZERO.toHexString()); - lenient().when(genesisConfigFile.getDifficulty()).thenReturn(Bytes.of(0).toHexString()); - lenient().when(genesisConfigFile.getExtraData()).thenReturn(Bytes.EMPTY.toHexString()); - lenient().when(genesisConfigFile.getMixHash()).thenReturn(Hash.ZERO.toHexString()); - lenient().when(genesisConfigFile.getNonce()).thenReturn(Long.toHexString(1)); - lenient().when(genesisConfigFile.getConfigOptions()).thenReturn(genesisConfigOptions); + lenient().when(genesisConfig.getParentHash()).thenReturn(Hash.ZERO.toHexString()); + lenient().when(genesisConfig.getDifficulty()).thenReturn(Bytes.of(0).toHexString()); + lenient().when(genesisConfig.getExtraData()).thenReturn(Bytes.EMPTY.toHexString()); + lenient().when(genesisConfig.getMixHash()).thenReturn(Hash.ZERO.toHexString()); + lenient().when(genesisConfig.getNonce()).thenReturn(Long.toHexString(1)); + lenient().when(genesisConfig.getConfigOptions()).thenReturn(genesisConfigOptions); lenient().when(genesisConfigOptions.getCheckpointOptions()).thenReturn(checkpointConfigOptions); when(genesisConfigOptions.getTerminalTotalDifficulty()) .thenReturn((Optional.of(UInt256.valueOf(100L)))); @@ -177,7 +177,7 @@ MergeBesuControllerBuilder visitWithMockConfigs(final MergeBesuControllerBuilder return (MergeBesuControllerBuilder) builder .gasLimitCalculator(gasLimitCalculator) - .genesisConfigFile(genesisConfigFile) + .genesisConfig(genesisConfig) .synchronizerConfiguration(synchronizerConfiguration) .ethProtocolConfiguration(ethProtocolConfiguration) .miningParameters(miningConfiguration) @@ -227,8 +227,7 @@ public void assertConfiguredBlock() { @Test public void assertBuiltContextMonitorsTTD() { final GenesisState genesisState = - GenesisState.fromConfig( - genesisConfigFile, this.besuControllerBuilder.createProtocolSchedule()); + GenesisState.fromConfig(genesisConfig, this.besuControllerBuilder.createProtocolSchedule()); final MutableBlockchain blockchain = createInMemoryBlockchain(genesisState.getBlock()); final MergeContext mergeContext = spy( diff --git a/besu/src/test/java/org/hyperledger/besu/controller/QbftBesuControllerBuilderTest.java b/besu/src/test/java/org/hyperledger/besu/controller/QbftBesuControllerBuilderTest.java index a448b11f406..c00a9160ca2 100644 --- a/besu/src/test/java/org/hyperledger/besu/controller/QbftBesuControllerBuilderTest.java +++ b/besu/src/test/java/org/hyperledger/besu/controller/QbftBesuControllerBuilderTest.java @@ -47,7 +47,7 @@ public class QbftBesuControllerBuilderTest extends AbstractBftBesuControllerBuilderTest { @Override - public void setupBftGenesisConfigFile() throws JsonProcessingException { + public void setupBftGenesisConfig() throws JsonProcessingException { // qbft prepForBuild setup lenient() @@ -71,7 +71,7 @@ public void setupBftGenesisConfigFile() throws JsonProcessingException { .thenReturn(new TransitionsConfigOptions(jsonTransitions)); lenient() - .when(genesisConfigFile.getExtraData()) + .when(genesisConfig.getExtraData()) .thenReturn( QbftExtraDataCodec.createGenesisExtraDataString(List.of(Address.fromHexString("1")))); } diff --git a/besu/src/test/java/org/hyperledger/besu/controller/TransitionControllerBuilderTest.java b/besu/src/test/java/org/hyperledger/besu/controller/TransitionControllerBuilderTest.java index da409482e03..dc8eee16eb5 100644 --- a/besu/src/test/java/org/hyperledger/besu/controller/TransitionControllerBuilderTest.java +++ b/besu/src/test/java/org/hyperledger/besu/controller/TransitionControllerBuilderTest.java @@ -21,7 +21,7 @@ import static org.mockito.Mockito.spy; import static org.mockito.Mockito.when; -import org.hyperledger.besu.config.GenesisConfigFile; +import org.hyperledger.besu.config.GenesisConfig; import org.hyperledger.besu.consensus.clique.BlockHeaderValidationRulesetFactory; import org.hyperledger.besu.consensus.clique.CliqueContext; import org.hyperledger.besu.consensus.common.EpochManager; @@ -98,9 +98,9 @@ public void setup() { preMergeProtocolSchedule, postMergeProtocolSchedule, mergeContext)); transitionProtocolSchedule.setProtocolContext(protocolContext); cliqueBuilder.nodeKey(NodeKeyUtils.generate()); - cliqueBuilder.genesisConfigFile(GenesisConfigFile.DEFAULT); - powBuilder.genesisConfigFile(GenesisConfigFile.DEFAULT); - postMergeBuilder.genesisConfigFile(GenesisConfigFile.DEFAULT); + cliqueBuilder.genesisConfig(GenesisConfig.DEFAULT); + powBuilder.genesisConfig(GenesisConfig.DEFAULT); + postMergeBuilder.genesisConfig(GenesisConfig.DEFAULT); postMergeBuilder.storageProvider(storageProvider); lenient().when(protocolContext.getBlockchain()).thenReturn(mockBlockchain); lenient() @@ -267,7 +267,7 @@ void assertDetachedRulesForPostMergeBlocks(final BlockHeaderValidator validator) TransitionCoordinator buildTransitionCoordinator( final BesuControllerBuilder preMerge, final MergeBesuControllerBuilder postMerge) { var builder = new TransitionBesuControllerBuilder(preMerge, postMerge); - builder.genesisConfigFile(GenesisConfigFile.mainnet()); + builder.genesisConfig(GenesisConfig.mainnet()); builder.storageProvider(storageProvider); builder.metricsSystem(new NoOpMetricsSystem()); var coordinator = diff --git a/besu/src/test/java/org/hyperledger/besu/util/EphemeryGenesisUpdaterTest.java b/besu/src/test/java/org/hyperledger/besu/util/EphemeryGenesisUpdaterTest.java index fe21c1e6d72..704f26f8e87 100644 --- a/besu/src/test/java/org/hyperledger/besu/util/EphemeryGenesisUpdaterTest.java +++ b/besu/src/test/java/org/hyperledger/besu/util/EphemeryGenesisUpdaterTest.java @@ -16,9 +16,9 @@ import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; -import static org.hyperledger.besu.config.GenesisConfigFile.fromConfig; +import static org.hyperledger.besu.config.GenesisConfig.fromConfig; -import org.hyperledger.besu.config.GenesisConfigFile; +import org.hyperledger.besu.config.GenesisConfig; import java.math.BigInteger; import java.util.Map; @@ -44,7 +44,7 @@ public class EphemeryGenesisUpdaterTest { .put("config", (new JsonObject()).put("chainId", GENESIS_CONFIG_TEST_CHAINID)) .put("timestamp", GENESIS_TEST_TIMESTAMP); - private static final GenesisConfigFile INVALID_GENESIS_JSON = fromConfig("{}"); + private static final GenesisConfig INVALID_GENESIS_JSON = fromConfig("{}"); private static final JsonObject INVALID_GENESIS_JSON_WITHOUT_CHAINID = (new JsonObject()).put("timestamp", GENESIS_TEST_TIMESTAMP); @@ -54,16 +54,16 @@ public class EphemeryGenesisUpdaterTest { @Test public void testEphemeryWhenChainIdIsAbsent() { - final GenesisConfigFile config = - GenesisConfigFile.fromConfig(INVALID_GENESIS_JSON_WITHOUT_CHAINID.toString()); + final GenesisConfig config = + GenesisConfig.fromConfig(INVALID_GENESIS_JSON_WITHOUT_CHAINID.toString()); Optional chainId = config.getConfigOptions().getChainId(); assertThat(chainId).isNotPresent(); } @Test public void testShouldDefaultTimestampToZero() { - final GenesisConfigFile config = - GenesisConfigFile.fromConfig(INVALID_GENESIS_JSON_WITHOUT_TIMESTAMP.toString()); + final GenesisConfig config = + GenesisConfig.fromConfig(INVALID_GENESIS_JSON_WITHOUT_TIMESTAMP.toString()); assertThat(config.getTimestamp()).isZero(); } @@ -76,7 +76,7 @@ public void testEphemeryWhenGenesisJsonIsInvalid() { @Test public void testEphemeryWhenGenesisJsonIsValid() { - final GenesisConfigFile config = GenesisConfigFile.fromConfig(VALID_GENESIS_JSON.toString()); + final GenesisConfig config = GenesisConfig.fromConfig(VALID_GENESIS_JSON.toString()); assertThat(String.valueOf(config.getTimestamp())) .isEqualTo(String.valueOf(GENESIS_TEST_TIMESTAMP)); assertThat(config.getConfigOptions().getChainId()) @@ -87,7 +87,7 @@ public void testEphemeryWhenGenesisJsonIsValid() { @Test public void testEphemeryNotYetDueForUpdate() { - final GenesisConfigFile config = GenesisConfigFile.fromConfig(VALID_GENESIS_JSON.toString()); + final GenesisConfig config = GenesisConfig.fromConfig(VALID_GENESIS_JSON.toString()); assertThat(EARLIER_TIMESTAMP).isLessThan(config.getTimestamp() + PERIOD_IN_SECONDS); } @@ -100,7 +100,7 @@ void testOverrideWithUpdatedChainIdAndTimeStamp() { long expectedGenesisTimestamp = GENESIS_TEST_TIMESTAMP + (PERIOD_SINCE_GENESIS * PERIOD_IN_SECONDS); - final GenesisConfigFile config = GenesisConfigFile.fromResource("/ephemery.json"); + final GenesisConfig config = GenesisConfig.fromResource("/ephemery.json"); final Map override = new TreeMap<>(String.CASE_INSENSITIVE_ORDER); override.put("chainId", String.valueOf(expectedChainId)); @@ -116,7 +116,7 @@ void testOverrideWithUpdatedChainIdAndTimeStamp() { @Test public void testEphemeryWhenSuccessful() { - final GenesisConfigFile config = GenesisConfigFile.fromConfig(VALID_GENESIS_JSON.toString()); + final GenesisConfig config = GenesisConfig.fromConfig(VALID_GENESIS_JSON.toString()); BigInteger expectedChainId = BigInteger.valueOf(GENESIS_CONFIG_TEST_CHAINID) @@ -127,7 +127,7 @@ public void testEphemeryWhenSuccessful() { final Map override = new TreeMap<>(String.CASE_INSENSITIVE_ORDER); override.put("chainId", String.valueOf(expectedChainId)); override.put("timestamp", String.valueOf(expectedGenesisTimestamp)); - final GenesisConfigFile updatedConfig = config.withOverrides(override); + final GenesisConfig updatedConfig = config.withOverrides(override); assertThat(LATER_TIMESTAMP) .isGreaterThan(Long.parseLong(String.valueOf(GENESIS_TEST_TIMESTAMP + PERIOD_IN_SECONDS))); diff --git a/config/src/main/java/org/hyperledger/besu/config/GenesisConfigFile.java b/config/src/main/java/org/hyperledger/besu/config/GenesisConfig.java similarity index 89% rename from config/src/main/java/org/hyperledger/besu/config/GenesisConfigFile.java rename to config/src/main/java/org/hyperledger/besu/config/GenesisConfig.java index 84c81a7f083..47fa2967451 100644 --- a/config/src/main/java/org/hyperledger/besu/config/GenesisConfigFile.java +++ b/config/src/main/java/org/hyperledger/besu/config/GenesisConfig.java @@ -29,11 +29,11 @@ import com.fasterxml.jackson.databind.node.ObjectNode; /** The Genesis config file. */ -public class GenesisConfigFile { +public class GenesisConfig { /** The constant DEFAULT. */ - public static final GenesisConfigFile DEFAULT = - new GenesisConfigFile(new GenesisReader.FromObjectNode(JsonUtil.createEmptyObjectNode())); + public static final GenesisConfig DEFAULT = + new GenesisConfig(new GenesisReader.FromObjectNode(JsonUtil.createEmptyObjectNode())); /** The constant BASEFEE_AT_GENESIS_DEFAULT_VALUE. */ public static final Wei BASEFEE_AT_GENESIS_DEFAULT_VALUE = Wei.of(1_000_000_000L); @@ -42,7 +42,7 @@ public class GenesisConfigFile { private final ObjectNode genesisRoot; private Map overrides; - private GenesisConfigFile(final GenesisReader loader) { + private GenesisConfig(final GenesisReader loader) { this.loader = loader; this.genesisRoot = loader.getRoot(); } @@ -52,8 +52,8 @@ private GenesisConfigFile(final GenesisReader loader) { * * @return the genesis config file */ - public static GenesisConfigFile mainnet() { - return fromSource(GenesisConfigFile.class.getResource("/mainnet.json")); + public static GenesisConfig mainnet() { + return fromSource(GenesisConfig.class.getResource("/mainnet.json")); } /** @@ -62,7 +62,7 @@ public static GenesisConfigFile mainnet() { * @param jsonSource the URL * @return the genesis config file */ - public static GenesisConfigFile fromSource(final URL jsonSource) { + public static GenesisConfig fromSource(final URL jsonSource) { return fromConfig(JsonUtil.objectNodeFromURL(jsonSource, false)); } @@ -72,8 +72,8 @@ public static GenesisConfigFile fromSource(final URL jsonSource) { * @param resourceName the resource name * @return the genesis config file */ - public static GenesisConfigFile fromResource(final String resourceName) { - return fromConfig(GenesisConfigFile.class.getResource(resourceName)); + public static GenesisConfig fromResource(final String resourceName) { + return fromConfig(GenesisConfig.class.getResource(resourceName)); } /** @@ -82,8 +82,8 @@ public static GenesisConfigFile fromResource(final String resourceName) { * @param jsonSource the json string * @return the genesis config file */ - public static GenesisConfigFile fromConfig(final URL jsonSource) { - return new GenesisConfigFile(new GenesisReader.FromURL(jsonSource)); + public static GenesisConfig fromConfig(final URL jsonSource) { + return new GenesisConfig(new GenesisReader.FromURL(jsonSource)); } /** @@ -92,7 +92,7 @@ public static GenesisConfigFile fromConfig(final URL jsonSource) { * @param json the json string * @return the genesis config file */ - public static GenesisConfigFile fromConfig(final String json) { + public static GenesisConfig fromConfig(final String json) { return fromConfig(JsonUtil.objectNodeFromString(json, false)); } @@ -102,8 +102,8 @@ public static GenesisConfigFile fromConfig(final String json) { * @param config the config * @return the genesis config file */ - public static GenesisConfigFile fromConfig(final ObjectNode config) { - return new GenesisConfigFile(new GenesisReader.FromObjectNode(config)); + public static GenesisConfig fromConfig(final ObjectNode config) { + return new GenesisConfig(new GenesisReader.FromObjectNode(config)); } /** @@ -137,7 +137,7 @@ public GenesisConfigOptions getConfigOptions() { * @param overrides the overrides * @return the config options */ - public GenesisConfigFile withOverrides(final Map overrides) { + public GenesisConfig withOverrides(final Map overrides) { this.overrides = overrides; return this; @@ -350,7 +350,7 @@ public List getForkTimestamps() { public boolean equals(final Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; - final GenesisConfigFile that = (GenesisConfigFile) o; + final GenesisConfig that = (GenesisConfig) o; return Objects.equals(genesisRoot, that.genesisRoot); } diff --git a/config/src/test/java/org/hyperledger/besu/config/CliqueConfigOptionsTest.java b/config/src/test/java/org/hyperledger/besu/config/CliqueConfigOptionsTest.java index f445730ac18..c8fb01b6a1c 100644 --- a/config/src/test/java/org/hyperledger/besu/config/CliqueConfigOptionsTest.java +++ b/config/src/test/java/org/hyperledger/besu/config/CliqueConfigOptionsTest.java @@ -78,6 +78,6 @@ private CliqueConfigOptions fromConfigOptions(final Map cliqueCo final ObjectNode options = JsonUtil.objectNodeFromMap(cliqueConfigOptions); configNode.set("clique", options); rootNode.set("config", configNode); - return GenesisConfigFile.fromConfig(rootNode).getConfigOptions().getCliqueConfigOptions(); + return GenesisConfig.fromConfig(rootNode).getConfigOptions().getCliqueConfigOptions(); } } diff --git a/config/src/test/java/org/hyperledger/besu/config/GenesisConfigOptionsTest.java b/config/src/test/java/org/hyperledger/besu/config/GenesisConfigOptionsTest.java index fe8149cc654..9b09362851f 100644 --- a/config/src/test/java/org/hyperledger/besu/config/GenesisConfigOptionsTest.java +++ b/config/src/test/java/org/hyperledger/besu/config/GenesisConfigOptionsTest.java @@ -260,7 +260,7 @@ void shouldGetChainIdWhenSpecified() { @Test void shouldSupportEmptyGenesisConfig() { - final GenesisConfigOptions config = GenesisConfigFile.fromConfig("{}").getConfigOptions(); + final GenesisConfigOptions config = GenesisConfig.fromConfig("{}").getConfigOptions(); assertThat(config.isEthHash()).isFalse(); assertThat(config.isClique()).isFalse(); assertThat(config.isPoa()).isFalse(); @@ -291,7 +291,7 @@ void shouldNotReturnTerminalTotalDifficultyWhenNotSpecified() { @Test void isZeroBaseFeeShouldDefaultToFalse() { - final GenesisConfigOptions config = GenesisConfigFile.fromConfig("{}").getConfigOptions(); + final GenesisConfigOptions config = GenesisConfig.fromConfig("{}").getConfigOptions(); assertThat(config.isZeroBaseFee()).isFalse(); } @@ -312,7 +312,7 @@ void asMapIncludesZeroBaseFee() { @Test void isFixedBaseFeeShouldDefaultToFalse() { - final GenesisConfigOptions config = GenesisConfigFile.fromConfig("{}").getConfigOptions(); + final GenesisConfigOptions config = GenesisConfig.fromConfig("{}").getConfigOptions(); assertThat(config.isFixedBaseFee()).isFalse(); } @@ -412,6 +412,6 @@ private GenesisConfigOptions fromConfigOptions(final Map configO final ObjectNode rootNode = JsonUtil.createEmptyObjectNode(); final ObjectNode options = JsonUtil.objectNodeFromMap(configOptions); rootNode.set("config", options); - return GenesisConfigFile.fromConfig(rootNode).getConfigOptions(); + return GenesisConfig.fromConfig(rootNode).getConfigOptions(); } } diff --git a/config/src/test/java/org/hyperledger/besu/config/GenesisConfigFileTest.java b/config/src/test/java/org/hyperledger/besu/config/GenesisConfigTest.java similarity index 89% rename from config/src/test/java/org/hyperledger/besu/config/GenesisConfigFileTest.java rename to config/src/test/java/org/hyperledger/besu/config/GenesisConfigTest.java index 3e6b488b9bd..33ff2eb0a36 100644 --- a/config/src/test/java/org/hyperledger/besu/config/GenesisConfigFileTest.java +++ b/config/src/test/java/org/hyperledger/besu/config/GenesisConfigTest.java @@ -17,7 +17,7 @@ import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatExceptionOfType; import static org.assertj.core.api.Assertions.assertThatThrownBy; -import static org.hyperledger.besu.config.GenesisConfigFile.fromConfig; +import static org.hyperledger.besu.config.GenesisConfig.fromConfig; import org.hyperledger.besu.datatypes.Address; import org.hyperledger.besu.datatypes.Wei; @@ -39,15 +39,15 @@ import org.assertj.core.api.ThrowableAssert.ThrowingCallable; import org.junit.jupiter.api.Test; -class GenesisConfigFileTest { +class GenesisConfigTest { private static final BigInteger MAINNET_CHAIN_ID = BigInteger.ONE; private static final BigInteger DEVELOPMENT_CHAIN_ID = BigInteger.valueOf(1337); - private static final GenesisConfigFile EMPTY_CONFIG = fromConfig("{}"); + private static final GenesisConfig EMPTY_CONFIG = fromConfig("{}"); @Test void shouldLoadMainnetConfigFile() { - final GenesisConfigFile config = GenesisConfigFile.mainnet(); + final GenesisConfig config = GenesisConfig.mainnet(); // Sanity check some basic properties to confirm this is the mainnet file. assertThat(config.getConfigOptions().isEthHash()).isTrue(); assertThat(config.getConfigOptions().getChainId()).hasValue(MAINNET_CHAIN_ID); @@ -64,7 +64,7 @@ void shouldLoadMainnetConfigFile() { @Test void shouldLoadDevelopmentConfigFile() { - final GenesisConfigFile config = GenesisConfigFile.fromResource("/dev.json"); + final GenesisConfig config = GenesisConfig.fromResource("/dev.json"); // Sanity check some basic properties to confirm this is the dev file. assertThat(config.getConfigOptions().isEthHash()).isTrue(); assertThat(config.getConfigOptions().getChainId()).hasValue(DEVELOPMENT_CHAIN_ID); @@ -156,27 +156,27 @@ void shouldGetTimestamp() { @Test void shouldGetBaseFeeAtGenesis() { - GenesisConfigFile withBaseFeeAtGenesis = - GenesisConfigFile.fromConfig("{\"config\":{\"londonBlock\":0},\"baseFeePerGas\":\"0xa\"}"); + GenesisConfig withBaseFeeAtGenesis = + GenesisConfig.fromConfig("{\"config\":{\"londonBlock\":0},\"baseFeePerGas\":\"0xa\"}"); assertThat(withBaseFeeAtGenesis.getBaseFeePerGas()).isPresent(); assertThat(withBaseFeeAtGenesis.getBaseFeePerGas().get().toLong()).isEqualTo(10L); } @Test void shouldGetDefaultBaseFeeAtGenesis() { - GenesisConfigFile withBaseFeeAtGenesis = - GenesisConfigFile.fromConfig("{\"config\":{\"londonBlock\":0}}"); + GenesisConfig withBaseFeeAtGenesis = + GenesisConfig.fromConfig("{\"config\":{\"londonBlock\":0}}"); // no specified baseFeePerGas: assertThat(withBaseFeeAtGenesis.getBaseFeePerGas()).isNotPresent(); // supply a default genesis baseFeePerGas when london-at-genesis: assertThat(withBaseFeeAtGenesis.getGenesisBaseFeePerGas()) - .contains(GenesisConfigFile.BASEFEE_AT_GENESIS_DEFAULT_VALUE); + .contains(GenesisConfig.BASEFEE_AT_GENESIS_DEFAULT_VALUE); } @Test void shouldGetBaseFeeExplicitlyAtGenesis() { - GenesisConfigFile withBaseFeeNotAtGenesis = - GenesisConfigFile.fromConfig("{\"config\":{\"londonBlock\":10},\"baseFeePerGas\":\"0xa\"}"); + GenesisConfig withBaseFeeNotAtGenesis = + GenesisConfig.fromConfig("{\"config\":{\"londonBlock\":10},\"baseFeePerGas\":\"0xa\"}"); // specified baseFeePerGas: Wei expectedBaseFee = Wei.of(0xa); assertThat(withBaseFeeNotAtGenesis.getBaseFeePerGas()).contains(expectedBaseFee); @@ -195,7 +195,7 @@ void shouldOverrideConfigOptionsBaseFeeWhenSpecified() { @Test void shouldGetTerminalTotalDifficultyAtGenesis() { - GenesisConfigFile withTerminalTotalDifficultyAtGenesis = + GenesisConfig withTerminalTotalDifficultyAtGenesis = fromConfig("{\"config\":{\"terminalTotalDifficulty\":1000}}"); assertThat(withTerminalTotalDifficultyAtGenesis.getConfigOptions().getTerminalTotalDifficulty()) .contains(UInt256.valueOf(1000L)); @@ -209,7 +209,7 @@ void shouldGetEmptyTerminalTotalDifficultyAtGenesis() { @Test void assertSepoliaTerminalTotalDifficulty() { GenesisConfigOptions sepoliaOptions = - GenesisConfigFile.fromResource("/sepolia.json").getConfigOptions(); + GenesisConfig.fromResource("/sepolia.json").getConfigOptions(); assertThat(sepoliaOptions.getTerminalTotalDifficulty()).isPresent(); assertThat(sepoliaOptions.getTerminalTotalDifficulty()) @@ -219,7 +219,7 @@ void assertSepoliaTerminalTotalDifficulty() { @Test void assertMainnetTerminalTotalDifficulty() { GenesisConfigOptions mainnetOptions = - GenesisConfigFile.fromResource("/mainnet.json").getConfigOptions(); + GenesisConfig.fromResource("/mainnet.json").getConfigOptions(); assertThat(mainnetOptions.getTerminalTotalDifficulty()).isPresent(); // tentative as of 2022-08-11: @@ -230,7 +230,7 @@ void assertMainnetTerminalTotalDifficulty() { @Test void assertTerminalTotalDifficultyOverride() { GenesisConfigOptions sepoliaOverrideOptions = - GenesisConfigFile.fromResource("/sepolia.json") + GenesisConfig.fromResource("/sepolia.json") .withOverrides(Map.of("terminalTotalDifficulty", String.valueOf(Long.MAX_VALUE))) .getConfigOptions(); @@ -241,8 +241,8 @@ void assertTerminalTotalDifficultyOverride() { @Test void shouldFindMergeNetSplitForkAndAlias() { - GenesisConfigFile mergeNetSplitGenesis = - GenesisConfigFile.fromConfig( + GenesisConfig mergeNetSplitGenesis = + GenesisConfig.fromConfig( "{\"config\":{\"mergeNetsplitBlock\":11},\"baseFeePerGas\":\"0xa\"}"); assertThat(mergeNetSplitGenesis.getForkBlockNumbers()).hasSize(1); assertThat(mergeNetSplitGenesis.getConfigOptions().getMergeNetSplitBlockNumber()).isPresent(); @@ -250,8 +250,8 @@ void shouldFindMergeNetSplitForkAndAlias() { .isEqualTo(11L); // assert empty if not present: - GenesisConfigFile londonGenesis = - GenesisConfigFile.fromConfig("{\"config\":{\"londonBlock\":11},\"baseFeePerGas\":\"0xa\"}"); + GenesisConfig londonGenesis = + GenesisConfig.fromConfig("{\"config\":{\"londonBlock\":11},\"baseFeePerGas\":\"0xa\"}"); assertThat(londonGenesis.getForkBlockNumbers()).hasSize(1); assertThat(londonGenesis.getConfigOptions().getMergeNetSplitBlockNumber()).isEmpty(); } @@ -263,7 +263,7 @@ void shouldDefaultTimestampToZero() { @Test void shouldGetAllocations() { - final GenesisConfigFile config = + final GenesisConfig config = fromConfig( "{" + " \"alloc\": {" @@ -322,13 +322,13 @@ void shouldGetAllocations() { @Test void shouldGetEmptyAllocationsWhenAllocNotPresent() { - final GenesisConfigFile config = fromConfig("{}"); + final GenesisConfig config = fromConfig("{}"); assertThat(config.streamAllocations()).isEmpty(); } @Test void shouldGetLargeChainId() { - final GenesisConfigFile config = + final GenesisConfig config = fromConfig( "{\"config\": { \"chainId\": 31415926535897932384626433832795028841971693993751058209749445923078164062862089986280348253421170679821480865132823066470938446095 }}"); assertThat(config.getConfigOptions().getChainId()) @@ -349,7 +349,7 @@ void mustNotAcceptComments() { @Test void testOverridePresent() { - final GenesisConfigFile config = GenesisConfigFile.fromResource("/dev.json"); + final GenesisConfig config = GenesisConfig.fromResource("/dev.json"); final int bigBlock = 999_999_999; final String bigBlockString = Integer.toString(bigBlock); final Map override = new TreeMap<>(String.CASE_INSENSITIVE_ORDER); @@ -368,7 +368,7 @@ void testOverridePresent() { @Test void testOverrideNull() { - final GenesisConfigFile config = GenesisConfigFile.fromResource("/dev.json"); + final GenesisConfig config = GenesisConfig.fromResource("/dev.json"); final Map override = new TreeMap<>(String.CASE_INSENSITIVE_ORDER); override.put("istanbulBlock", null); override.put("chainId", null); @@ -384,7 +384,7 @@ void testOverrideNull() { @Test void testOverrideCaseInsensitivity() { - final GenesisConfigFile config = GenesisConfigFile.fromResource("/dev.json"); + final GenesisConfig config = GenesisConfig.fromResource("/dev.json"); final int bigBlock = 999_999_999; final String bigBlockString = Integer.toString(bigBlock); final Map override = new HashMap<>(); @@ -405,7 +405,7 @@ void testOverrideCaseInsensitivity() { @Test void testOverrideEmptyString() { - final GenesisConfigFile config = GenesisConfigFile.fromResource("/dev.json"); + final GenesisConfig config = GenesisConfig.fromResource("/dev.json"); final Map override = new TreeMap<>(String.CASE_INSENSITIVE_ORDER); override.put("istanbulBlock", ""); override.put("chainId", ""); @@ -420,7 +420,7 @@ void testOverrideEmptyString() { @Test void testNoOverride() { - final GenesisConfigFile config = GenesisConfigFile.fromResource("/dev.json"); + final GenesisConfig config = GenesisConfig.fromResource("/dev.json"); assertThat(config.getConfigOptions().getLondonBlockNumber()).hasValue(0); assertThat(config.getConfigOptions().getIstanbulBlockNumber()).isNotPresent(); @@ -433,7 +433,7 @@ void testNoOverride() { @Test void testConstantinopleFixShouldNotBeSupportedAlongPetersburg() { // petersburg node - final GenesisConfigFile config = GenesisConfigFile.fromResource("/all_forks.json"); + final GenesisConfig config = GenesisConfig.fromResource("/all_forks.json"); assertThat(config.getConfigOptions().getPetersburgBlockNumber()).hasValue(7); @@ -463,7 +463,7 @@ void shouldLoadForksInSortedOrder() throws IOException { "valid_config_with_custom_forks.json"), StandardCharsets.UTF_8))); - final GenesisConfigFile config = fromConfig(configNode); + final GenesisConfig config = fromConfig(configNode); assertThat(config.getForkBlockNumbers()).containsExactly(1L, 2L, 3L, 1035301L, 2222222L); assertThat(config.getConfigOptions().getChainId()).hasValue(BigInteger.valueOf(4)); @@ -483,7 +483,7 @@ void shouldLoadForksIgnoreClassicForkBlock() throws IOException { // declared (which we want to ignore) "valid_config_with_etc_forks.json"), StandardCharsets.UTF_8))); - final GenesisConfigFile config = fromConfig(configNode); + final GenesisConfig config = fromConfig(configNode); assertThat(config.getForkBlockNumbers()).containsExactly(1L, 2L, 3L, 1035301L); assertThat(config.getConfigOptions().getChainId()).hasValue(BigInteger.valueOf(61)); @@ -528,9 +528,9 @@ void shouldLoadForksIgnoreUnexpectedValues() throws IOException { "valid_config_with_unexpected_forks.json"), StandardCharsets.UTF_8))); - final GenesisConfigFile configFileNoUnexpectedForks = fromConfig(configNoUnexpectedForks); - final GenesisConfigFile configFileClassicFork = fromConfig(configClassicFork); - final GenesisConfigFile configFileMultipleUnexpectedForks = + final GenesisConfig configFileNoUnexpectedForks = fromConfig(configNoUnexpectedForks); + final GenesisConfig configFileClassicFork = fromConfig(configClassicFork); + final GenesisConfig configFileMultipleUnexpectedForks = fromConfig(configMultipleUnexpectedForks); assertThat(configFileNoUnexpectedForks.getForkBlockNumbers()) @@ -559,7 +559,7 @@ void roundTripForkIdBlocks() throws IOException { Resources.toString(Resources.getResource("all_forks.json"), StandardCharsets.UTF_8); final ObjectNode genesisNode = JsonUtil.objectNodeFromString(configText); - final GenesisConfigFile genesisConfig = fromConfig(genesisNode); + final GenesisConfig genesisConfig = fromConfig(genesisNode); final ObjectNode output = JsonUtil.objectNodeFromMap(genesisConfig.getConfigOptions().asMap()); @@ -567,7 +567,7 @@ void roundTripForkIdBlocks() throws IOException { .isEqualTo(JsonUtil.getJson(genesisNode.get("config"), true)); } - private GenesisConfigFile configWithProperty(final String key, final String value) { + private GenesisConfig configWithProperty(final String key, final String value) { return fromConfig("{\"" + key + "\":\"" + value + "\"}"); } diff --git a/config/src/test/java/org/hyperledger/besu/config/JsonBftConfigOptionsTest.java b/config/src/test/java/org/hyperledger/besu/config/JsonBftConfigOptionsTest.java index bbb4c4a6ceb..5a81108f0c8 100644 --- a/config/src/test/java/org/hyperledger/besu/config/JsonBftConfigOptionsTest.java +++ b/config/src/test/java/org/hyperledger/besu/config/JsonBftConfigOptionsTest.java @@ -254,6 +254,6 @@ private BftConfigOptions fromConfigOptions(final Map ibftConfigO final ObjectNode options = JsonUtil.objectNodeFromMap(ibftConfigOptions); configNode.set("ibft2", options); rootNode.set("config", configNode); - return GenesisConfigFile.fromConfig(rootNode).getConfigOptions().getBftConfigOptions(); + return GenesisConfig.fromConfig(rootNode).getConfigOptions().getBftConfigOptions(); } } diff --git a/consensus/clique/src/test/java/org/hyperledger/besu/consensus/clique/CliqueProtocolScheduleTest.java b/consensus/clique/src/test/java/org/hyperledger/besu/consensus/clique/CliqueProtocolScheduleTest.java index 47741206229..fcbf10e7ac3 100644 --- a/consensus/clique/src/test/java/org/hyperledger/besu/consensus/clique/CliqueProtocolScheduleTest.java +++ b/consensus/clique/src/test/java/org/hyperledger/besu/consensus/clique/CliqueProtocolScheduleTest.java @@ -20,7 +20,7 @@ import static org.mockito.Mockito.when; import org.hyperledger.besu.config.CliqueConfigOptions; -import org.hyperledger.besu.config.GenesisConfigFile; +import org.hyperledger.besu.config.GenesisConfig; import org.hyperledger.besu.config.GenesisConfigOptions; import org.hyperledger.besu.config.JsonCliqueConfigOptions; import org.hyperledger.besu.consensus.common.ForkSpec; @@ -61,7 +61,7 @@ public void protocolSpecsAreCreatedAtBlockDefinedInJson() { + "\"byzantiumBlock\": 1035301}" + "}"; - final GenesisConfigOptions config = GenesisConfigFile.fromConfig(jsonInput).getConfigOptions(); + final GenesisConfigOptions config = GenesisConfig.fromConfig(jsonInput).getConfigOptions(); final ProtocolSchedule protocolSchedule = CliqueProtocolSchedule.create( config, @@ -91,7 +91,7 @@ public void parametersAlignWithMainnetWithAdjustments() { new ForksSchedule<>(List.of(new ForkSpec<>(0, JsonCliqueConfigOptions.DEFAULT))); final ProtocolSpec homestead = CliqueProtocolSchedule.create( - GenesisConfigFile.DEFAULT.getConfigOptions(), + GenesisConfig.DEFAULT.getConfigOptions(), forksSchedule, NODE_KEY, PrivacyParameters.DEFAULT, @@ -163,7 +163,7 @@ public void shouldValidateBaseFeeMarketTransition() { final String jsonInput = "{\"config\": " + "\t{\"chainId\": 1337,\n" + "\t\"londonBlock\": 2}\n" + "}"; - final GenesisConfigOptions config = GenesisConfigFile.fromConfig(jsonInput).getConfigOptions(); + final GenesisConfigOptions config = GenesisConfig.fromConfig(jsonInput).getConfigOptions(); final ForksSchedule forksSchedule = new ForksSchedule<>(List.of(new ForkSpec<>(0, JsonCliqueConfigOptions.DEFAULT))); final ProtocolSchedule protocolSchedule = diff --git a/consensus/clique/src/test/java/org/hyperledger/besu/consensus/clique/blockcreation/CliqueBlockCreatorTest.java b/consensus/clique/src/test/java/org/hyperledger/besu/consensus/clique/blockcreation/CliqueBlockCreatorTest.java index 0ece2823327..51c55e52935 100644 --- a/consensus/clique/src/test/java/org/hyperledger/besu/consensus/clique/blockcreation/CliqueBlockCreatorTest.java +++ b/consensus/clique/src/test/java/org/hyperledger/besu/consensus/clique/blockcreation/CliqueBlockCreatorTest.java @@ -22,7 +22,7 @@ import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; -import org.hyperledger.besu.config.GenesisConfigFile; +import org.hyperledger.besu.config.GenesisConfig; import org.hyperledger.besu.consensus.clique.CliqueBlockInterface; import org.hyperledger.besu.consensus.clique.CliqueContext; import org.hyperledger.besu.consensus.clique.CliqueExtraData; @@ -110,7 +110,7 @@ void setup() { protocolSchedule = CliqueProtocolSchedule.create( - GenesisConfigFile.DEFAULT.getConfigOptions(), + GenesisConfig.DEFAULT.getConfigOptions(), new ForksSchedule<>(List.of()), proposerNodeKey, PrivacyParameters.DEFAULT, @@ -125,7 +125,7 @@ void setup() { CliqueHelpers.setCliqueContext(cliqueContext); final Block genesis = - GenesisState.fromConfig(GenesisConfigFile.mainnet(), protocolSchedule).getBlock(); + GenesisState.fromConfig(GenesisConfig.mainnet(), protocolSchedule).getBlock(); blockchain = createInMemoryBlockchain(genesis); protocolContext = new ProtocolContext(blockchain, stateArchive, cliqueContext, new BadBlockManager()); diff --git a/consensus/clique/src/test/java/org/hyperledger/besu/consensus/clique/blockcreation/CliqueMinerExecutorTest.java b/consensus/clique/src/test/java/org/hyperledger/besu/consensus/clique/blockcreation/CliqueMinerExecutorTest.java index 377757a322b..cd2130599e5 100644 --- a/consensus/clique/src/test/java/org/hyperledger/besu/consensus/clique/blockcreation/CliqueMinerExecutorTest.java +++ b/consensus/clique/src/test/java/org/hyperledger/besu/consensus/clique/blockcreation/CliqueMinerExecutorTest.java @@ -20,7 +20,7 @@ import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; -import org.hyperledger.besu.config.GenesisConfigFile; +import org.hyperledger.besu.config.GenesisConfig; import org.hyperledger.besu.config.GenesisConfigOptions; import org.hyperledger.besu.consensus.clique.CliqueBlockHeaderFunctions; import org.hyperledger.besu.consensus.clique.CliqueBlockInterface; @@ -74,7 +74,7 @@ public class CliqueMinerExecutorTest { private static final int EPOCH_LENGTH = 10; private static final GenesisConfigOptions GENESIS_CONFIG_OPTIONS = - GenesisConfigFile.fromConfig("{}").getConfigOptions(); + GenesisConfig.fromConfig("{}").getConfigOptions(); private final NodeKey proposerNodeKey = NodeKeyUtils.generate(); private final Random random = new Random(21341234L); private Address localAddress; diff --git a/consensus/ibft/src/test/java/org/hyperledger/besu/consensus/ibft/blockcreation/BftBlockCreatorTest.java b/consensus/ibft/src/test/java/org/hyperledger/besu/consensus/ibft/blockcreation/BftBlockCreatorTest.java index df5a313ae77..a4373b2aa36 100644 --- a/consensus/ibft/src/test/java/org/hyperledger/besu/consensus/ibft/blockcreation/BftBlockCreatorTest.java +++ b/consensus/ibft/src/test/java/org/hyperledger/besu/consensus/ibft/blockcreation/BftBlockCreatorTest.java @@ -23,7 +23,7 @@ import static org.mockito.Mockito.when; import org.hyperledger.besu.config.BftConfigOptions; -import org.hyperledger.besu.config.GenesisConfigFile; +import org.hyperledger.besu.config.GenesisConfig; import org.hyperledger.besu.config.GenesisConfigOptions; import org.hyperledger.besu.consensus.common.ForkSpec; import org.hyperledger.besu.consensus.common.ForksSchedule; @@ -110,8 +110,7 @@ public BlockHeaderValidator.Builder createBlockHeaderRuleset( } }; final GenesisConfigOptions configOptions = - GenesisConfigFile.fromConfig("{\"config\": {\"spuriousDragonBlock\":0}}") - .getConfigOptions(); + GenesisConfig.fromConfig("{\"config\": {\"spuriousDragonBlock\":0}}").getConfigOptions(); final ForksSchedule forksSchedule = new ForksSchedule<>(List.of(new ForkSpec<>(0, configOptions.getBftConfigOptions()))); final ProtocolSchedule protocolSchedule = diff --git a/consensus/merge/src/test/java/org/hyperledger/besu/consensus/merge/MergeProtocolScheduleTest.java b/consensus/merge/src/test/java/org/hyperledger/besu/consensus/merge/MergeProtocolScheduleTest.java index 2fff61a8299..9bf74d0d085 100644 --- a/consensus/merge/src/test/java/org/hyperledger/besu/consensus/merge/MergeProtocolScheduleTest.java +++ b/consensus/merge/src/test/java/org/hyperledger/besu/consensus/merge/MergeProtocolScheduleTest.java @@ -16,7 +16,7 @@ import static org.assertj.core.api.Assertions.assertThat; -import org.hyperledger.besu.config.GenesisConfigFile; +import org.hyperledger.besu.config.GenesisConfig; import org.hyperledger.besu.config.GenesisConfigOptions; import org.hyperledger.besu.datatypes.Wei; import org.hyperledger.besu.ethereum.chain.BadBlockManager; @@ -46,7 +46,7 @@ public void protocolSpecsAreCreatedAtBlockDefinedInJson() { + "\"LondonBlock\": 1559}" + "}"; - final GenesisConfigOptions config = GenesisConfigFile.fromConfig(jsonInput).getConfigOptions(); + final GenesisConfigOptions config = GenesisConfig.fromConfig(jsonInput).getConfigOptions(); final ProtocolSchedule protocolSchedule = MergeProtocolSchedule.create( config, @@ -67,7 +67,7 @@ public void protocolSpecsAreCreatedAtBlockDefinedInJson() { @Test public void mergeSpecificModificationsAreUnappliedForShanghai() { - final GenesisConfigOptions config = GenesisConfigFile.mainnet().getConfigOptions(); + final GenesisConfigOptions config = GenesisConfig.mainnet().getConfigOptions(); final ProtocolSchedule protocolSchedule = MergeProtocolSchedule.create( config, @@ -108,7 +108,7 @@ public void mergeSpecificModificationsAreUnappliedForCancun_whenShanghaiNotConfi + "\"cancunTime\": 1000}" + "}"; - final GenesisConfigOptions config = GenesisConfigFile.fromConfig(jsonInput).getConfigOptions(); + final GenesisConfigOptions config = GenesisConfig.fromConfig(jsonInput).getConfigOptions(); final ProtocolSchedule protocolSchedule = MergeProtocolSchedule.create( config, @@ -141,7 +141,7 @@ public void mergeSpecificModificationsAreUnappliedForCancun_whenShanghaiNotConfi @Test public void mergeSpecificModificationsAreUnappliedForAllMainnetForksAfterParis() { - final GenesisConfigOptions config = GenesisConfigFile.mainnet().getConfigOptions(); + final GenesisConfigOptions config = GenesisConfig.mainnet().getConfigOptions(); final ProtocolSchedule protocolSchedule = MergeProtocolSchedule.create( config, @@ -178,7 +178,7 @@ public void mergeSpecificModificationsAreUnappliedForAllMainnetForksAfterParis() public void parametersAlignWithMainnetWithAdjustments() { final ProtocolSpec london = MergeProtocolSchedule.create( - GenesisConfigFile.DEFAULT.getConfigOptions(), + GenesisConfig.DEFAULT.getConfigOptions(), false, MiningConfiguration.MINING_DISABLED, new BadBlockManager(), diff --git a/consensus/merge/src/test/java/org/hyperledger/besu/consensus/merge/blockcreation/MergeCoordinatorTest.java b/consensus/merge/src/test/java/org/hyperledger/besu/consensus/merge/blockcreation/MergeCoordinatorTest.java index 90c4b6866e4..ea1fa73eaa5 100644 --- a/consensus/merge/src/test/java/org/hyperledger/besu/consensus/merge/blockcreation/MergeCoordinatorTest.java +++ b/consensus/merge/src/test/java/org/hyperledger/besu/consensus/merge/blockcreation/MergeCoordinatorTest.java @@ -132,7 +132,7 @@ public class MergeCoordinatorTest implements MergeGenesisConfigHelper { @Mock EthScheduler ethScheduler; - private final Address coinbase = genesisAllocations(getPosGenesisConfigFile()).findFirst().get(); + private final Address coinbase = genesisAllocations(getPosGenesisConfig()).findFirst().get(); private MiningConfiguration miningConfiguration = ImmutableMiningConfiguration.builder() @@ -148,7 +148,7 @@ public class MergeCoordinatorTest implements MergeGenesisConfigHelper { private final ProtocolSchedule protocolSchedule = spy(getMergeProtocolSchedule()); private final GenesisState genesisState = - GenesisState.fromConfig(getPosGenesisConfigFile(), protocolSchedule); + GenesisState.fromConfig(getPosGenesisConfig(), protocolSchedule); private final WorldStateArchive worldStateArchive = createInMemoryWorldStateArchive(); diff --git a/consensus/merge/src/test/java/org/hyperledger/besu/consensus/merge/blockcreation/MergeGenesisConfigHelper.java b/consensus/merge/src/test/java/org/hyperledger/besu/consensus/merge/blockcreation/MergeGenesisConfigHelper.java index 582c8c5dd55..49174351cb0 100644 --- a/consensus/merge/src/test/java/org/hyperledger/besu/consensus/merge/blockcreation/MergeGenesisConfigHelper.java +++ b/consensus/merge/src/test/java/org/hyperledger/besu/consensus/merge/blockcreation/MergeGenesisConfigHelper.java @@ -15,7 +15,7 @@ package org.hyperledger.besu.consensus.merge.blockcreation; import org.hyperledger.besu.config.GenesisAccount; -import org.hyperledger.besu.config.GenesisConfigFile; +import org.hyperledger.besu.config.GenesisConfig; import org.hyperledger.besu.consensus.merge.MergeProtocolSchedule; import org.hyperledger.besu.datatypes.Address; import org.hyperledger.besu.ethereum.chain.BadBlockManager; @@ -30,31 +30,31 @@ public interface MergeGenesisConfigHelper { - default GenesisConfigFile getPosGenesisConfigFile() { + default GenesisConfig getPosGenesisConfig() { try { final URI uri = MergeGenesisConfigHelper.class.getResource("/posAtGenesis.json").toURI(); - return GenesisConfigFile.fromSource(uri.toURL()); + return GenesisConfig.fromSource(uri.toURL()); } catch (final URISyntaxException | IOException e) { throw new IllegalStateException(e); } } - default GenesisConfigFile getPowGenesisConfigFile() { + default GenesisConfig getPowGenesisConfig() { try { final URI uri = MergeGenesisConfigHelper.class.getResource("/powAtGenesis.json").toURI(); - return GenesisConfigFile.fromSource(uri.toURL()); + return GenesisConfig.fromSource(uri.toURL()); } catch (final URISyntaxException | IOException e) { throw new IllegalStateException(e); } } - default Stream

genesisAllocations(final GenesisConfigFile configFile) { + default Stream
genesisAllocations(final GenesisConfig configFile) { return configFile.streamAllocations().map(GenesisAccount::address); } default ProtocolSchedule getMergeProtocolSchedule() { return MergeProtocolSchedule.create( - getPosGenesisConfigFile().getConfigOptions(), + getPosGenesisConfig().getConfigOptions(), false, MiningConfiguration.MINING_DISABLED, new BadBlockManager(), diff --git a/consensus/merge/src/test/java/org/hyperledger/besu/consensus/merge/blockcreation/MergeReorgTest.java b/consensus/merge/src/test/java/org/hyperledger/besu/consensus/merge/blockcreation/MergeReorgTest.java index 22153eeceee..7ec2df35f23 100644 --- a/consensus/merge/src/test/java/org/hyperledger/besu/consensus/merge/blockcreation/MergeReorgTest.java +++ b/consensus/merge/src/test/java/org/hyperledger/besu/consensus/merge/blockcreation/MergeReorgTest.java @@ -70,7 +70,7 @@ public class MergeReorgTest implements MergeGenesisConfigHelper { private final MergeContext mergeContext = PostMergeContext.get(); private final ProtocolSchedule mockProtocolSchedule = getMergeProtocolSchedule(); private final GenesisState genesisState = - GenesisState.fromConfig(getPowGenesisConfigFile(), mockProtocolSchedule); + GenesisState.fromConfig(getPowGenesisConfig(), mockProtocolSchedule); private final WorldStateArchive worldStateArchive = createInMemoryWorldStateArchive(); private final MutableBlockchain blockchain = createInMemoryBlockchain(genesisState.getBlock()); @@ -78,7 +78,7 @@ public class MergeReorgTest implements MergeGenesisConfigHelper { private final ProtocolContext protocolContext = new ProtocolContext(blockchain, worldStateArchive, mergeContext, new BadBlockManager()); - private final Address coinbase = genesisAllocations(getPowGenesisConfigFile()).findFirst().get(); + private final Address coinbase = genesisAllocations(getPowGenesisConfig()).findFirst().get(); private final BlockHeaderTestFixture headerGenerator = new BlockHeaderTestFixture(); private final BaseFeeMarket feeMarket = new LondonFeeMarket(0, genesisState.getBlock().getHeader().getBaseFee()); @@ -132,7 +132,7 @@ public void reorgsAcrossTDDToDifferentTargetsWhenNotFinal() { Difficulty tdd = blockchain.getTotalDifficultyByHash(ttdA.getHash()).get(); assertThat(tdd.getAsBigInteger()) .isGreaterThan( - getPosGenesisConfigFile() + getPosGenesisConfig() .getConfigOptions() .getTerminalTotalDifficulty() .get() diff --git a/consensus/qbft/src/integration-test/java/org/hyperledger/besu/consensus/qbft/support/TestContextBuilder.java b/consensus/qbft/src/integration-test/java/org/hyperledger/besu/consensus/qbft/support/TestContextBuilder.java index a9de97ae18a..426d18e3e1d 100644 --- a/consensus/qbft/src/integration-test/java/org/hyperledger/besu/consensus/qbft/support/TestContextBuilder.java +++ b/consensus/qbft/src/integration-test/java/org/hyperledger/besu/consensus/qbft/support/TestContextBuilder.java @@ -23,7 +23,7 @@ import static org.mockito.Mockito.when; import org.hyperledger.besu.config.BftFork; -import org.hyperledger.besu.config.GenesisConfigFile; +import org.hyperledger.besu.config.GenesisConfig; import org.hyperledger.besu.config.JsonQbftConfigOptions; import org.hyperledger.besu.config.JsonUtil; import org.hyperledger.besu.config.QbftConfigOptions; @@ -367,7 +367,7 @@ private static Block createGenesisBlock(final Set
validators) { private GenesisState createGenesisBlock(final String genesisFile) throws IOException { return GenesisState.fromConfig( - GenesisConfigFile.fromSource(Path.of(genesisFile).toUri().toURL()), + GenesisConfig.fromSource(Path.of(genesisFile).toUri().toURL()), ProtocolScheduleFixture.MAINNET); } diff --git a/ethereum/api/src/integration-test/java/org/hyperledger/besu/ethereum/api/jsonrpc/BlockchainImporter.java b/ethereum/api/src/integration-test/java/org/hyperledger/besu/ethereum/api/jsonrpc/BlockchainImporter.java index 7e1be90e10e..307979f827f 100644 --- a/ethereum/api/src/integration-test/java/org/hyperledger/besu/ethereum/api/jsonrpc/BlockchainImporter.java +++ b/ethereum/api/src/integration-test/java/org/hyperledger/besu/ethereum/api/jsonrpc/BlockchainImporter.java @@ -14,7 +14,7 @@ */ package org.hyperledger.besu.ethereum.api.jsonrpc; -import org.hyperledger.besu.config.GenesisConfigFile; +import org.hyperledger.besu.config.GenesisConfig; import org.hyperledger.besu.ethereum.chain.BadBlockManager; import org.hyperledger.besu.ethereum.chain.GenesisState; import org.hyperledger.besu.ethereum.core.Block; @@ -45,7 +45,7 @@ public class BlockchainImporter { public BlockchainImporter(final URL blocksUrl, final String genesisJson) throws Exception { protocolSchedule = MainnetProtocolSchedule.fromConfig( - GenesisConfigFile.fromConfig(genesisJson).getConfigOptions(), + GenesisConfig.fromConfig(genesisJson).getConfigOptions(), MiningConfiguration.newDefault(), new BadBlockManager(), false, diff --git a/ethereum/blockcreation/src/test/java/org/hyperledger/besu/ethereum/blockcreation/AbstractBlockCreatorTest.java b/ethereum/blockcreation/src/test/java/org/hyperledger/besu/ethereum/blockcreation/AbstractBlockCreatorTest.java index b70c48ad026..4c4bf134855 100644 --- a/ethereum/blockcreation/src/test/java/org/hyperledger/besu/ethereum/blockcreation/AbstractBlockCreatorTest.java +++ b/ethereum/blockcreation/src/test/java/org/hyperledger/besu/ethereum/blockcreation/AbstractBlockCreatorTest.java @@ -24,7 +24,7 @@ import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; -import org.hyperledger.besu.config.GenesisConfigFile; +import org.hyperledger.besu.config.GenesisConfig; import org.hyperledger.besu.crypto.KeyPair; import org.hyperledger.besu.crypto.SECPPrivateKey; import org.hyperledger.besu.crypto.SignatureAlgorithm; @@ -298,12 +298,12 @@ record CreateOn(AbstractBlockCreator blockCreator, BlockHeader parentHeader) {} private CreateOn createBlockCreator(final ProtocolSpecAdapters protocolSpecAdapters) { - final var genesisConfigFile = GenesisConfigFile.fromResource("/block-creation-genesis.json"); + final var genesisConfig = GenesisConfig.fromResource("/block-creation-genesis.json"); final ExecutionContextTestFixture executionContextTestFixture = - ExecutionContextTestFixture.builder(genesisConfigFile) + ExecutionContextTestFixture.builder(genesisConfig) .protocolSchedule( new ProtocolScheduleBuilder( - genesisConfigFile.getConfigOptions(), + genesisConfig.getConfigOptions(), Optional.of(BigInteger.valueOf(42)), protocolSpecAdapters, PrivacyParameters.DEFAULT, diff --git a/ethereum/blockcreation/src/test/java/org/hyperledger/besu/ethereum/blockcreation/AbstractBlockTransactionSelectorTest.java b/ethereum/blockcreation/src/test/java/org/hyperledger/besu/ethereum/blockcreation/AbstractBlockTransactionSelectorTest.java index 2787189ece7..202b0fdee66 100644 --- a/ethereum/blockcreation/src/test/java/org/hyperledger/besu/ethereum/blockcreation/AbstractBlockTransactionSelectorTest.java +++ b/ethereum/blockcreation/src/test/java/org/hyperledger/besu/ethereum/blockcreation/AbstractBlockTransactionSelectorTest.java @@ -33,7 +33,7 @@ import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; -import org.hyperledger.besu.config.GenesisConfigFile; +import org.hyperledger.besu.config.GenesisConfig; import org.hyperledger.besu.crypto.KeyPair; import org.hyperledger.besu.crypto.SignatureAlgorithmFactory; import org.hyperledger.besu.datatypes.Address; @@ -132,7 +132,7 @@ public abstract class AbstractBlockTransactionSelectorTest { Address.extract(Hash.hash(keyPair.getPublicKey().getEncodedBytes())); protected final MetricsSystem metricsSystem = new NoOpMetricsSystem(); - protected GenesisConfigFile genesisConfigFile; + protected GenesisConfig genesisConfig; protected MutableBlockchain blockchain; protected TransactionPool transactionPool; protected MutableWorldState worldState; @@ -152,7 +152,7 @@ public abstract class AbstractBlockTransactionSelectorTest { @BeforeEach public void setup() { - genesisConfigFile = getGenesisConfigFile(); + genesisConfig = getGenesisConfig(); protocolSchedule = createProtocolSchedule(); transactionSelectionService = new TransactionSelectionServiceImpl(); defaultTestMiningConfiguration = @@ -162,8 +162,7 @@ public void setup() { MIN_OCCUPANCY_80_PERCENT, DEFAULT_NON_POA_BLOCK_TXS_SELECTION_MAX_TIME); - final Block genesisBlock = - GenesisState.fromConfig(genesisConfigFile, protocolSchedule).getBlock(); + final Block genesisBlock = GenesisState.fromConfig(genesisConfig, protocolSchedule).getBlock(); blockchain = DefaultBlockchain.createMutable( @@ -198,7 +197,7 @@ public void setup() { }); } - protected abstract GenesisConfigFile getGenesisConfigFile(); + protected abstract GenesisConfig getGenesisConfig(); protected abstract ProtocolSchedule createProtocolSchedule(); @@ -232,7 +231,7 @@ protected ProcessableBlockHeader createBlock(final long gasLimit, final Wei base public void emptyPendingTransactionsResultsInEmptyVettingResult() { final ProtocolSchedule protocolSchedule = FixedDifficultyProtocolSchedule.create( - GenesisConfigFile.fromResource("/dev.json").getConfigOptions(), + GenesisConfig.fromResource("/dev.json").getConfigOptions(), EvmConfiguration.DEFAULT, MiningConfiguration.MINING_DISABLED, new BadBlockManager(), diff --git a/ethereum/blockcreation/src/test/java/org/hyperledger/besu/ethereum/blockcreation/LegacyFeeMarketBlockTransactionSelectorTest.java b/ethereum/blockcreation/src/test/java/org/hyperledger/besu/ethereum/blockcreation/LegacyFeeMarketBlockTransactionSelectorTest.java index 327d4bd37d0..4aad300d511 100644 --- a/ethereum/blockcreation/src/test/java/org/hyperledger/besu/ethereum/blockcreation/LegacyFeeMarketBlockTransactionSelectorTest.java +++ b/ethereum/blockcreation/src/test/java/org/hyperledger/besu/ethereum/blockcreation/LegacyFeeMarketBlockTransactionSelectorTest.java @@ -19,7 +19,7 @@ import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; -import org.hyperledger.besu.config.GenesisConfigFile; +import org.hyperledger.besu.config.GenesisConfig; import org.hyperledger.besu.datatypes.Wei; import org.hyperledger.besu.ethereum.chain.BadBlockManager; import org.hyperledger.besu.ethereum.core.MiningConfiguration; @@ -49,14 +49,14 @@ public class LegacyFeeMarketBlockTransactionSelectorTest extends AbstractBlockTransactionSelectorTest { @Override - protected GenesisConfigFile getGenesisConfigFile() { - return GenesisConfigFile.fromResource("/block-transaction-selector/gas-price-genesis.json"); + protected GenesisConfig getGenesisConfig() { + return GenesisConfig.fromResource("/block-transaction-selector/gas-price-genesis.json"); } @Override protected ProtocolSchedule createProtocolSchedule() { return new ProtocolScheduleBuilder( - genesisConfigFile.getConfigOptions(), + genesisConfig.getConfigOptions(), Optional.of(CHAIN_ID), ProtocolSpecAdapters.create(0, Function.identity()), new PrivacyParameters(), diff --git a/ethereum/blockcreation/src/test/java/org/hyperledger/besu/ethereum/blockcreation/LondonFeeMarketBlockTransactionSelectorTest.java b/ethereum/blockcreation/src/test/java/org/hyperledger/besu/ethereum/blockcreation/LondonFeeMarketBlockTransactionSelectorTest.java index 62eaf713c54..eb77c6df658 100644 --- a/ethereum/blockcreation/src/test/java/org/hyperledger/besu/ethereum/blockcreation/LondonFeeMarketBlockTransactionSelectorTest.java +++ b/ethereum/blockcreation/src/test/java/org/hyperledger/besu/ethereum/blockcreation/LondonFeeMarketBlockTransactionSelectorTest.java @@ -19,7 +19,7 @@ import static org.hyperledger.besu.ethereum.core.MiningConfiguration.DEFAULT_NON_POA_BLOCK_TXS_SELECTION_MAX_TIME; import static org.mockito.Mockito.mock; -import org.hyperledger.besu.config.GenesisConfigFile; +import org.hyperledger.besu.config.GenesisConfig; import org.hyperledger.besu.datatypes.Address; import org.hyperledger.besu.datatypes.Wei; import org.hyperledger.besu.ethereum.blockcreation.txselection.BlockTransactionSelector; @@ -60,14 +60,14 @@ public class LondonFeeMarketBlockTransactionSelectorTest extends AbstractBlockTransactionSelectorTest { @Override - protected GenesisConfigFile getGenesisConfigFile() { - return GenesisConfigFile.fromResource("/block-transaction-selector/london-genesis.json"); + protected GenesisConfig getGenesisConfig() { + return GenesisConfig.fromResource("/block-transaction-selector/london-genesis.json"); } @Override protected ProtocolSchedule createProtocolSchedule() { return new ProtocolScheduleBuilder( - genesisConfigFile.getConfigOptions(), + genesisConfig.getConfigOptions(), Optional.of(CHAIN_ID), ProtocolSpecAdapters.create(0, Function.identity()), new PrivacyParameters(), diff --git a/ethereum/blockcreation/src/test/java/org/hyperledger/besu/ethereum/blockcreation/PoWBlockCreatorTest.java b/ethereum/blockcreation/src/test/java/org/hyperledger/besu/ethereum/blockcreation/PoWBlockCreatorTest.java index e8b9baa0a73..8813fcf38c7 100644 --- a/ethereum/blockcreation/src/test/java/org/hyperledger/besu/ethereum/blockcreation/PoWBlockCreatorTest.java +++ b/ethereum/blockcreation/src/test/java/org/hyperledger/besu/ethereum/blockcreation/PoWBlockCreatorTest.java @@ -20,7 +20,7 @@ import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; -import org.hyperledger.besu.config.GenesisConfigFile; +import org.hyperledger.besu.config.GenesisConfig; import org.hyperledger.besu.datatypes.Address; import org.hyperledger.besu.datatypes.Hash; import org.hyperledger.besu.datatypes.Wei; @@ -85,15 +85,15 @@ class PoWBlockCreatorTest extends AbstractBlockCreatorTest { @Test void createMainnetBlock1() throws IOException { - final var genesisConfigFile = GenesisConfigFile.mainnet(); + final var genesisConfig = GenesisConfig.mainnet(); final MiningConfiguration miningConfiguration = createMiningParameters(BLOCK_1_NONCE); final ExecutionContextTestFixture executionContextTestFixture = - ExecutionContextTestFixture.builder(genesisConfigFile) + ExecutionContextTestFixture.builder(genesisConfig) .protocolSchedule( new ProtocolScheduleBuilder( - genesisConfigFile.getConfigOptions(), + genesisConfig.getConfigOptions(), Optional.of(BigInteger.valueOf(42)), ProtocolSpecAdapters.create(0, Function.identity()), PrivacyParameters.DEFAULT, @@ -143,23 +143,23 @@ void createMainnetBlock1() throws IOException { @Test void createMainnetBlock1_fixedDifficulty1() { - final var genesisConfigFile = - GenesisConfigFile.fromResource("/block-creation-fixed-difficulty-genesis.json"); + final var genesisConfig = + GenesisConfig.fromResource("/block-creation-fixed-difficulty-genesis.json"); final MiningConfiguration miningConfiguration = createMiningParameters(FIXED_DIFFICULTY_NONCE); final ExecutionContextTestFixture executionContextTestFixture = - ExecutionContextTestFixture.builder(genesisConfigFile) + ExecutionContextTestFixture.builder(genesisConfig) .protocolSchedule( new ProtocolScheduleBuilder( - genesisConfigFile.getConfigOptions(), + genesisConfig.getConfigOptions(), Optional.of(BigInteger.valueOf(42)), ProtocolSpecAdapters.create( 0, specBuilder -> specBuilder.difficultyCalculator( FixedDifficultyCalculators.calculator( - genesisConfigFile.getConfigOptions()))), + genesisConfig.getConfigOptions()))), PrivacyParameters.DEFAULT, false, EvmConfiguration.DEFAULT, @@ -201,21 +201,21 @@ void createMainnetBlock1_fixedDifficulty1() { @Test void rewardBeneficiary_zeroReward_skipZeroRewardsFalse() { - final var genesisConfigFile = - GenesisConfigFile.fromResource("/block-creation-fixed-difficulty-genesis.json"); + final var genesisConfig = + GenesisConfig.fromResource("/block-creation-fixed-difficulty-genesis.json"); final MiningConfiguration miningConfiguration = createMiningParameters(FIXED_DIFFICULTY_NONCE); ProtocolSchedule protocolSchedule = new ProtocolScheduleBuilder( - genesisConfigFile.getConfigOptions(), + genesisConfig.getConfigOptions(), Optional.of(BigInteger.valueOf(42)), ProtocolSpecAdapters.create( 0, specBuilder -> specBuilder.difficultyCalculator( FixedDifficultyCalculators.calculator( - genesisConfigFile.getConfigOptions()))), + genesisConfig.getConfigOptions()))), PrivacyParameters.DEFAULT, false, EvmConfiguration.DEFAULT, @@ -225,7 +225,7 @@ void rewardBeneficiary_zeroReward_skipZeroRewardsFalse() { new NoOpMetricsSystem()) .createProtocolSchedule(); final ExecutionContextTestFixture executionContextTestFixture = - ExecutionContextTestFixture.builder(genesisConfigFile) + ExecutionContextTestFixture.builder(genesisConfig) .protocolSchedule(protocolSchedule) .build(); @@ -278,21 +278,21 @@ void rewardBeneficiary_zeroReward_skipZeroRewardsFalse() { @Test void rewardBeneficiary_zeroReward_skipZeroRewardsTrue() { - final var genesisConfigFile = - GenesisConfigFile.fromResource("/block-creation-fixed-difficulty-genesis.json"); + final var genesisConfig = + GenesisConfig.fromResource("/block-creation-fixed-difficulty-genesis.json"); final MiningConfiguration miningConfiguration = createMiningParameters(FIXED_DIFFICULTY_NONCE); ProtocolSchedule protocolSchedule = new ProtocolScheduleBuilder( - genesisConfigFile.getConfigOptions(), + genesisConfig.getConfigOptions(), Optional.of(BigInteger.valueOf(42)), ProtocolSpecAdapters.create( 0, specBuilder -> specBuilder.difficultyCalculator( FixedDifficultyCalculators.calculator( - genesisConfigFile.getConfigOptions()))), + genesisConfig.getConfigOptions()))), PrivacyParameters.DEFAULT, false, EvmConfiguration.DEFAULT, @@ -302,7 +302,7 @@ void rewardBeneficiary_zeroReward_skipZeroRewardsTrue() { new NoOpMetricsSystem()) .createProtocolSchedule(); final ExecutionContextTestFixture executionContextTestFixture = - ExecutionContextTestFixture.builder(genesisConfigFile) + ExecutionContextTestFixture.builder(genesisConfig) .protocolSchedule(protocolSchedule) .build(); diff --git a/ethereum/core/src/integration-test/java/org/hyperledger/besu/ethereum/vm/TraceTransactionIntegrationTest.java b/ethereum/core/src/integration-test/java/org/hyperledger/besu/ethereum/vm/TraceTransactionIntegrationTest.java index a029c4b4a49..5ad9635a263 100644 --- a/ethereum/core/src/integration-test/java/org/hyperledger/besu/ethereum/vm/TraceTransactionIntegrationTest.java +++ b/ethereum/core/src/integration-test/java/org/hyperledger/besu/ethereum/vm/TraceTransactionIntegrationTest.java @@ -18,7 +18,7 @@ import static org.assertj.core.api.Assertions.entry; import static org.hyperledger.besu.evm.operation.BlockHashOperation.BlockHashLookup; -import org.hyperledger.besu.config.GenesisConfigFile; +import org.hyperledger.besu.config.GenesisConfig; import org.hyperledger.besu.crypto.KeyPair; import org.hyperledger.besu.crypto.SignatureAlgorithmFactory; import org.hyperledger.besu.datatypes.TransactionType; @@ -70,8 +70,7 @@ public class TraceTransactionIntegrationTest { @BeforeEach public void setUp() { final ExecutionContextTestFixture contextTestFixture = - ExecutionContextTestFixture.builder(GenesisConfigFile.fromResource("/genesis-it.json")) - .build(); + ExecutionContextTestFixture.builder(GenesisConfig.fromResource("/genesis-it.json")).build(); genesisBlock = contextTestFixture.getGenesis(); blockchain = contextTestFixture.getBlockchain(); worldStateArchive = contextTestFixture.getStateArchive(); diff --git a/ethereum/core/src/jmh/java/org/hyperledger/besu/ethereum/vm/operations/OperationBenchmarkHelper.java b/ethereum/core/src/jmh/java/org/hyperledger/besu/ethereum/vm/operations/OperationBenchmarkHelper.java index 4289a91a3c8..cff04abbdc5 100644 --- a/ethereum/core/src/jmh/java/org/hyperledger/besu/ethereum/vm/operations/OperationBenchmarkHelper.java +++ b/ethereum/core/src/jmh/java/org/hyperledger/besu/ethereum/vm/operations/OperationBenchmarkHelper.java @@ -16,7 +16,7 @@ import static java.util.Collections.emptyList; -import org.hyperledger.besu.config.GenesisConfigFile; +import org.hyperledger.besu.config.GenesisConfig; import org.hyperledger.besu.ethereum.chain.Blockchain; import org.hyperledger.besu.ethereum.chain.MutableBlockchain; import org.hyperledger.besu.ethereum.core.Block; @@ -75,7 +75,7 @@ public static OperationBenchmarkHelper create() throws IOException { KeyValueSegmentIdentifier.BLOCKCHAIN, optimisticRocksDBColumnarKeyValueStorage); final ExecutionContextTestFixture executionContext = - ExecutionContextTestFixture.builder(GenesisConfigFile.fromResource("/genesis-jmh.json")) + ExecutionContextTestFixture.builder(GenesisConfig.fromResource("/genesis-jmh.json")) .blockchainKeyValueStorage(keyValueStorage) .build(); final MutableBlockchain blockchain = executionContext.getBlockchain(); diff --git a/ethereum/core/src/main/java/org/hyperledger/besu/ethereum/chain/GenesisState.java b/ethereum/core/src/main/java/org/hyperledger/besu/ethereum/chain/GenesisState.java index 0dcc3450121..56c33e55c7d 100644 --- a/ethereum/core/src/main/java/org/hyperledger/besu/ethereum/chain/GenesisState.java +++ b/ethereum/core/src/main/java/org/hyperledger/besu/ethereum/chain/GenesisState.java @@ -18,7 +18,7 @@ import static org.hyperledger.besu.ethereum.trie.common.GenesisWorldStateProvider.createGenesisWorldState; import org.hyperledger.besu.config.GenesisAccount; -import org.hyperledger.besu.config.GenesisConfigFile; +import org.hyperledger.besu.config.GenesisConfig; import org.hyperledger.besu.datatypes.Address; import org.hyperledger.besu.datatypes.BlobGas; import org.hyperledger.besu.datatypes.Hash; @@ -53,11 +53,11 @@ public final class GenesisState { private final Block block; - private final GenesisConfigFile genesisConfigFile; + private final GenesisConfig genesisConfig; - private GenesisState(final Block block, final GenesisConfigFile genesisConfigFile) { + private GenesisState(final Block block, final GenesisConfig genesisConfig) { this.block = block; - this.genesisConfigFile = genesisConfigFile; + this.genesisConfig = genesisConfig; } /** @@ -68,7 +68,7 @@ private GenesisState(final Block block, final GenesisConfigFile genesisConfigFil * @return A new {@link GenesisState}. */ public static GenesisState fromJson(final String json, final ProtocolSchedule protocolSchedule) { - return fromConfig(GenesisConfigFile.fromConfig(json), protocolSchedule); + return fromConfig(GenesisConfig.fromConfig(json), protocolSchedule); } /** @@ -86,18 +86,18 @@ static GenesisState fromJsonSource( final URL jsonSource, final ProtocolSchedule protocolSchedule) { return fromConfig( - dataStorageConfiguration, GenesisConfigFile.fromConfig(jsonSource), protocolSchedule); + dataStorageConfiguration, GenesisConfig.fromConfig(jsonSource), protocolSchedule); } /** * Construct a {@link GenesisState} from a genesis file object. * - * @param config A {@link GenesisConfigFile} describing the genesis block. + * @param config A {@link GenesisConfig} describing the genesis block. * @param protocolSchedule A protocol Schedule associated with * @return A new {@link GenesisState}. */ public static GenesisState fromConfig( - final GenesisConfigFile config, final ProtocolSchedule protocolSchedule) { + final GenesisConfig config, final ProtocolSchedule protocolSchedule) { return fromConfig(DataStorageConfiguration.DEFAULT_CONFIG, config, protocolSchedule); } @@ -106,43 +106,42 @@ public static GenesisState fromConfig( * * @param dataStorageConfiguration A {@link DataStorageConfiguration} describing the storage * configuration - * @param genesisConfigFile A {@link GenesisConfigFile} describing the genesis block. + * @param genesisConfig A {@link GenesisConfig} describing the genesis block. * @param protocolSchedule A protocol Schedule associated with * @return A new {@link GenesisState}. */ public static GenesisState fromConfig( final DataStorageConfiguration dataStorageConfiguration, - final GenesisConfigFile genesisConfigFile, + final GenesisConfig genesisConfig, final ProtocolSchedule protocolSchedule) { - final var genesisStateRoot = - calculateGenesisStateRoot(dataStorageConfiguration, genesisConfigFile); + final var genesisStateRoot = calculateGenesisStateRoot(dataStorageConfiguration, genesisConfig); final Block block = new Block( - buildHeader(genesisConfigFile, genesisStateRoot, protocolSchedule), - buildBody(genesisConfigFile)); - return new GenesisState(block, genesisConfigFile); + buildHeader(genesisConfig, genesisStateRoot, protocolSchedule), + buildBody(genesisConfig)); + return new GenesisState(block, genesisConfig); } /** * Construct a {@link GenesisState} from a JSON object. * * @param genesisStateRoot The root of the genesis state. - * @param genesisConfigFile A {@link GenesisConfigFile} describing the genesis block. + * @param genesisConfig A {@link GenesisConfig} describing the genesis block. * @param protocolSchedule A protocol Schedule associated with * @return A new {@link GenesisState}. */ public static GenesisState fromStorage( final Hash genesisStateRoot, - final GenesisConfigFile genesisConfigFile, + final GenesisConfig genesisConfig, final ProtocolSchedule protocolSchedule) { final Block block = new Block( - buildHeader(genesisConfigFile, genesisStateRoot, protocolSchedule), - buildBody(genesisConfigFile)); - return new GenesisState(block, genesisConfigFile); + buildHeader(genesisConfig, genesisStateRoot, protocolSchedule), + buildBody(genesisConfig)); + return new GenesisState(block, genesisConfig); } - private static BlockBody buildBody(final GenesisConfigFile config) { + private static BlockBody buildBody(final GenesisConfig config) { final Optional> withdrawals = isShanghaiAtGenesis(config) ? Optional.of(emptyList()) : Optional.empty(); @@ -159,7 +158,7 @@ public Block getBlock() { * @param target WorldView to write genesis state to */ public void writeStateTo(final MutableWorldState target) { - writeAccountsTo(target, genesisConfigFile.streamAllocations(), block.getHeader()); + writeAccountsTo(target, genesisConfig.streamAllocations(), block.getHeader()); } private static void writeAccountsTo( @@ -180,10 +179,9 @@ private static void writeAccountsTo( } private static Hash calculateGenesisStateRoot( - final DataStorageConfiguration dataStorageConfiguration, - final GenesisConfigFile genesisConfigFile) { + final DataStorageConfiguration dataStorageConfiguration, final GenesisConfig genesisConfig) { try (var worldState = createGenesisWorldState(dataStorageConfiguration)) { - writeAccountsTo(worldState, genesisConfigFile.streamAllocations(), null); + writeAccountsTo(worldState, genesisConfig.streamAllocations(), null); return worldState.rootHash(); } catch (Exception e) { throw new RuntimeException(e); @@ -191,7 +189,7 @@ private static Hash calculateGenesisStateRoot( } private static BlockHeader buildHeader( - final GenesisConfigFile genesis, + final GenesisConfig genesis, final Hash genesisRootHash, final ProtocolSchedule protocolSchedule) { @@ -228,7 +226,7 @@ private static BlockHeader buildHeader( .buildBlockHeader(); } - private static Address parseCoinbase(final GenesisConfigFile genesis) { + private static Address parseCoinbase(final GenesisConfig genesis) { return genesis .getCoinbase() .map(str -> withNiceErrorMessage("coinbase", str, Address::fromHexString)) @@ -250,39 +248,39 @@ private static IllegalArgumentException createInvalidBlockConfigException( "Invalid " + name + " in genesis block configuration: " + value, e); } - private static Hash parseParentHash(final GenesisConfigFile genesis) { + private static Hash parseParentHash(final GenesisConfig genesis) { return withNiceErrorMessage("parentHash", genesis.getParentHash(), Hash::fromHexStringLenient); } - private static Bytes parseExtraData(final GenesisConfigFile genesis) { + private static Bytes parseExtraData(final GenesisConfig genesis) { return withNiceErrorMessage("extraData", genesis.getExtraData(), Bytes::fromHexString); } - private static Difficulty parseDifficulty(final GenesisConfigFile genesis) { + private static Difficulty parseDifficulty(final GenesisConfig genesis) { return withNiceErrorMessage("difficulty", genesis.getDifficulty(), Difficulty::fromHexString); } - private static Hash parseMixHash(final GenesisConfigFile genesis) { + private static Hash parseMixHash(final GenesisConfig genesis) { return withNiceErrorMessage("mixHash", genesis.getMixHash(), Hash::fromHexStringLenient); } - private static long parseNonce(final GenesisConfigFile genesis) { + private static long parseNonce(final GenesisConfig genesis) { return withNiceErrorMessage("nonce", genesis.getNonce(), GenesisState::parseUnsignedLong); } - private static long parseBlobGasUsed(final GenesisConfigFile genesis) { + private static long parseBlobGasUsed(final GenesisConfig genesis) { return withNiceErrorMessage( "blobGasUsed", genesis.getBlobGasUsed(), GenesisState::parseUnsignedLong); } - private static BlobGas parseExcessBlobGas(final GenesisConfigFile genesis) { + private static BlobGas parseExcessBlobGas(final GenesisConfig genesis) { long excessBlobGas = withNiceErrorMessage( "excessBlobGas", genesis.getExcessBlobGas(), GenesisState::parseUnsignedLong); return BlobGas.of(excessBlobGas); } - private static Bytes32 parseParentBeaconBlockRoot(final GenesisConfigFile genesis) { + private static Bytes32 parseParentBeaconBlockRoot(final GenesisConfig genesis) { return withNiceErrorMessage( "parentBeaconBlockRoot", genesis.getParentBeaconBlockRoot(), Bytes32::fromHexString); } @@ -295,7 +293,7 @@ private static long parseUnsignedLong(final String value) { return Long.parseUnsignedLong(v, 16); } - private static boolean isShanghaiAtGenesis(final GenesisConfigFile genesis) { + private static boolean isShanghaiAtGenesis(final GenesisConfig genesis) { final OptionalLong shanghaiTimestamp = genesis.getConfigOptions().getShanghaiTime(); if (shanghaiTimestamp.isPresent()) { return genesis.getTimestamp() >= shanghaiTimestamp.getAsLong(); @@ -303,7 +301,7 @@ private static boolean isShanghaiAtGenesis(final GenesisConfigFile genesis) { return isCancunAtGenesis(genesis); } - private static boolean isCancunAtGenesis(final GenesisConfigFile genesis) { + private static boolean isCancunAtGenesis(final GenesisConfig genesis) { final OptionalLong cancunTimestamp = genesis.getConfigOptions().getCancunTime(); if (cancunTimestamp.isPresent()) { return genesis.getTimestamp() >= cancunTimestamp.getAsLong(); @@ -311,7 +309,7 @@ private static boolean isCancunAtGenesis(final GenesisConfigFile genesis) { return isPragueAtGenesis(genesis) || isCancunEOFAtGenesis(genesis); } - private static boolean isCancunEOFAtGenesis(final GenesisConfigFile genesis) { + private static boolean isCancunEOFAtGenesis(final GenesisConfig genesis) { final OptionalLong cancunEOFTimestamp = genesis.getConfigOptions().getCancunEOFTime(); if (cancunEOFTimestamp.isPresent()) { return genesis.getTimestamp() >= cancunEOFTimestamp.getAsLong(); @@ -319,7 +317,7 @@ private static boolean isCancunEOFAtGenesis(final GenesisConfigFile genesis) { return false; } - private static boolean isPragueAtGenesis(final GenesisConfigFile genesis) { + private static boolean isPragueAtGenesis(final GenesisConfig genesis) { final OptionalLong pragueTimestamp = genesis.getConfigOptions().getPragueTime(); if (pragueTimestamp.isPresent()) { return genesis.getTimestamp() >= pragueTimestamp.getAsLong(); @@ -327,7 +325,7 @@ private static boolean isPragueAtGenesis(final GenesisConfigFile genesis) { return isOsakaAtGenesis(genesis); } - private static boolean isOsakaAtGenesis(final GenesisConfigFile genesis) { + private static boolean isOsakaAtGenesis(final GenesisConfig genesis) { final OptionalLong osakaTimestamp = genesis.getConfigOptions().getOsakaTime(); if (osakaTimestamp.isPresent()) { return genesis.getTimestamp() >= osakaTimestamp.getAsLong(); @@ -335,7 +333,7 @@ private static boolean isOsakaAtGenesis(final GenesisConfigFile genesis) { return isFutureEipsTimeAtGenesis(genesis); } - private static boolean isFutureEipsTimeAtGenesis(final GenesisConfigFile genesis) { + private static boolean isFutureEipsTimeAtGenesis(final GenesisConfig genesis) { final OptionalLong futureEipsTime = genesis.getConfigOptions().getFutureEipsTime(); if (futureEipsTime.isPresent()) { return genesis.getTimestamp() >= futureEipsTime.getAsLong(); @@ -343,7 +341,7 @@ private static boolean isFutureEipsTimeAtGenesis(final GenesisConfigFile genesis return isExperimentalEipsTimeAtGenesis(genesis); } - private static boolean isExperimentalEipsTimeAtGenesis(final GenesisConfigFile genesis) { + private static boolean isExperimentalEipsTimeAtGenesis(final GenesisConfig genesis) { final OptionalLong experimentalEipsTime = genesis.getConfigOptions().getExperimentalEipsTime(); if (experimentalEipsTime.isPresent()) { return genesis.getTimestamp() >= experimentalEipsTime.getAsLong(); diff --git a/ethereum/core/src/main/java/org/hyperledger/besu/ethereum/mainnet/feemarket/LondonFeeMarket.java b/ethereum/core/src/main/java/org/hyperledger/besu/ethereum/mainnet/feemarket/LondonFeeMarket.java index d1a148ceedf..5ba94a78ad1 100644 --- a/ethereum/core/src/main/java/org/hyperledger/besu/ethereum/mainnet/feemarket/LondonFeeMarket.java +++ b/ethereum/core/src/main/java/org/hyperledger/besu/ethereum/mainnet/feemarket/LondonFeeMarket.java @@ -14,7 +14,7 @@ */ package org.hyperledger.besu.ethereum.mainnet.feemarket; -import org.hyperledger.besu.config.GenesisConfigFile; +import org.hyperledger.besu.config.GenesisConfig; import org.hyperledger.besu.datatypes.Wei; import org.hyperledger.besu.ethereum.core.Transaction; import org.hyperledger.besu.ethereum.core.feemarket.TransactionPriceCalculator; @@ -28,8 +28,7 @@ public class LondonFeeMarket implements BaseFeeMarket { private static final Logger LOG = LoggerFactory.getLogger(LondonFeeMarket.class); - static final Wei DEFAULT_BASEFEE_INITIAL_VALUE = - GenesisConfigFile.BASEFEE_AT_GENESIS_DEFAULT_VALUE; + static final Wei DEFAULT_BASEFEE_INITIAL_VALUE = GenesisConfig.BASEFEE_AT_GENESIS_DEFAULT_VALUE; static final long DEFAULT_BASEFEE_MAX_CHANGE_DENOMINATOR = 8L; static final long DEFAULT_SLACK_COEFFICIENT = 2L; diff --git a/ethereum/core/src/test-support/java/org/hyperledger/besu/ethereum/core/BlockchainSetupUtil.java b/ethereum/core/src/test-support/java/org/hyperledger/besu/ethereum/core/BlockchainSetupUtil.java index 3391a0e162c..b705ba01117 100644 --- a/ethereum/core/src/test-support/java/org/hyperledger/besu/ethereum/core/BlockchainSetupUtil.java +++ b/ethereum/core/src/test-support/java/org/hyperledger/besu/ethereum/core/BlockchainSetupUtil.java @@ -20,7 +20,7 @@ import static org.hyperledger.besu.ethereum.core.InMemoryKeyValueStorageProvider.createInMemoryWorldStateArchive; import static org.mockito.Mockito.mock; -import org.hyperledger.besu.config.GenesisConfigFile; +import org.hyperledger.besu.config.GenesisConfig; import org.hyperledger.besu.ethereum.ProtocolContext; import org.hyperledger.besu.ethereum.chain.BadBlockManager; import org.hyperledger.besu.ethereum.chain.Blockchain; @@ -147,9 +147,9 @@ public static BlockchainSetupUtil createForEthashChain( } private static ProtocolSchedule mainnetProtocolScheduleProvider( - final GenesisConfigFile genesisConfigFile) { + final GenesisConfig genesisConfig) { return MainnetProtocolSchedule.fromConfig( - genesisConfigFile.getConfigOptions(), + genesisConfig.getConfigOptions(), EvmConfiguration.DEFAULT, MiningConfiguration.newDefault(), new BadBlockManager(), @@ -170,12 +170,10 @@ private static BlockchainSetupUtil create( final ProtocolContextProvider protocolContextProvider, final EthScheduler scheduler) { try { - final GenesisConfigFile genesisConfigFile = - GenesisConfigFile.fromSource(chainResources.getGenesisURL()); - final ProtocolSchedule protocolSchedule = protocolScheduleProvider.get(genesisConfigFile); + final GenesisConfig genesisConfig = GenesisConfig.fromSource(chainResources.getGenesisURL()); + final ProtocolSchedule protocolSchedule = protocolScheduleProvider.get(genesisConfig); - final GenesisState genesisState = - GenesisState.fromConfig(genesisConfigFile, protocolSchedule); + final GenesisState genesisState = GenesisState.fromConfig(genesisConfig, protocolSchedule); final MutableBlockchain blockchain = createInMemoryBlockchain(genesisState.getBlock()); final WorldStateArchive worldArchive = storageFormat == DataStorageFormat.BONSAI @@ -267,7 +265,7 @@ private void importBlocks( } private interface ProtocolScheduleProvider { - ProtocolSchedule get(GenesisConfigFile genesisConfig); + ProtocolSchedule get(GenesisConfig genesisConfig); } private interface ProtocolContextProvider { diff --git a/ethereum/core/src/test-support/java/org/hyperledger/besu/ethereum/core/ExecutionContextTestFixture.java b/ethereum/core/src/test-support/java/org/hyperledger/besu/ethereum/core/ExecutionContextTestFixture.java index b4eaec04d3e..873490fd451 100644 --- a/ethereum/core/src/test-support/java/org/hyperledger/besu/ethereum/core/ExecutionContextTestFixture.java +++ b/ethereum/core/src/test-support/java/org/hyperledger/besu/ethereum/core/ExecutionContextTestFixture.java @@ -17,7 +17,7 @@ import static org.hyperledger.besu.ethereum.core.InMemoryKeyValueStorageProvider.createBonsaiInMemoryWorldStateArchive; import static org.hyperledger.besu.ethereum.core.InMemoryKeyValueStorageProvider.createInMemoryWorldStateArchive; -import org.hyperledger.besu.config.GenesisConfigFile; +import org.hyperledger.besu.config.GenesisConfig; import org.hyperledger.besu.ethereum.ProtocolContext; import org.hyperledger.besu.ethereum.chain.BadBlockManager; import org.hyperledger.besu.ethereum.chain.DefaultBlockchain; @@ -52,12 +52,12 @@ public class ExecutionContextTestFixture { private final ProtocolContext protocolContext; private ExecutionContextTestFixture( - final GenesisConfigFile genesisConfigFile, + final GenesisConfig genesisConfig, final ProtocolSchedule protocolSchedule, final KeyValueStorage blockchainKeyValueStorage, final KeyValueStorage variablesKeyValueStorage, final Optional dataStorageFormat) { - final GenesisState genesisState = GenesisState.fromConfig(genesisConfigFile, protocolSchedule); + final GenesisState genesisState = GenesisState.fromConfig(genesisConfig, protocolSchedule); this.genesis = genesisState.getBlock(); this.blockchainKeyValueStorage = blockchainKeyValueStorage; this.variablesKeyValueStorage = variablesKeyValueStorage; @@ -82,11 +82,11 @@ private ExecutionContextTestFixture( } public static ExecutionContextTestFixture create() { - return new Builder(GenesisConfigFile.mainnet()).build(); + return new Builder(GenesisConfig.mainnet()).build(); } - public static Builder builder(final GenesisConfigFile genesisConfigFile) { - return new Builder(genesisConfigFile); + public static Builder builder(final GenesisConfig genesisConfig) { + return new Builder(genesisConfig); } public Block getGenesis() { @@ -118,14 +118,14 @@ public ProtocolContext getProtocolContext() { } public static class Builder { - private final GenesisConfigFile genesisConfigFile; + private final GenesisConfig genesisConfig; private KeyValueStorage variablesKeyValueStorage; private KeyValueStorage blockchainKeyValueStorage; private ProtocolSchedule protocolSchedule; private Optional dataStorageFormat = Optional.empty(); - public Builder(final GenesisConfigFile genesisConfigFile) { - this.genesisConfigFile = genesisConfigFile; + public Builder(final GenesisConfig genesisConfig) { + this.genesisConfig = genesisConfig; } public Builder variablesKeyValueStorage(final KeyValueStorage keyValueStorage) { @@ -152,7 +152,7 @@ public ExecutionContextTestFixture build() { if (protocolSchedule == null) { protocolSchedule = new ProtocolScheduleBuilder( - genesisConfigFile.getConfigOptions(), + genesisConfig.getConfigOptions(), Optional.of(BigInteger.valueOf(42)), ProtocolSpecAdapters.create(0, Function.identity()), new PrivacyParameters(), @@ -172,7 +172,7 @@ public ExecutionContextTestFixture build() { } return new ExecutionContextTestFixture( - genesisConfigFile, + genesisConfig, protocolSchedule, variablesKeyValueStorage, blockchainKeyValueStorage, diff --git a/ethereum/core/src/test-support/java/org/hyperledger/besu/ethereum/core/ProtocolScheduleFixture.java b/ethereum/core/src/test-support/java/org/hyperledger/besu/ethereum/core/ProtocolScheduleFixture.java index db1114e832b..fc5ca291233 100644 --- a/ethereum/core/src/test-support/java/org/hyperledger/besu/ethereum/core/ProtocolScheduleFixture.java +++ b/ethereum/core/src/test-support/java/org/hyperledger/besu/ethereum/core/ProtocolScheduleFixture.java @@ -16,7 +16,7 @@ import static org.hyperledger.besu.config.JsonUtil.normalizeKeys; -import org.hyperledger.besu.config.GenesisConfigFile; +import org.hyperledger.besu.config.GenesisConfig; import org.hyperledger.besu.config.GenesisConfigOptions; import org.hyperledger.besu.config.JsonGenesisConfigOptions; import org.hyperledger.besu.ethereum.chain.BadBlockManager; @@ -47,7 +47,7 @@ public class ProtocolScheduleFixture { private static GenesisConfigOptions getMainnetConfigOptions() { // this method avoids reading all the alloc accounts when all we want is the "config" section try (final JsonParser jsonParser = - new JsonFactory().createParser(GenesisConfigFile.class.getResource("/mainnet.json"))) { + new JsonFactory().createParser(GenesisConfig.class.getResource("/mainnet.json"))) { while (jsonParser.nextToken() != JsonToken.END_OBJECT) { if ("config".equals(jsonParser.getCurrentName())) { diff --git a/ethereum/core/src/test/java/org/hyperledger/besu/ethereum/difficulty/fixed/FixedProtocolScheduleTest.java b/ethereum/core/src/test/java/org/hyperledger/besu/ethereum/difficulty/fixed/FixedProtocolScheduleTest.java index 9a6ddeaeb73..6d8d7350a25 100644 --- a/ethereum/core/src/test/java/org/hyperledger/besu/ethereum/difficulty/fixed/FixedProtocolScheduleTest.java +++ b/ethereum/core/src/test/java/org/hyperledger/besu/ethereum/difficulty/fixed/FixedProtocolScheduleTest.java @@ -16,7 +16,7 @@ import static org.assertj.core.api.Assertions.assertThat; -import org.hyperledger.besu.config.GenesisConfigFile; +import org.hyperledger.besu.config.GenesisConfig; import org.hyperledger.besu.ethereum.chain.BadBlockManager; import org.hyperledger.besu.ethereum.core.BlockHeader; import org.hyperledger.besu.ethereum.core.BlockHeaderTestFixture; @@ -34,7 +34,7 @@ public void reportedDifficultyForAllBlocksIsAFixedValue() { final ProtocolSchedule schedule = FixedDifficultyProtocolSchedule.create( - GenesisConfigFile.fromResource("/dev.json").getConfigOptions(), + GenesisConfig.fromResource("/dev.json").getConfigOptions(), EvmConfiguration.DEFAULT, MiningConfiguration.MINING_DISABLED, new BadBlockManager(), diff --git a/ethereum/core/src/test/java/org/hyperledger/besu/ethereum/mainnet/AbstractBlockProcessorIntegrationTest.java b/ethereum/core/src/test/java/org/hyperledger/besu/ethereum/mainnet/AbstractBlockProcessorIntegrationTest.java index c9e43327d96..0d05376183d 100644 --- a/ethereum/core/src/test/java/org/hyperledger/besu/ethereum/mainnet/AbstractBlockProcessorIntegrationTest.java +++ b/ethereum/core/src/test/java/org/hyperledger/besu/ethereum/mainnet/AbstractBlockProcessorIntegrationTest.java @@ -17,7 +17,7 @@ import static org.assertj.core.api.Assertions.assertThat; import static org.junit.jupiter.api.Assertions.assertTrue; -import org.hyperledger.besu.config.GenesisConfigFile; +import org.hyperledger.besu.config.GenesisConfig; import org.hyperledger.besu.crypto.KeyPair; import org.hyperledger.besu.crypto.SECPPrivateKey; import org.hyperledger.besu.crypto.SignatureAlgorithm; @@ -87,7 +87,7 @@ class AbstractBlockProcessorIntegrationTest { public void setUp() { final ExecutionContextTestFixture contextTestFixture = ExecutionContextTestFixture.builder( - GenesisConfigFile.fromResource( + GenesisConfig.fromResource( "/org/hyperledger/besu/ethereum/mainnet/genesis-bp-it.json")) .dataStorageFormat(DataStorageFormat.BONSAI) .build(); @@ -100,7 +100,7 @@ public void setUp() { private static Stream blockProcessorProvider() { final ExecutionContextTestFixture contextTestFixture = ExecutionContextTestFixture.builder( - GenesisConfigFile.fromResource( + GenesisConfig.fromResource( "/org/hyperledger/besu/ethereum/mainnet/genesis-bp-it.json")) .dataStorageFormat(DataStorageFormat.BONSAI) .build(); diff --git a/ethereum/core/src/test/java/org/hyperledger/besu/ethereum/mainnet/MainnetProtocolScheduleTest.java b/ethereum/core/src/test/java/org/hyperledger/besu/ethereum/mainnet/MainnetProtocolScheduleTest.java index 9ce20cb6267..bec03463336 100644 --- a/ethereum/core/src/test/java/org/hyperledger/besu/ethereum/mainnet/MainnetProtocolScheduleTest.java +++ b/ethereum/core/src/test/java/org/hyperledger/besu/ethereum/mainnet/MainnetProtocolScheduleTest.java @@ -14,7 +14,7 @@ */ package org.hyperledger.besu.ethereum.mainnet; -import org.hyperledger.besu.config.GenesisConfigFile; +import org.hyperledger.besu.config.GenesisConfig; import org.hyperledger.besu.ethereum.chain.BadBlockManager; import org.hyperledger.besu.ethereum.core.BlockHeader; import org.hyperledger.besu.ethereum.core.BlockHeaderTestFixture; @@ -71,7 +71,7 @@ public void shouldReturnDefaultProtocolSpecsWhenCustomNumbersAreNotUsed() { public void shouldOnlyUseFrontierWhenEmptyJsonConfigIsUsed() { final ProtocolSchedule sched = MainnetProtocolSchedule.fromConfig( - GenesisConfigFile.fromConfig("{}").getConfigOptions(), + GenesisConfig.fromConfig("{}").getConfigOptions(), EvmConfiguration.DEFAULT, MiningConfiguration.MINING_DISABLED, new BadBlockManager(), @@ -88,7 +88,7 @@ public void createFromConfigWithSettings() { "{\"config\": {\"homesteadBlock\": 2, \"daoForkBlock\": 3, \"eip150Block\": 14, \"eip158Block\": 15, \"byzantiumBlock\": 16, \"constantinopleBlock\": 18, \"petersburgBlock\": 19, \"chainId\":1234}}"; final ProtocolSchedule sched = MainnetProtocolSchedule.fromConfig( - GenesisConfigFile.fromConfig(json).getConfigOptions(), + GenesisConfig.fromConfig(json).getConfigOptions(), EvmConfiguration.DEFAULT, MiningConfiguration.MINING_DISABLED, new BadBlockManager(), @@ -122,7 +122,7 @@ public void outOfOrderConstantinoplesFail() { .isThrownBy( () -> MainnetProtocolSchedule.fromConfig( - GenesisConfigFile.fromConfig(json).getConfigOptions(), + GenesisConfig.fromConfig(json).getConfigOptions(), EvmConfiguration.DEFAULT, MiningConfiguration.MINING_DISABLED, new BadBlockManager(), diff --git a/ethereum/core/src/test/java/org/hyperledger/besu/ethereum/trie/diffbased/bonsai/AbstractIsolationTests.java b/ethereum/core/src/test/java/org/hyperledger/besu/ethereum/trie/diffbased/bonsai/AbstractIsolationTests.java index 275adc9ff43..de0aa4a8cb8 100644 --- a/ethereum/core/src/test/java/org/hyperledger/besu/ethereum/trie/diffbased/bonsai/AbstractIsolationTests.java +++ b/ethereum/core/src/test/java/org/hyperledger/besu/ethereum/trie/diffbased/bonsai/AbstractIsolationTests.java @@ -22,7 +22,7 @@ import static org.mockito.Mockito.when; import org.hyperledger.besu.config.GenesisAccount; -import org.hyperledger.besu.config.GenesisConfigFile; +import org.hyperledger.besu.config.GenesisConfig; import org.hyperledger.besu.crypto.KeyPair; import org.hyperledger.besu.crypto.SECPPrivateKey; import org.hyperledger.besu.crypto.SignatureAlgorithmFactory; @@ -105,13 +105,13 @@ public abstract class AbstractIsolationTests { .createKeyPair(SECPPrivateKey.create(key, "ECDSA")); protected final ProtocolSchedule protocolSchedule = MainnetProtocolSchedule.fromConfig( - GenesisConfigFile.fromResource("/dev.json").getConfigOptions(), + GenesisConfig.fromResource("/dev.json").getConfigOptions(), MiningConfiguration.MINING_DISABLED, new BadBlockManager(), false, new NoOpMetricsSystem()); protected final GenesisState genesisState = - GenesisState.fromConfig(GenesisConfigFile.fromResource("/dev.json"), protocolSchedule); + GenesisState.fromConfig(GenesisConfig.fromResource("/dev.json"), protocolSchedule); protected final MutableBlockchain blockchain = createInMemoryBlockchain(genesisState.getBlock()); protected final TransactionPoolConfiguration poolConfiguration = @@ -144,7 +144,7 @@ public abstract class AbstractIsolationTests { ethScheduler); protected final List accounts = - GenesisConfigFile.fromResource("/dev.json") + GenesisConfig.fromResource("/dev.json") .streamAllocations() .filter(ga -> ga.privateKey() != null) .toList(); diff --git a/ethereum/eth/src/test/java/org/hyperledger/besu/ethereum/eth/manager/EthProtocolManagerTestBuilder.java b/ethereum/eth/src/test/java/org/hyperledger/besu/ethereum/eth/manager/EthProtocolManagerTestBuilder.java index 90c69925818..3bd629db1e6 100644 --- a/ethereum/eth/src/test/java/org/hyperledger/besu/ethereum/eth/manager/EthProtocolManagerTestBuilder.java +++ b/ethereum/eth/src/test/java/org/hyperledger/besu/ethereum/eth/manager/EthProtocolManagerTestBuilder.java @@ -17,7 +17,7 @@ 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.config.GenesisConfig; import org.hyperledger.besu.ethereum.chain.Blockchain; import org.hyperledger.besu.ethereum.chain.GenesisState; import org.hyperledger.besu.ethereum.core.BlockchainSetupUtil; @@ -48,7 +48,7 @@ public class EthProtocolManagerTestBuilder { private static final ProtocolSchedule DEFAULT_PROTOCOL_SCHEDULE = ProtocolScheduleFixture.MAINNET; private ProtocolSchedule protocolSchedule; - private GenesisConfigFile genesisConfigFile; + private GenesisConfig genesisConfig; private GenesisState genesisState; private Blockchain blockchain; private BigInteger networkId; @@ -76,9 +76,8 @@ public EthProtocolManagerTestBuilder setProtocolSchedule( return this; } - public EthProtocolManagerTestBuilder setGenesisConfigFile( - final GenesisConfigFile genesisConfigFile) { - this.genesisConfigFile = genesisConfigFile; + public EthProtocolManagerTestBuilder setGenesisConfigFile(final GenesisConfig genesisConfig) { + this.genesisConfig = genesisConfig; return this; } @@ -171,11 +170,11 @@ public EthProtocolManager build() { if (protocolSchedule == null) { protocolSchedule = DEFAULT_PROTOCOL_SCHEDULE; } - if (genesisConfigFile == null) { - genesisConfigFile = GenesisConfigFile.mainnet(); + if (genesisConfig == null) { + genesisConfig = GenesisConfig.mainnet(); } if (genesisState == null) { - genesisState = GenesisState.fromConfig(genesisConfigFile, protocolSchedule); + genesisState = GenesisState.fromConfig(genesisConfig, protocolSchedule); } if (blockchain == null) { blockchain = createInMemoryBlockchain(genesisState.getBlock()); diff --git a/ethereum/eth/src/test/java/org/hyperledger/besu/ethereum/eth/messages/BlockBodiesMessageTest.java b/ethereum/eth/src/test/java/org/hyperledger/besu/ethereum/eth/messages/BlockBodiesMessageTest.java index 2bb1394a1d3..536f74aba68 100644 --- a/ethereum/eth/src/test/java/org/hyperledger/besu/ethereum/eth/messages/BlockBodiesMessageTest.java +++ b/ethereum/eth/src/test/java/org/hyperledger/besu/ethereum/eth/messages/BlockBodiesMessageTest.java @@ -16,7 +16,7 @@ import static org.junit.jupiter.api.Assertions.assertThrows; -import org.hyperledger.besu.config.GenesisConfigFile; +import org.hyperledger.besu.config.GenesisConfig; import org.hyperledger.besu.ethereum.chain.BadBlockManager; import org.hyperledger.besu.ethereum.core.BlockBody; import org.hyperledger.besu.ethereum.core.BlockHeader; @@ -57,7 +57,7 @@ public final class BlockBodiesMessageTest { public void setup() { protocolSchedule = FixedDifficultyProtocolSchedule.create( - GenesisConfigFile.fromResource("/dev.json").getConfigOptions(), + GenesisConfig.fromResource("/dev.json").getConfigOptions(), false, EvmConfiguration.DEFAULT, MiningConfiguration.MINING_DISABLED, diff --git a/ethereum/eth/src/test/java/org/hyperledger/besu/ethereum/eth/messages/BlockHeadersMessageTest.java b/ethereum/eth/src/test/java/org/hyperledger/besu/ethereum/eth/messages/BlockHeadersMessageTest.java index 9173a7af48b..ab42e404431 100644 --- a/ethereum/eth/src/test/java/org/hyperledger/besu/ethereum/eth/messages/BlockHeadersMessageTest.java +++ b/ethereum/eth/src/test/java/org/hyperledger/besu/ethereum/eth/messages/BlockHeadersMessageTest.java @@ -14,7 +14,7 @@ */ package org.hyperledger.besu.ethereum.eth.messages; -import org.hyperledger.besu.config.GenesisConfigFile; +import org.hyperledger.besu.config.GenesisConfig; import org.hyperledger.besu.ethereum.chain.BadBlockManager; import org.hyperledger.besu.ethereum.core.BlockHeader; import org.hyperledger.besu.ethereum.core.MiningConfiguration; @@ -64,7 +64,7 @@ public void blockHeadersRoundTrip() throws IOException { final List readHeaders = message.getHeaders( FixedDifficultyProtocolSchedule.create( - GenesisConfigFile.fromResource("/dev.json").getConfigOptions(), + GenesisConfig.fromResource("/dev.json").getConfigOptions(), false, EvmConfiguration.DEFAULT, MiningConfiguration.MINING_DISABLED, diff --git a/ethereum/eth/src/test/java/org/hyperledger/besu/ethereum/eth/sync/ChainHeadTrackerTest.java b/ethereum/eth/src/test/java/org/hyperledger/besu/ethereum/eth/sync/ChainHeadTrackerTest.java index dfad68a65ee..aa47fd09a34 100644 --- a/ethereum/eth/src/test/java/org/hyperledger/besu/ethereum/eth/sync/ChainHeadTrackerTest.java +++ b/ethereum/eth/src/test/java/org/hyperledger/besu/ethereum/eth/sync/ChainHeadTrackerTest.java @@ -16,7 +16,7 @@ import static org.assertj.core.api.Assertions.assertThat; -import org.hyperledger.besu.config.GenesisConfigFile; +import org.hyperledger.besu.config.GenesisConfig; import org.hyperledger.besu.datatypes.Hash; import org.hyperledger.besu.ethereum.chain.BadBlockManager; import org.hyperledger.besu.ethereum.chain.MutableBlockchain; @@ -63,7 +63,7 @@ public class ChainHeadTrackerTest { private final ProtocolSchedule protocolSchedule = FixedDifficultyProtocolSchedule.create( - GenesisConfigFile.fromResource("/dev.json").getConfigOptions(), + GenesisConfig.fromResource("/dev.json").getConfigOptions(), false, EvmConfiguration.DEFAULT, MiningConfiguration.MINING_DISABLED, diff --git a/ethereum/eth/src/test/java/org/hyperledger/besu/ethereum/eth/transactions/AbstractTransactionPoolTestBase.java b/ethereum/eth/src/test/java/org/hyperledger/besu/ethereum/eth/transactions/AbstractTransactionPoolTestBase.java index 7046270cd59..f69232eec4e 100644 --- a/ethereum/eth/src/test/java/org/hyperledger/besu/ethereum/eth/transactions/AbstractTransactionPoolTestBase.java +++ b/ethereum/eth/src/test/java/org/hyperledger/besu/ethereum/eth/transactions/AbstractTransactionPoolTestBase.java @@ -32,7 +32,7 @@ import static org.mockito.Mockito.when; import static org.mockito.quality.Strictness.LENIENT; -import org.hyperledger.besu.config.GenesisConfigFile; +import org.hyperledger.besu.config.GenesisConfig; import org.hyperledger.besu.crypto.KeyPair; import org.hyperledger.besu.crypto.SignatureAlgorithmFactory; import org.hyperledger.besu.datatypes.BlobsWithCommitments; @@ -174,7 +174,7 @@ protected TransactionTestFixture createBaseTransactionBaseFeeMarket(final int no protected abstract ExecutionContextTestFixture createExecutionContextTestFixture(); protected static ExecutionContextTestFixture createExecutionContextTestFixtureBaseFeeMarket() { - final var genesisConfigFile = GenesisConfigFile.fromResource("/txpool-test-genesis.json"); + final var genesisConfigFile = GenesisConfig.fromResource("/txpool-test-genesis.json"); final ProtocolSchedule protocolSchedule = new ProtocolScheduleBuilder( genesisConfigFile.getConfigOptions(), diff --git a/ethereum/eth/src/test/java/org/hyperledger/besu/ethereum/eth/transactions/TestNode.java b/ethereum/eth/src/test/java/org/hyperledger/besu/ethereum/eth/transactions/TestNode.java index 4d47b909946..e29b8285c9c 100644 --- a/ethereum/eth/src/test/java/org/hyperledger/besu/ethereum/eth/transactions/TestNode.java +++ b/ethereum/eth/src/test/java/org/hyperledger/besu/ethereum/eth/transactions/TestNode.java @@ -23,7 +23,7 @@ import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; -import org.hyperledger.besu.config.GenesisConfigFile; +import org.hyperledger.besu.config.GenesisConfig; import org.hyperledger.besu.crypto.KeyPair; import org.hyperledger.besu.cryptoservices.NodeKey; import org.hyperledger.besu.cryptoservices.NodeKeyUtils; @@ -117,10 +117,10 @@ public TestNode( .setBindPort(listenPort) .setSupportedProtocols(EthProtocol.get())); - final GenesisConfigFile genesisConfigFile = GenesisConfigFile.fromResource("/dev.json"); + final GenesisConfig genesisConfig = GenesisConfig.fromResource("/dev.json"); final ProtocolSchedule protocolSchedule = FixedDifficultyProtocolSchedule.create( - GenesisConfigFile.fromResource("/dev.json").getConfigOptions(), + GenesisConfig.fromResource("/dev.json").getConfigOptions(), false, EvmConfiguration.DEFAULT, MiningConfiguration.MINING_DISABLED, @@ -128,7 +128,7 @@ public TestNode( false, new NoOpMetricsSystem()); - final GenesisState genesisState = GenesisState.fromConfig(genesisConfigFile, protocolSchedule); + final GenesisState genesisState = GenesisState.fromConfig(genesisConfig, protocolSchedule); final BlockHeaderFunctions blockHeaderFunctions = ScheduleBasedBlockHeaderFunctions.create(protocolSchedule); final MutableBlockchain blockchain = diff --git a/ethereum/evmtool/src/main/java/org/hyperledger/besu/evmtool/EvmToolCommand.java b/ethereum/evmtool/src/main/java/org/hyperledger/besu/evmtool/EvmToolCommand.java index 2574d4b8e39..7af78fa02e2 100644 --- a/ethereum/evmtool/src/main/java/org/hyperledger/besu/evmtool/EvmToolCommand.java +++ b/ethereum/evmtool/src/main/java/org/hyperledger/besu/evmtool/EvmToolCommand.java @@ -464,9 +464,9 @@ public void run() { .coinbase(coinbase) .difficulty( Difficulty.fromHexString( - genesisFileModule.providesGenesisConfigFile().getDifficulty())) + genesisFileModule.providesGenesisConfig().getDifficulty())) .number(0) - .gasLimit(genesisFileModule.providesGenesisConfigFile().getGasLimit()) + .gasLimit(genesisFileModule.providesGenesisConfig().getGasLimit()) .timestamp(0) .ommersHash(Hash.EMPTY_LIST_HASH) .stateRoot(Hash.EMPTY_TRIE_HASH) @@ -483,7 +483,7 @@ public void run() { .getBlockchain() .getChainHeadHeader() .getBaseFee() - .or(() -> genesisFileModule.providesGenesisConfigFile().getBaseFeePerGas()) + .or(() -> genesisFileModule.providesGenesisConfig().getBaseFeePerGas()) .orElse( protocolSpec.getFeeMarket().implementsBaseFee() ? Wei.of(0xa) : null)) .buildBlockHeader(); diff --git a/ethereum/evmtool/src/main/java/org/hyperledger/besu/evmtool/GenesisFileModule.java b/ethereum/evmtool/src/main/java/org/hyperledger/besu/evmtool/GenesisFileModule.java index 8512b5537e0..7af024bf18b 100644 --- a/ethereum/evmtool/src/main/java/org/hyperledger/besu/evmtool/GenesisFileModule.java +++ b/ethereum/evmtool/src/main/java/org/hyperledger/besu/evmtool/GenesisFileModule.java @@ -16,7 +16,7 @@ import org.hyperledger.besu.cli.config.EthNetworkConfig; import org.hyperledger.besu.cli.config.NetworkName; -import org.hyperledger.besu.config.GenesisConfigFile; +import org.hyperledger.besu.config.GenesisConfig; import org.hyperledger.besu.config.GenesisConfigOptions; import org.hyperledger.besu.datatypes.HardforkId.MainnetHardforkId; import org.hyperledger.besu.ethereum.chain.GenesisState; @@ -64,14 +64,14 @@ protected GenesisFileModule(final String genesisConfig) { @Singleton @Provides - GenesisConfigFile providesGenesisConfigFile() { - return GenesisConfigFile.fromConfig(genesisConfig); + GenesisConfig providesGenesisConfig() { + return GenesisConfig.fromConfig(genesisConfig); } @Singleton @Provides - GenesisConfigOptions provideGenesisConfigOptions(final GenesisConfigFile genesisConfigFile) { - return genesisConfigFile.getConfigOptions(); + GenesisConfigOptions provideGenesisConfigOptions(final GenesisConfig genesisConfig) { + return genesisConfig.getConfigOptions(); } @Singleton @@ -88,8 +88,8 @@ ProtocolSchedule provideProtocolSchedule( @Singleton @Provides GenesisState provideGenesisState( - final GenesisConfigFile genesisConfigFile, final ProtocolSchedule protocolSchedule) { - return GenesisState.fromConfig(genesisConfigFile, protocolSchedule); + final GenesisConfig genesisConfig, final ProtocolSchedule protocolSchedule) { + return GenesisState.fromConfig(genesisConfig, protocolSchedule); } @Singleton diff --git a/ethereum/permissioning/src/test/java/org/hyperledger/besu/ethereum/permissioning/NodeSmartContractPermissioningControllerTest.java b/ethereum/permissioning/src/test/java/org/hyperledger/besu/ethereum/permissioning/NodeSmartContractPermissioningControllerTest.java index fa0608a031c..487874d8e3d 100644 --- a/ethereum/permissioning/src/test/java/org/hyperledger/besu/ethereum/permissioning/NodeSmartContractPermissioningControllerTest.java +++ b/ethereum/permissioning/src/test/java/org/hyperledger/besu/ethereum/permissioning/NodeSmartContractPermissioningControllerTest.java @@ -23,7 +23,7 @@ import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; -import org.hyperledger.besu.config.GenesisConfigFile; +import org.hyperledger.besu.config.GenesisConfig; import org.hyperledger.besu.config.JsonUtil; import org.hyperledger.besu.datatypes.Address; import org.hyperledger.besu.ethereum.chain.GenesisState; @@ -63,7 +63,7 @@ private NodeSmartContractPermissioningController setupController( final ObjectNode jsonData = JsonUtil.objectNodeFromString(emptyContractFile, true); final GenesisState genesisState = - GenesisState.fromConfig(GenesisConfigFile.fromConfig(jsonData), protocolSchedule); + GenesisState.fromConfig(GenesisConfig.fromConfig(jsonData), protocolSchedule); final MutableBlockchain blockchain = createInMemoryBlockchain(genesisState.getBlock()); final WorldStateArchive worldArchive = createInMemoryWorldStateArchive(); diff --git a/ethereum/permissioning/src/test/java/org/hyperledger/besu/ethereum/permissioning/TransactionSmartContractPermissioningControllerTest.java b/ethereum/permissioning/src/test/java/org/hyperledger/besu/ethereum/permissioning/TransactionSmartContractPermissioningControllerTest.java index d9746cfcf5f..daea4a6d210 100644 --- a/ethereum/permissioning/src/test/java/org/hyperledger/besu/ethereum/permissioning/TransactionSmartContractPermissioningControllerTest.java +++ b/ethereum/permissioning/src/test/java/org/hyperledger/besu/ethereum/permissioning/TransactionSmartContractPermissioningControllerTest.java @@ -22,7 +22,7 @@ import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; -import org.hyperledger.besu.config.GenesisConfigFile; +import org.hyperledger.besu.config.GenesisConfig; import org.hyperledger.besu.crypto.SignatureAlgorithmFactory; import org.hyperledger.besu.datatypes.Address; import org.hyperledger.besu.datatypes.TransactionType; @@ -61,8 +61,7 @@ private TransactionSmartContractPermissioningController setupController( final GenesisState genesisState = GenesisState.fromConfig( - GenesisConfigFile.fromSource(this.getClass().getResource(resourceName)), - protocolSchedule); + GenesisConfig.fromSource(this.getClass().getResource(resourceName)), protocolSchedule); final MutableBlockchain blockchain = createInMemoryBlockchain(genesisState.getBlock()); final WorldStateArchive worldArchive = createInMemoryWorldStateArchive(); diff --git a/ethereum/referencetests/src/reference-test/java/org/hyperledger/besu/ethereum/mainnet/DifficultyCalculatorTests.java b/ethereum/referencetests/src/reference-test/java/org/hyperledger/besu/ethereum/mainnet/DifficultyCalculatorTests.java index ea09a1eb983..a5e3d364fc2 100644 --- a/ethereum/referencetests/src/reference-test/java/org/hyperledger/besu/ethereum/mainnet/DifficultyCalculatorTests.java +++ b/ethereum/referencetests/src/reference-test/java/org/hyperledger/besu/ethereum/mainnet/DifficultyCalculatorTests.java @@ -18,7 +18,7 @@ import static org.assertj.core.api.Assertions.assertThat; -import org.hyperledger.besu.config.GenesisConfigFile; +import org.hyperledger.besu.config.GenesisConfig; import org.hyperledger.besu.config.JsonUtil; import org.hyperledger.besu.config.StubGenesisConfigOptions; import org.hyperledger.besu.datatypes.Address; @@ -57,7 +57,7 @@ public static Stream getTestParametersForConfig() throws IOException Arguments.of( "/BasicTests/difficultyMainNetwork.json", MainnetProtocolSchedule.fromConfig( - GenesisConfigFile.mainnet() + GenesisConfig.mainnet() .withOverrides(postMergeOverrides).getConfigOptions(), EvmConfiguration.DEFAULT, MiningConfiguration.MINING_DISABLED, new BadBlockManager(), false, new NoOpMetricsSystem())), Arguments.of( From 320c4764cee3d7a089ea3d7d7f271b8f8c67634f Mon Sep 17 00:00:00 2001 From: Matilda-Clerke Date: Thu, 19 Dec 2024 10:39:59 +1100 Subject: [PATCH 4/6] Replace waitforpeertask with ethpeers method (#8009) * 7582: Add waitForPeer method to PeerSelector and EthPeers Signed-off-by: Matilda Clerke * 7582: Replace all usages of WaitForPeer[s]Task with new EthPeers.waitForPeer method Signed-off-by: Matilda Clerke * 7582: Fix PivotBlockConfirmerTest Signed-off-by: Matilda Clerke * 7582: spotless Signed-off-by: Matilda Clerke * 7582: Fix broken PivotBlockRetrieverTest Signed-off-by: Matilda Clerke * 7582: Fix broken FastSyncActionsTest Signed-off-by: Matilda Clerke * 7582: spotless Signed-off-by: Matilda Clerke * 7582: Fix issues after merge Signed-off-by: Matilda Clerke * 7582: Put AbstractSyncTargetManager.waitForPeerAndThenSetSyncTarget code back separate thread to avoid infinite loop waiting for peers during acceptance tests Signed-off-by: Matilda Clerke * 7582: Remove pivot block checks when waiting for peer in FastSyncActions Signed-off-by: Matilda Clerke * 7582: Remove estimated chain height check from PivotBlockConfirmer when waiting for peers Signed-off-by: Matilda Clerke * 7582: Fix broken PivotBlockRetrieverTest Signed-off-by: Matilda Clerke * Use isSuitablePeer as peer selection criteria when waiting for a peer in AbstractRetryingPeerTask Signed-off-by: Matilda Clerke * Remove MetricsSystem from PivotSelectorFromPeers Signed-off-by: Matilda Clerke --------- Signed-off-by: Matilda Clerke --- .../controller/BesuControllerBuilder.java | 3 +- .../qbft/BFTPivotSelectorFromPeers.java | 5 +- .../qbft/sync/QbftPivotSelectorTest.java | 34 +---- .../besu/ethereum/eth/manager/EthPeers.java | 34 +++++ .../eth/manager/peertask/PeerSelector.java | 9 ++ .../task/AbstractRetryingPeerTask.java | 8 +- .../eth/manager/task/WaitForPeerTask.java | 64 --------- .../eth/manager/task/WaitForPeersTask.java | 83 ------------ .../eth/sync/AbstractSyncTargetManager.java | 14 +- .../backwardsync/BackwardSyncAlgorithm.java | 14 +- .../eth/sync/fastsync/FastSyncActions.java | 14 +- .../sync/fastsync/PivotBlockConfirmer.java | 16 ++- .../sync/fastsync/PivotSelectorFromPeers.java | 21 +-- .../fastsync/PivotSelectorFromSafeBlock.java | 12 +- .../eth/manager/task/WaitForPeerTaskTest.java | 87 ------------- .../manager/task/WaitForPeersTaskTest.java | 105 --------------- .../sync/fastsync/FastSyncActionsTest.java | 123 ++++-------------- .../fastsync/PivotBlockRetrieverTest.java | 12 +- 18 files changed, 120 insertions(+), 538 deletions(-) delete mode 100644 ethereum/eth/src/main/java/org/hyperledger/besu/ethereum/eth/manager/task/WaitForPeerTask.java delete mode 100644 ethereum/eth/src/main/java/org/hyperledger/besu/ethereum/eth/manager/task/WaitForPeersTask.java delete mode 100644 ethereum/eth/src/test/java/org/hyperledger/besu/ethereum/eth/manager/task/WaitForPeerTaskTest.java delete mode 100644 ethereum/eth/src/test/java/org/hyperledger/besu/ethereum/eth/manager/task/WaitForPeersTaskTest.java diff --git a/besu/src/main/java/org/hyperledger/besu/controller/BesuControllerBuilder.java b/besu/src/main/java/org/hyperledger/besu/controller/BesuControllerBuilder.java index 9498f7b2d92..d10ab04362c 100644 --- a/besu/src/main/java/org/hyperledger/besu/controller/BesuControllerBuilder.java +++ b/besu/src/main/java/org/hyperledger/besu/controller/BesuControllerBuilder.java @@ -923,7 +923,6 @@ private PivotBlockSelector createPivotSelector( ethContext, syncConfig, syncState, - metricsSystem, protocolContext, nodeKey, blockchain.getChainHeadHeader()); @@ -953,7 +952,7 @@ private PivotBlockSelector createPivotSelector( unsubscribeForkchoiceListener); } else { LOG.info("TTD difficulty is not present, creating initial sync phase for PoW"); - return new PivotSelectorFromPeers(ethContext, syncConfig, syncState, metricsSystem); + return new PivotSelectorFromPeers(ethContext, syncConfig, syncState); } } diff --git a/consensus/qbft/src/main/java/org/hyperledger/besu/consensus/qbft/BFTPivotSelectorFromPeers.java b/consensus/qbft/src/main/java/org/hyperledger/besu/consensus/qbft/BFTPivotSelectorFromPeers.java index 7437b349a2a..78ad1816635 100644 --- a/consensus/qbft/src/main/java/org/hyperledger/besu/consensus/qbft/BFTPivotSelectorFromPeers.java +++ b/consensus/qbft/src/main/java/org/hyperledger/besu/consensus/qbft/BFTPivotSelectorFromPeers.java @@ -26,7 +26,6 @@ import org.hyperledger.besu.ethereum.eth.sync.fastsync.NoSyncRequiredException; import org.hyperledger.besu.ethereum.eth.sync.fastsync.PivotSelectorFromPeers; import org.hyperledger.besu.ethereum.eth.sync.state.SyncState; -import org.hyperledger.besu.plugin.services.MetricsSystem; import java.util.Optional; import java.util.concurrent.atomic.AtomicBoolean; @@ -56,7 +55,6 @@ public class BFTPivotSelectorFromPeers extends PivotSelectorFromPeers { * @param ethContext the eth context * @param syncConfig the sync config * @param syncState the sync state - * @param metricsSystem the metrics * @param protocolContext the protocol context * @param nodeKey the node key * @param blockHeader the block header @@ -65,11 +63,10 @@ public BFTPivotSelectorFromPeers( final EthContext ethContext, final SynchronizerConfiguration syncConfig, final SyncState syncState, - final MetricsSystem metricsSystem, final ProtocolContext protocolContext, final NodeKey nodeKey, final BlockHeader blockHeader) { - super(ethContext, syncConfig, syncState, metricsSystem); + super(ethContext, syncConfig, syncState); this.protocolContext = protocolContext; this.blockHeader = blockHeader; this.nodeKey = nodeKey; diff --git a/consensus/qbft/src/test/java/org/hyperledger/besu/consensus/qbft/sync/QbftPivotSelectorTest.java b/consensus/qbft/src/test/java/org/hyperledger/besu/consensus/qbft/sync/QbftPivotSelectorTest.java index 2f3013ea714..76f41dc6506 100644 --- a/consensus/qbft/src/test/java/org/hyperledger/besu/consensus/qbft/sync/QbftPivotSelectorTest.java +++ b/consensus/qbft/src/test/java/org/hyperledger/besu/consensus/qbft/sync/QbftPivotSelectorTest.java @@ -33,7 +33,6 @@ import org.hyperledger.besu.ethereum.eth.sync.fastsync.FastSyncState; import org.hyperledger.besu.ethereum.eth.sync.fastsync.NoSyncRequiredException; import org.hyperledger.besu.ethereum.eth.sync.state.SyncState; -import org.hyperledger.besu.plugin.services.MetricsSystem; import java.util.ArrayList; import java.util.List; @@ -55,7 +54,6 @@ public class QbftPivotSelectorTest { @Mock private ProtocolContext protocolContext; @Mock private BftContext bftContext; @Mock private SyncState syncState; - @Mock private MetricsSystem metricsSystem; @Mock private EthContext ethContext; @Mock private EthPeers ethPeers; @Mock private ValidatorProvider validatorProvider; @@ -80,13 +78,7 @@ public void returnEmptySyncStateIfValidatorWithOtherValidatorsButNoPeers() { when(validatorProvider.getValidatorsAtHead()).thenReturn(validatorList); BFTPivotSelectorFromPeers pivotSelector = new BFTPivotSelectorFromPeers( - ethContext, - syncConfig, - syncState, - metricsSystem, - protocolContext, - nodeKey, - blockHeader); + ethContext, syncConfig, syncState, protocolContext, nodeKey, blockHeader); Optional pivotState = pivotSelector.selectNewPivotBlock(); assertThat(pivotState.isEmpty()).isTrue(); } @@ -104,13 +96,7 @@ public void returnNoSyncRequiredIfOnlyValidatorAndNoPeers() { when(validatorProvider.getValidatorsAtHead()).thenReturn(validatorList); BFTPivotSelectorFromPeers pivotSelector = new BFTPivotSelectorFromPeers( - ethContext, - syncConfig, - syncState, - metricsSystem, - protocolContext, - nodeKey, - blockHeader); + ethContext, syncConfig, syncState, protocolContext, nodeKey, blockHeader); try { Optional pivotState = pivotSelector.selectNewPivotBlock(); @@ -126,13 +112,7 @@ public void returnEmptySyncStateIfNonValidatorWithNoBestPeer() { when(validatorProvider.nodeIsValidator(any())).thenReturn(false); BFTPivotSelectorFromPeers pivotSelector = new BFTPivotSelectorFromPeers( - ethContext, - syncConfig, - syncState, - metricsSystem, - protocolContext, - nodeKey, - blockHeader); + ethContext, syncConfig, syncState, protocolContext, nodeKey, blockHeader); Optional pivotState = pivotSelector.selectNewPivotBlock(); assertThat(pivotState.isEmpty()).isTrue(); @@ -145,13 +125,7 @@ public void returnEmptySyncStateIfValidatorAndNotAtGenesisAndOtherValidators() { when(blockHeader.getNumber()).thenReturn(10L); BFTPivotSelectorFromPeers pivotSelector = new BFTPivotSelectorFromPeers( - ethContext, - syncConfig, - syncState, - metricsSystem, - protocolContext, - nodeKey, - blockHeader); + ethContext, syncConfig, syncState, protocolContext, nodeKey, blockHeader); Optional pivotState = pivotSelector.selectNewPivotBlock(); assertThat(pivotState.isEmpty()).isTrue(); diff --git a/ethereum/eth/src/main/java/org/hyperledger/besu/ethereum/eth/manager/EthPeers.java b/ethereum/eth/src/main/java/org/hyperledger/besu/ethereum/eth/manager/EthPeers.java index fda8bb0f167..c91ed9646d2 100644 --- a/ethereum/eth/src/main/java/org/hyperledger/besu/ethereum/eth/manager/EthPeers.java +++ b/ethereum/eth/src/main/java/org/hyperledger/besu/ethereum/eth/manager/EthPeers.java @@ -474,6 +474,40 @@ public Optional getPeer(final Predicate filter) { .min(LEAST_TO_MOST_BUSY); } + // Part of the PeerSelector interface, to be split apart later + @Override + public CompletableFuture waitForPeer(final Predicate filter) { + final CompletableFuture future = new CompletableFuture<>(); + LOG.debug("Waiting for peer matching filter. {} peers currently connected.", peerCount()); + // check for an existing peer matching the filter and use that if one is found + Optional maybePeer = getPeer(filter); + if (maybePeer.isPresent()) { + LOG.debug("Found peer matching filter already connected!"); + future.complete(maybePeer.get()); + } else { + // no existing peer matches our filter. Subscribe to new connections until we find one + LOG.debug("Subscribing to new peer connections to wait until one matches filter"); + final long subscriptionId = + subscribeConnect( + (peer) -> { + if (!future.isDone() && filter.test(peer)) { + LOG.debug("Found new peer matching filter!"); + future.complete(peer); + } else { + LOG.debug("New peer does not match filter"); + } + }); + future.handle( + (peer, throwable) -> { + LOG.debug("Unsubscribing from new peer connections with ID {}", subscriptionId); + unsubscribeConnect(subscriptionId); + return null; + }); + } + + return future; + } + // Part of the PeerSelector interface, to be split apart later @Override public Optional getPeerByPeerId(final PeerId peerId) { diff --git a/ethereum/eth/src/main/java/org/hyperledger/besu/ethereum/eth/manager/peertask/PeerSelector.java b/ethereum/eth/src/main/java/org/hyperledger/besu/ethereum/eth/manager/peertask/PeerSelector.java index 8f7ab33e42d..73f01e71c74 100644 --- a/ethereum/eth/src/main/java/org/hyperledger/besu/ethereum/eth/manager/peertask/PeerSelector.java +++ b/ethereum/eth/src/main/java/org/hyperledger/besu/ethereum/eth/manager/peertask/PeerSelector.java @@ -18,6 +18,7 @@ import org.hyperledger.besu.ethereum.p2p.peers.PeerId; import java.util.Optional; +import java.util.concurrent.CompletableFuture; import java.util.function.Predicate; /** Selects the EthPeers for the PeerTaskExecutor */ @@ -31,6 +32,14 @@ public interface PeerSelector { */ Optional getPeer(final Predicate filter); + /** + * Waits for a peer matching the supplied filter + * + * @param filter a Predicate\ matching desirable peers + * @return a CompletableFuture into which a peer will be placed + */ + CompletableFuture waitForPeer(final Predicate filter); + /** * Attempts to get the EthPeer identified by peerId * diff --git a/ethereum/eth/src/main/java/org/hyperledger/besu/ethereum/eth/manager/task/AbstractRetryingPeerTask.java b/ethereum/eth/src/main/java/org/hyperledger/besu/ethereum/eth/manager/task/AbstractRetryingPeerTask.java index e7f1556b5a2..dd75a6eff98 100644 --- a/ethereum/eth/src/main/java/org/hyperledger/besu/ethereum/eth/manager/task/AbstractRetryingPeerTask.java +++ b/ethereum/eth/src/main/java/org/hyperledger/besu/ethereum/eth/manager/task/AbstractRetryingPeerTask.java @@ -26,6 +26,7 @@ import java.time.Duration; import java.util.Optional; import java.util.concurrent.CompletableFuture; +import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeoutException; import java.util.function.Predicate; @@ -129,13 +130,12 @@ protected void handleTaskError(final Throwable error) { "No useful peer found, wait max 5 seconds for new peer to connect: current peers {}", ethContext.getEthPeers().peerCount()); - final WaitForPeerTask waitTask = WaitForPeerTask.create(ethContext, metricsSystem); executeSubTask( () -> ethContext - .getScheduler() - // wait for a new peer for up to 5 seconds - .timeout(waitTask, Duration.ofSeconds(5)) + .getEthPeers() + .waitForPeer(this::isSuitablePeer) + .orTimeout(5, TimeUnit.SECONDS) // execute the task again .whenComplete((r, t) -> executeTaskTimed())); return; diff --git a/ethereum/eth/src/main/java/org/hyperledger/besu/ethereum/eth/manager/task/WaitForPeerTask.java b/ethereum/eth/src/main/java/org/hyperledger/besu/ethereum/eth/manager/task/WaitForPeerTask.java deleted file mode 100644 index 44ced57e7ba..00000000000 --- a/ethereum/eth/src/main/java/org/hyperledger/besu/ethereum/eth/manager/task/WaitForPeerTask.java +++ /dev/null @@ -1,64 +0,0 @@ -/* - * Copyright ConsenSys AG. - * - * 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.task; - -import org.hyperledger.besu.ethereum.eth.manager.EthContext; -import org.hyperledger.besu.ethereum.eth.manager.EthPeers; -import org.hyperledger.besu.plugin.services.MetricsSystem; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -/** Wait for a single new peer to connect. */ -public class WaitForPeerTask extends AbstractEthTask { - private static final Logger LOG = LoggerFactory.getLogger(WaitForPeerTask.class); - - private final EthContext ethContext; - private volatile Long peerListenerId; - - private WaitForPeerTask(final EthContext ethContext, final MetricsSystem metricsSystem) { - super(metricsSystem); - this.ethContext = ethContext; - } - - public static WaitForPeerTask create( - final EthContext ethContext, final MetricsSystem metricsSystem) { - return new WaitForPeerTask(ethContext, metricsSystem); - } - - @Override - protected void executeTask() { - final EthPeers ethPeers = ethContext.getEthPeers(); - LOG.debug( - "Waiting for new peer connection. {} peers currently connected.", ethPeers.peerCount()); - // Listen for peer connections and complete task when we hit our target - peerListenerId = - ethPeers.subscribeConnect( - (peer) -> { - LOG.debug("Finished waiting for peer connection."); - // We hit our target - result.complete(null); - }); - } - - @Override - protected void cleanup() { - super.cleanup(); - final Long listenerId = peerListenerId; - if (listenerId != null) { - ethContext.getEthPeers().unsubscribeConnect(listenerId); - } - } -} diff --git a/ethereum/eth/src/main/java/org/hyperledger/besu/ethereum/eth/manager/task/WaitForPeersTask.java b/ethereum/eth/src/main/java/org/hyperledger/besu/ethereum/eth/manager/task/WaitForPeersTask.java deleted file mode 100644 index b0d40770293..00000000000 --- a/ethereum/eth/src/main/java/org/hyperledger/besu/ethereum/eth/manager/task/WaitForPeersTask.java +++ /dev/null @@ -1,83 +0,0 @@ -/* - * Copyright ConsenSys AG. - * - * 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.task; - -import org.hyperledger.besu.ethereum.eth.manager.EthContext; -import org.hyperledger.besu.ethereum.eth.manager.EthPeers; -import org.hyperledger.besu.plugin.services.MetricsSystem; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -/** Waits for some number of peers to connect. */ -public class WaitForPeersTask extends AbstractEthTask { - private static final Logger LOG = LoggerFactory.getLogger(WaitForPeersTask.class); - - private final int targetPeerCount; - private final EthContext ethContext; - private volatile Long peerListenerId; - - private WaitForPeersTask( - final EthContext ethContext, final int targetPeerCount, final MetricsSystem metricsSystem) { - super(metricsSystem); - this.targetPeerCount = targetPeerCount; - this.ethContext = ethContext; - } - - public static WaitForPeersTask create( - final EthContext ethContext, final int targetPeerCount, final MetricsSystem metricsSystem) { - return new WaitForPeersTask(ethContext, targetPeerCount, metricsSystem); - } - - @Override - protected void executeTask() { - final EthPeers ethPeers = ethContext.getEthPeers(); - if (ethPeers.peerCount() >= targetPeerCount) { - LOG.debug("We already hit our target of at least {} peers connected", targetPeerCount); - result.complete(null); - return; - } - - LOG.info( - "Waiting for {} total peers to connect. {} peers currently connected.", - targetPeerCount, - ethPeers.peerCount()); - // Listen for peer connections and complete task when we hit our target - peerListenerId = - ethPeers.subscribeConnect( - (peer) -> { - final int peerCount = ethPeers.peerCount(); - if (peerCount >= targetPeerCount) { - LOG.debug("Complete: {} peers connected.", targetPeerCount); - // We hit our target - result.complete(null); - } else { - LOG.debug( - "Waiting for {} total peers to connect. {} peers currently connected.", - targetPeerCount, - peerCount); - } - }); - } - - @Override - protected void cleanup() { - super.cleanup(); - final Long listenerId = peerListenerId; - if (listenerId != null) { - ethContext.getEthPeers().unsubscribeConnect(peerListenerId); - } - } -} diff --git a/ethereum/eth/src/main/java/org/hyperledger/besu/ethereum/eth/sync/AbstractSyncTargetManager.java b/ethereum/eth/src/main/java/org/hyperledger/besu/ethereum/eth/sync/AbstractSyncTargetManager.java index a60892f1574..46d9aed20a4 100644 --- a/ethereum/eth/src/main/java/org/hyperledger/besu/ethereum/eth/sync/AbstractSyncTargetManager.java +++ b/ethereum/eth/src/main/java/org/hyperledger/besu/ethereum/eth/sync/AbstractSyncTargetManager.java @@ -19,7 +19,6 @@ import org.hyperledger.besu.ethereum.ProtocolContext; import org.hyperledger.besu.ethereum.eth.manager.EthContext; import org.hyperledger.besu.ethereum.eth.manager.EthPeer; -import org.hyperledger.besu.ethereum.eth.manager.task.WaitForPeerTask; import org.hyperledger.besu.ethereum.eth.sync.state.SyncTarget; import org.hyperledger.besu.ethereum.eth.sync.tasks.DetermineCommonAncestorTask; import org.hyperledger.besu.ethereum.mainnet.ProtocolSchedule; @@ -117,13 +116,16 @@ protected Optional finalizeSelectedSyncTarget(final SyncTarget syncT protected abstract CompletableFuture> selectBestAvailableSyncTarget(); private CompletableFuture waitForPeerAndThenSetSyncTarget() { - return waitForNewPeer().handle((r, t) -> r).thenCompose((r) -> findSyncTarget()); - } - - private CompletableFuture waitForNewPeer() { return ethContext .getScheduler() - .timeout(WaitForPeerTask.create(ethContext, metricsSystem), Duration.ofSeconds(5)); + .scheduleFutureTask( + () -> + ethContext + .getEthPeers() + .waitForPeer((peer) -> true) + .handle((ignored, ignored2) -> null) + .thenCompose((r) -> findSyncTarget()), + Duration.ofSeconds(5)); } private boolean isCancelled() { diff --git a/ethereum/eth/src/main/java/org/hyperledger/besu/ethereum/eth/sync/backwardsync/BackwardSyncAlgorithm.java b/ethereum/eth/src/main/java/org/hyperledger/besu/ethereum/eth/sync/backwardsync/BackwardSyncAlgorithm.java index 506b360730e..a7311ac469a 100644 --- a/ethereum/eth/src/main/java/org/hyperledger/besu/ethereum/eth/sync/backwardsync/BackwardSyncAlgorithm.java +++ b/ethereum/eth/src/main/java/org/hyperledger/besu/ethereum/eth/sync/backwardsync/BackwardSyncAlgorithm.java @@ -21,7 +21,6 @@ import org.hyperledger.besu.ethereum.core.Block; import org.hyperledger.besu.ethereum.core.BlockHeader; import org.hyperledger.besu.ethereum.eth.manager.exceptions.MaxRetriesReachedException; -import org.hyperledger.besu.ethereum.eth.manager.task.WaitForPeersTask; import org.hyperledger.besu.plugin.services.BesuEvents; import java.util.Optional; @@ -189,7 +188,12 @@ private void checkReadiness(final long idTTD, final long idIS) { final boolean await = latch.get().await(2, TimeUnit.MINUTES); if (await) { LOG.debug("Preconditions meet, ensure at least one peer is connected"); - waitForPeers(1).get(); + context + .getEthContext() + .getEthPeers() + .waitForPeer((peer) -> true) + .orTimeout(5, TimeUnit.SECONDS) + .get(); } } } catch (InterruptedException e) { @@ -211,12 +215,6 @@ private void countDownIfReady() { } } - private CompletableFuture waitForPeers(final int count) { - final WaitForPeersTask waitForPeersTask = - WaitForPeersTask.create(context.getEthContext(), count, context.getMetricsSystem()); - return waitForPeersTask.run(); - } - @Override public void onInitialSyncCompleted() { countDownIfReady(); diff --git a/ethereum/eth/src/main/java/org/hyperledger/besu/ethereum/eth/sync/fastsync/FastSyncActions.java b/ethereum/eth/src/main/java/org/hyperledger/besu/ethereum/eth/sync/fastsync/FastSyncActions.java index 0ce6d2f2ff5..2eb6b460375 100644 --- a/ethereum/eth/src/main/java/org/hyperledger/besu/ethereum/eth/sync/fastsync/FastSyncActions.java +++ b/ethereum/eth/src/main/java/org/hyperledger/besu/ethereum/eth/sync/fastsync/FastSyncActions.java @@ -24,7 +24,6 @@ import org.hyperledger.besu.ethereum.eth.manager.peertask.PeerTaskExecutorResponseCode; import org.hyperledger.besu.ethereum.eth.manager.peertask.PeerTaskExecutorResult; import org.hyperledger.besu.ethereum.eth.manager.peertask.task.GetHeadersFromPeerTask; -import org.hyperledger.besu.ethereum.eth.manager.task.WaitForPeersTask; import org.hyperledger.besu.ethereum.eth.sync.ChainDownloader; import org.hyperledger.besu.ethereum.eth.sync.PivotBlockSelector; import org.hyperledger.besu.ethereum.eth.sync.SynchronizerConfiguration; @@ -131,11 +130,13 @@ public CompletableFuture downloadPivotBlockHeader( private CompletableFuture internalDownloadPivotBlockHeader( final FastSyncState currentState) { if (currentState.hasPivotBlockHeader()) { - LOG.info("Initial sync state {} already contains the block header", currentState); + LOG.debug("Initial sync state {} already contains the block header", currentState); return completedFuture(currentState); } - return waitForPeers(1) + return ethContext + .getEthPeers() + .waitForPeer((peer) -> true) .thenCompose( unused -> currentState @@ -245,11 +246,4 @@ private CompletableFuture downloadPivotBlockHeader(final Hash has public boolean isBlockchainBehind(final long blockNumber) { return protocolContext.getBlockchain().getChainHeadHeader().getNumber() < blockNumber; } - - private CompletableFuture waitForPeers(final int count) { - - final WaitForPeersTask waitForPeersTask = - WaitForPeersTask.create(ethContext, count, metricsSystem); - return waitForPeersTask.run(); - } } diff --git a/ethereum/eth/src/main/java/org/hyperledger/besu/ethereum/eth/sync/fastsync/PivotBlockConfirmer.java b/ethereum/eth/src/main/java/org/hyperledger/besu/ethereum/eth/sync/fastsync/PivotBlockConfirmer.java index e8a07c92050..9b3b40f8a8c 100644 --- a/ethereum/eth/src/main/java/org/hyperledger/besu/ethereum/eth/sync/fastsync/PivotBlockConfirmer.java +++ b/ethereum/eth/src/main/java/org/hyperledger/besu/ethereum/eth/sync/fastsync/PivotBlockConfirmer.java @@ -21,7 +21,6 @@ import org.hyperledger.besu.ethereum.eth.manager.peertask.PeerTaskExecutorResult; import org.hyperledger.besu.ethereum.eth.manager.peertask.task.GetHeadersFromPeerTask; import org.hyperledger.besu.ethereum.eth.manager.task.EthTask; -import org.hyperledger.besu.ethereum.eth.manager.task.WaitForPeerTask; import org.hyperledger.besu.ethereum.eth.sync.SynchronizerConfiguration; import org.hyperledger.besu.ethereum.eth.sync.tasks.RetryingGetHeaderFromPeerByNumberTask; import org.hyperledger.besu.ethereum.mainnet.ProtocolSchedule; @@ -175,7 +174,6 @@ private CompletableFuture executePivotQuery(final long blockNumber) // Stop loop if this task is done return CompletableFuture.failedFuture(new CancellationException()); } - final Optional query = createPivotQuery(blockNumber); final CompletableFuture pivotHeaderFuture; if (query.isPresent()) { @@ -188,9 +186,17 @@ private CompletableFuture executePivotQuery(final long blockNumber) pivotHeaderFuture = ethContext .getScheduler() - .timeout(WaitForPeerTask.create(ethContext, metricsSystem), Duration.ofSeconds(5)) - .handle((err, res) -> null) // Ignore result - .thenCompose(res -> executePivotQuery(blockNumber)); + .scheduleFutureTask( + () -> + ethContext + .getEthPeers() + .waitForPeer( + (peer) -> !pivotBlockQueriesByPeerId.containsKey(peer.nodeId())) + // Ignore result, ensure even a timeout will result in calling + // executePivotQuery + .handle((r, e) -> null) + .thenCompose(res -> executePivotQuery(blockNumber)), + Duration.ofSeconds(5)); } return pivotHeaderFuture; diff --git a/ethereum/eth/src/main/java/org/hyperledger/besu/ethereum/eth/sync/fastsync/PivotSelectorFromPeers.java b/ethereum/eth/src/main/java/org/hyperledger/besu/ethereum/eth/sync/fastsync/PivotSelectorFromPeers.java index 16f7e09d6d1..9816dc66d3f 100644 --- a/ethereum/eth/src/main/java/org/hyperledger/besu/ethereum/eth/sync/fastsync/PivotSelectorFromPeers.java +++ b/ethereum/eth/src/main/java/org/hyperledger/besu/ethereum/eth/sync/fastsync/PivotSelectorFromPeers.java @@ -17,13 +17,11 @@ import org.hyperledger.besu.ethereum.core.BlockHeader; import org.hyperledger.besu.ethereum.eth.manager.EthContext; import org.hyperledger.besu.ethereum.eth.manager.EthPeer; -import org.hyperledger.besu.ethereum.eth.manager.task.WaitForPeersTask; import org.hyperledger.besu.ethereum.eth.sync.PivotBlockSelector; import org.hyperledger.besu.ethereum.eth.sync.SynchronizerConfiguration; import org.hyperledger.besu.ethereum.eth.sync.TrailingPeerLimiter; import org.hyperledger.besu.ethereum.eth.sync.TrailingPeerRequirements; import org.hyperledger.besu.ethereum.eth.sync.state.SyncState; -import org.hyperledger.besu.plugin.services.MetricsSystem; import java.util.Optional; import java.util.concurrent.CompletableFuture; @@ -38,17 +36,14 @@ public class PivotSelectorFromPeers implements PivotBlockSelector { protected final EthContext ethContext; protected final SynchronizerConfiguration syncConfig; private final SyncState syncState; - private final MetricsSystem metricsSystem; public PivotSelectorFromPeers( final EthContext ethContext, final SynchronizerConfiguration syncConfig, - final SyncState syncState, - final MetricsSystem metricsSystem) { + final SyncState syncState) { this.ethContext = ethContext; this.syncConfig = syncConfig; this.syncState = syncState; - this.metricsSystem = metricsSystem; } @Override @@ -58,15 +53,19 @@ public Optional selectNewPivotBlock() { @Override public CompletableFuture prepareRetry() { + final long estimatedPivotBlock = conservativelyEstimatedPivotBlock(); final TrailingPeerLimiter trailingPeerLimiter = new TrailingPeerLimiter( ethContext.getEthPeers(), () -> new TrailingPeerRequirements( - conservativelyEstimatedPivotBlock(), syncConfig.getMaxTrailingPeers())); + estimatedPivotBlock, syncConfig.getMaxTrailingPeers())); trailingPeerLimiter.enforceTrailingPeerLimit(); - return waitForPeers(syncConfig.getSyncMinimumPeerCount()); + return ethContext + .getEthPeers() + .waitForPeer((peer) -> peer.chainState().getEstimatedHeight() >= estimatedPivotBlock) + .thenRun(() -> {}); } @Override @@ -129,10 +128,4 @@ private long conservativelyEstimatedPivotBlock() { syncState.getLocalChainHeight() + syncConfig.getSyncPivotDistance(); return Math.min(syncState.bestChainHeight(), estimatedNextPivot); } - - private CompletableFuture waitForPeers(final int count) { - final WaitForPeersTask waitForPeersTask = - WaitForPeersTask.create(ethContext, count, metricsSystem); - return waitForPeersTask.run(); - } } diff --git a/ethereum/eth/src/main/java/org/hyperledger/besu/ethereum/eth/sync/fastsync/PivotSelectorFromSafeBlock.java b/ethereum/eth/src/main/java/org/hyperledger/besu/ethereum/eth/sync/fastsync/PivotSelectorFromSafeBlock.java index bfbba248c1f..f30fb54e22c 100644 --- a/ethereum/eth/src/main/java/org/hyperledger/besu/ethereum/eth/sync/fastsync/PivotSelectorFromSafeBlock.java +++ b/ethereum/eth/src/main/java/org/hyperledger/besu/ethereum/eth/sync/fastsync/PivotSelectorFromSafeBlock.java @@ -23,7 +23,6 @@ import org.hyperledger.besu.ethereum.eth.manager.peertask.PeerTaskExecutorResponseCode; import org.hyperledger.besu.ethereum.eth.manager.peertask.PeerTaskExecutorResult; import org.hyperledger.besu.ethereum.eth.manager.peertask.task.GetHeadersFromPeerTask; -import org.hyperledger.besu.ethereum.eth.manager.task.WaitForPeersTask; import org.hyperledger.besu.ethereum.eth.sync.PivotBlockSelector; import org.hyperledger.besu.ethereum.eth.sync.SynchronizerConfiguration; import org.hyperledger.besu.ethereum.eth.sync.tasks.RetryingGetHeaderFromPeerByHashTask; @@ -129,7 +128,9 @@ public long getBestChainHeight() { LOG.debug( "Downloading chain head block header by hash {}", headBlockHash); try { - return waitForPeers(1) + return ethContext + .getEthPeers() + .waitForPeer((peer) -> true) .thenCompose(unused -> downloadBlockHeader(headBlockHash)) .thenApply( blockHeader -> { @@ -193,11 +194,4 @@ private CompletableFuture downloadBlockHeader(final Hash hash) { } }); } - - private CompletableFuture waitForPeers(final int count) { - - final WaitForPeersTask waitForPeersTask = - WaitForPeersTask.create(ethContext, count, metricsSystem); - return waitForPeersTask.run(); - } } diff --git a/ethereum/eth/src/test/java/org/hyperledger/besu/ethereum/eth/manager/task/WaitForPeerTaskTest.java b/ethereum/eth/src/test/java/org/hyperledger/besu/ethereum/eth/manager/task/WaitForPeerTaskTest.java deleted file mode 100644 index 07bce17b608..00000000000 --- a/ethereum/eth/src/test/java/org/hyperledger/besu/ethereum/eth/manager/task/WaitForPeerTaskTest.java +++ /dev/null @@ -1,87 +0,0 @@ -/* - * Copyright ConsenSys AG. - * - * 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.task; - -import static org.assertj.core.api.Assertions.assertThat; - -import org.hyperledger.besu.ethereum.eth.manager.EthContext; -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.metrics.noop.NoOpMetricsSystem; -import org.hyperledger.besu.plugin.services.MetricsSystem; - -import java.util.concurrent.CompletableFuture; -import java.util.concurrent.ExecutionException; -import java.util.concurrent.atomic.AtomicBoolean; - -import org.junit.jupiter.api.BeforeEach; -import org.junit.jupiter.api.Test; - -public class WaitForPeerTaskTest { - private EthProtocolManager ethProtocolManager; - private EthContext ethContext; - private final MetricsSystem metricsSystem = new NoOpMetricsSystem(); - - @BeforeEach - public void setupTest() { - ethProtocolManager = EthProtocolManagerTestBuilder.builder().build(); - ethContext = ethProtocolManager.ethContext(); - } - - @Test - public void completesWhenPeerConnects() throws ExecutionException, InterruptedException { - // Execute task and wait for response - final AtomicBoolean successful = new AtomicBoolean(false); - final EthTask task = WaitForPeerTask.create(ethContext, metricsSystem); - final CompletableFuture future = task.run(); - future.whenComplete( - (result, error) -> { - if (error == null) { - successful.compareAndSet(false, true); - } - }); - EthProtocolManagerTestUtil.createPeer(ethProtocolManager); - assertThat(successful).isTrue(); - } - - @Test - public void doesNotCompleteWhenNoPeerConnects() throws ExecutionException, InterruptedException { - final AtomicBoolean successful = new AtomicBoolean(false); - final EthTask task = WaitForPeerTask.create(ethContext, metricsSystem); - final CompletableFuture future = task.run(); - future.whenComplete( - (result, error) -> { - if (error == null) { - successful.compareAndSet(false, true); - } - }); - - assertThat(successful).isFalse(); - } - - @Test - public void cancel() throws ExecutionException, InterruptedException { - // Execute task - final EthTask task = WaitForPeerTask.create(ethContext, metricsSystem); - final CompletableFuture future = task.run(); - - assertThat(future.isDone()).isFalse(); - task.cancel(); - assertThat(future.isDone()).isTrue(); - assertThat(future.isCancelled()).isTrue(); - assertThat(task.run().isCancelled()).isTrue(); - } -} diff --git a/ethereum/eth/src/test/java/org/hyperledger/besu/ethereum/eth/manager/task/WaitForPeersTaskTest.java b/ethereum/eth/src/test/java/org/hyperledger/besu/ethereum/eth/manager/task/WaitForPeersTaskTest.java deleted file mode 100644 index c4bf495139f..00000000000 --- a/ethereum/eth/src/test/java/org/hyperledger/besu/ethereum/eth/manager/task/WaitForPeersTaskTest.java +++ /dev/null @@ -1,105 +0,0 @@ -/* - * Copyright ConsenSys AG. - * - * 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.task; - -import static org.assertj.core.api.Assertions.assertThat; - -import org.hyperledger.besu.ethereum.eth.manager.EthContext; -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.metrics.noop.NoOpMetricsSystem; -import org.hyperledger.besu.plugin.services.MetricsSystem; - -import java.util.concurrent.CompletableFuture; -import java.util.concurrent.ExecutionException; -import java.util.concurrent.atomic.AtomicBoolean; - -import org.junit.jupiter.api.BeforeEach; -import org.junit.jupiter.api.Test; - -public class WaitForPeersTaskTest { - private EthProtocolManager ethProtocolManager; - private EthContext ethContext; - private final MetricsSystem metricsSystem = new NoOpMetricsSystem(); - - @BeforeEach - public void setupTest() { - ethProtocolManager = EthProtocolManagerTestBuilder.builder().build(); - ethContext = ethProtocolManager.ethContext(); - } - - @Test - public void completesWhenPeersConnects() throws ExecutionException, InterruptedException { - // Execute task and wait for response - final AtomicBoolean successful = new AtomicBoolean(false); - final EthTask task = WaitForPeersTask.create(ethContext, 2, metricsSystem); - final CompletableFuture future = task.run(); - future.whenComplete( - (result, error) -> { - if (error == null) { - successful.compareAndSet(false, true); - } - }); - EthProtocolManagerTestUtil.createPeer(ethProtocolManager); - EthProtocolManagerTestUtil.createPeer(ethProtocolManager); - assertThat(successful).isTrue(); - } - - @Test - public void doesNotCompleteWhenNoPeerConnects() throws ExecutionException, InterruptedException { - final AtomicBoolean successful = new AtomicBoolean(false); - final EthTask task = WaitForPeersTask.create(ethContext, 2, metricsSystem); - final CompletableFuture future = task.run(); - future.whenComplete( - (result, error) -> { - if (error == null) { - successful.compareAndSet(false, true); - } - }); - - assertThat(successful).isFalse(); - } - - @Test - public void doesNotCompleteWhenSomePeersConnects() - throws ExecutionException, InterruptedException { - final AtomicBoolean successful = new AtomicBoolean(false); - final EthTask task = WaitForPeersTask.create(ethContext, 2, metricsSystem); - final CompletableFuture future = task.run(); - future.whenComplete( - (result, error) -> { - if (error == null) { - successful.compareAndSet(false, true); - } - }); - EthProtocolManagerTestUtil.createPeer(ethProtocolManager); - - assertThat(successful).isFalse(); - } - - @Test - public void cancel() throws ExecutionException, InterruptedException { - // Execute task - final EthTask task = WaitForPeersTask.create(ethContext, 2, metricsSystem); - final CompletableFuture future = task.run(); - - assertThat(future.isDone()).isFalse(); - task.cancel(); - assertThat(future.isDone()).isTrue(); - assertThat(future.isCancelled()).isTrue(); - assertThat(task.run().isCancelled()).isTrue(); - } -} diff --git a/ethereum/eth/src/test/java/org/hyperledger/besu/ethereum/eth/sync/fastsync/FastSyncActionsTest.java b/ethereum/eth/src/test/java/org/hyperledger/besu/ethereum/eth/sync/fastsync/FastSyncActionsTest.java index ffce23ee2c9..fe9683059f4 100644 --- a/ethereum/eth/src/test/java/org/hyperledger/besu/ethereum/eth/sync/fastsync/FastSyncActionsTest.java +++ b/ethereum/eth/src/test/java/org/hyperledger/besu/ethereum/eth/sync/fastsync/FastSyncActionsTest.java @@ -16,6 +16,8 @@ import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; import org.hyperledger.besu.config.GenesisConfigOptions; @@ -29,7 +31,6 @@ import org.hyperledger.besu.ethereum.core.ProtocolScheduleFixture; import org.hyperledger.besu.ethereum.eth.EthProtocolConfiguration; import org.hyperledger.besu.ethereum.eth.manager.EthContext; -import org.hyperledger.besu.ethereum.eth.manager.EthPeer; import org.hyperledger.besu.ethereum.eth.manager.EthPeers; import org.hyperledger.besu.ethereum.eth.manager.EthProtocolManager; import org.hyperledger.besu.ethereum.eth.manager.EthProtocolManagerTestBuilder; @@ -119,8 +120,7 @@ public void setUp( metricsSystem = new NoOpMetricsSystem(); fastSyncActions = createFastSyncActions( - syncConfig, - new PivotSelectorFromPeers(ethContext, syncConfig, syncState, metricsSystem)); + syncConfig, new PivotSelectorFromPeers(ethContext, syncConfig, syncState)); } @ParameterizedTest @@ -170,8 +170,7 @@ public void selectPivotBlockShouldSelectBlockPivotDistanceFromBestPeer( fastSyncActions = createFastSyncActions( - syncConfig, - new PivotSelectorFromPeers(ethContext, syncConfig, syncState, metricsSystem)); + syncConfig, new PivotSelectorFromPeers(ethContext, syncConfig, syncState)); EthProtocolManagerTestUtil.createPeer(ethProtocolManager, 5000); @@ -188,8 +187,7 @@ public void selectPivotBlockShouldConsiderTotalDifficultyWhenSelectingBestPeer( setUp(storageFormat, false, Optional.of(1)); fastSyncActions = createFastSyncActions( - syncConfig, - new PivotSelectorFromPeers(ethContext, syncConfig, syncState, metricsSystem)); + syncConfig, new PivotSelectorFromPeers(ethContext, syncConfig, syncState)); EthProtocolManagerTestUtil.createPeer(ethProtocolManager, Difficulty.of(1000), 5500); EthProtocolManagerTestUtil.createPeer(ethProtocolManager, Difficulty.of(2000), 4000); @@ -208,8 +206,7 @@ public void selectPivotBlockShouldWaitAndRetryUntilMinHeightEstimatesAreAvailabl EthProtocolManagerTestUtil.disableEthSchedulerAutoRun(ethProtocolManager); fastSyncActions = createFastSyncActions( - syncConfig, - new PivotSelectorFromPeers(ethContext, syncConfig, syncState, metricsSystem)); + syncConfig, new PivotSelectorFromPeers(ethContext, syncConfig, syncState)); final CompletableFuture result = fastSyncActions.selectPivotBlock(FastSyncState.EMPTY_SYNC_STATE); @@ -231,100 +228,27 @@ public void selectPivotBlockShouldWaitAndRetryUntilMinHeightEstimatesAreAvailabl @ParameterizedTest @ArgumentsSource(FastSyncActionsTest.FastSyncActionsTestArguments.class) - public void selectPivotBlockShouldWaitAndRetryIfSufficientChainHeightEstimatesAreUnavailable( + public void selectPivotBlockShouldRetryIfPivotBlockSelectorReturnsEmptyOptional( final DataStorageFormat storageFormat) { - int minPeers = 3; - setUp(storageFormat, false, Optional.of(minPeers)); - fastSyncActions = - createFastSyncActions( - syncConfig, - new PivotSelectorFromPeers(ethContext, syncConfig, syncState, metricsSystem)); - final long minPivotHeight = syncConfig.getSyncPivotDistance() + 1L; - EthProtocolManagerTestUtil.disableEthSchedulerAutoRun(ethProtocolManager); - - // Create peers without chain height estimates - List peers = new ArrayList<>(); - for (int i = 0; i < minPeers; i++) { - final Difficulty td = Difficulty.of(i); - final OptionalLong height = OptionalLong.empty(); - final RespondingEthPeer peer = - EthProtocolManagerTestUtil.createPeer(ethProtocolManager, td, height); - peers.add(peer); - } - - // No pivot should be selected while peers do not have height estimates - final CompletableFuture result = - fastSyncActions.selectPivotBlock(FastSyncState.EMPTY_SYNC_STATE); - assertThat(result).isNotDone(); - EthProtocolManagerTestUtil.runPendingFutures(ethProtocolManager); - assertThat(result).isNotDone(); - - // Set subset of heights - peers - .subList(0, minPeers - 1) - .forEach(p -> p.getEthPeer().chainState().updateHeightEstimate(minPivotHeight + 10)); - - // No pivot should be selected while only a subset of peers have height estimates - EthProtocolManagerTestUtil.runPendingFutures(ethProtocolManager); - assertThat(result).isNotDone(); - - // Set final height - final long bestPeerHeight = minPivotHeight + 1; - peers.get(minPeers - 1).getEthPeer().chainState().updateHeightEstimate(bestPeerHeight); - final FastSyncState expected = - new FastSyncState(bestPeerHeight - syncConfig.getSyncPivotDistance()); - EthProtocolManagerTestUtil.runPendingFutures(ethProtocolManager); - assertThat(result).isCompletedWithValue(expected); - } + setUp(storageFormat, false, Optional.of(3)); - @ParameterizedTest - @ArgumentsSource(FastSyncActionsTest.FastSyncActionsTestArguments.class) - public void selectPivotBlockShouldWaitAndRetryIfSufficientValidatedPeersUnavailable( - final DataStorageFormat storageFormat) { - final int minPeers = 3; - setUp(storageFormat, false, Optional.of(minPeers)); - final PeerValidator validator = mock(PeerValidator.class); - fastSyncActions = - createFastSyncActions( - syncConfig, - new PivotSelectorFromPeers(ethContext, syncConfig, syncState, metricsSystem)); - final long minPivotHeight = syncConfig.getSyncPivotDistance() + 1L; - EthProtocolManagerTestUtil.disableEthSchedulerAutoRun(ethProtocolManager); + PivotBlockSelector pivotBlockSelector = mock(PivotBlockSelector.class); + fastSyncActions = createFastSyncActions(syncConfig, pivotBlockSelector); - // Create peers that are not validated - final OptionalLong height = OptionalLong.of(minPivotHeight + 10); - List peers = new ArrayList<>(); - for (int i = 0; i < minPeers; i++) { - final Difficulty td = Difficulty.of(i); + FastSyncState expectedResult = new FastSyncState(123); - final RespondingEthPeer peer = - EthProtocolManagerTestUtil.createPeer(ethProtocolManager, td, height, validator); - peers.add(peer); - } + when(pivotBlockSelector.selectNewPivotBlock()) + .thenReturn(Optional.empty()) + .thenReturn(Optional.of(expectedResult)); + when(pivotBlockSelector.prepareRetry()).thenReturn(CompletableFuture.runAsync(() -> {})); - // No pivot should be selected while peers are not fully validated - final CompletableFuture result = + CompletableFuture resultFuture = fastSyncActions.selectPivotBlock(FastSyncState.EMPTY_SYNC_STATE); - assertThat(result).isNotDone(); - EthProtocolManagerTestUtil.runPendingFutures(ethProtocolManager); - assertThat(result).isNotDone(); - - // Validate a subset of peers - peers.subList(0, minPeers - 1).forEach(p -> p.getEthPeer().markValidated(validator)); - // No pivot should be selected while only a subset of peers has height estimates - EthProtocolManagerTestUtil.runPendingFutures(ethProtocolManager); - assertThat(result).isNotDone(); + verify(pivotBlockSelector, times(2)).selectNewPivotBlock(); + verify(pivotBlockSelector).prepareRetry(); - // Set best height and mark best peer validated - final long bestPeerHeight = minPivotHeight + 11; - final EthPeer bestPeer = peers.get(minPeers - 1).getEthPeer(); - bestPeer.chainState().updateHeightEstimate(bestPeerHeight); - bestPeer.markValidated(validator); - final FastSyncState expected = - new FastSyncState(bestPeerHeight - syncConfig.getSyncPivotDistance()); - EthProtocolManagerTestUtil.runPendingFutures(ethProtocolManager); - assertThat(result).isCompletedWithValue(expected); + assertThat(resultFuture).isCompletedWithValue(expectedResult); } @ParameterizedTest @@ -355,8 +279,7 @@ private void selectPivotBlockUsesBestPeerMatchingRequiredCriteria( final int peerCount = 4; fastSyncActions = createFastSyncActions( - syncConfig, - new PivotSelectorFromPeers(ethContext, syncConfig, syncState, metricsSystem)); + syncConfig, new PivotSelectorFromPeers(ethContext, syncConfig, syncState)); final long minPivotHeight = syncConfig.getSyncPivotDistance() + 1L; EthProtocolManagerTestUtil.disableEthSchedulerAutoRun(ethProtocolManager); @@ -404,8 +327,7 @@ public void selectPivotBlockShouldWaitAndRetryIfBestPeerChainIsShorterThanPivotD setUp(storageFormat, false, Optional.of(1)); fastSyncActions = createFastSyncActions( - syncConfig, - new PivotSelectorFromPeers(ethContext, syncConfig, syncState, metricsSystem)); + syncConfig, new PivotSelectorFromPeers(ethContext, syncConfig, syncState)); final long pivotDistance = syncConfig.getSyncPivotDistance(); EthProtocolManagerTestUtil.disableEthSchedulerAutoRun(ethProtocolManager); @@ -466,8 +388,7 @@ public void downloadPivotBlockHeaderShouldRetrievePivotBlockHeader( setUp(storageFormat, false, Optional.of(1)); fastSyncActions = createFastSyncActions( - syncConfig, - new PivotSelectorFromPeers(ethContext, syncConfig, syncState, metricsSystem)); + syncConfig, new PivotSelectorFromPeers(ethContext, syncConfig, syncState)); final RespondingEthPeer peer = EthProtocolManagerTestUtil.createPeer(ethProtocolManager, 1001); final CompletableFuture result = diff --git a/ethereum/eth/src/test/java/org/hyperledger/besu/ethereum/eth/sync/fastsync/PivotBlockRetrieverTest.java b/ethereum/eth/src/test/java/org/hyperledger/besu/ethereum/eth/sync/fastsync/PivotBlockRetrieverTest.java index 2bfc84876a4..9cd23a54bdf 100644 --- a/ethereum/eth/src/test/java/org/hyperledger/besu/ethereum/eth/sync/fastsync/PivotBlockRetrieverTest.java +++ b/ethereum/eth/src/test/java/org/hyperledger/besu/ethereum/eth/sync/fastsync/PivotBlockRetrieverTest.java @@ -164,6 +164,7 @@ public void shouldIgnorePeersThatDoNotHaveThePivotBlock(final DataStorageFormat // Add new peer that we can query final RespondingEthPeer respondingPeerB = EthProtocolManagerTestUtil.createPeer(ethProtocolManager, 1000); + EthProtocolManagerTestUtil.runPendingFutures(ethProtocolManager); respondingPeerB.respond(responder); // We need one more responsive peer before we're done @@ -174,6 +175,7 @@ public void shouldIgnorePeersThatDoNotHaveThePivotBlock(final DataStorageFormat // Add new peer that we can query final RespondingEthPeer respondingPeerC = EthProtocolManagerTestUtil.createPeer(ethProtocolManager, 1000); + EthProtocolManagerTestUtil.runPendingFutures(ethProtocolManager); respondingPeerC.respond(responder); assertThat(badPeerA.hasOutstandingRequests()).isFalse(); assertThat(badPeerB.hasOutstandingRequests()).isFalse(); @@ -215,11 +217,9 @@ public void shouldIgnorePeersThatAreNotFullyValidated(final DataStorageFormat st final RespondingEthPeer respondingPeerB = EthProtocolManagerTestUtil.createPeer(ethProtocolManager, 1000, peerValidator); respondingPeerB.getEthPeer().markValidated(peerValidator); - // When our new peer "connects", it is not yet valid, so we need to expire our retry timeout - // so that the peer will get re-processed - EthProtocolManagerTestUtil.expirePendingTimeouts(ethProtocolManager); + // add another peer to ensure we get past the waitForPeer call + EthProtocolManagerTestUtil.createPeer(ethProtocolManager, 1000, peerValidator); - assertThat(respondingPeerB.hasOutstandingRequests()).isTrue(); respondingPeerB.respond(responder); // We need one more responsive peer before we're done @@ -231,9 +231,9 @@ public void shouldIgnorePeersThatAreNotFullyValidated(final DataStorageFormat st final RespondingEthPeer respondingPeerC = EthProtocolManagerTestUtil.createPeer(ethProtocolManager, 1000, peerValidator); respondingPeerC.getEthPeer().markValidated(peerValidator); - EthProtocolManagerTestUtil.expirePendingTimeouts(ethProtocolManager); + // add another peer to ensure we get past the waitForPeer call + EthProtocolManagerTestUtil.createPeer(ethProtocolManager, 1000, peerValidator); - assertThat(respondingPeerC.hasOutstandingRequests()).isTrue(); respondingPeerC.respond(responder); assertThat(badPeerA.hasOutstandingRequests()).isFalse(); assertThat(badPeerB.hasOutstandingRequests()).isFalse(); From 0448af8d242145551a5f22837841fe15cdd7d830 Mon Sep 17 00:00:00 2001 From: Sally MacFarlane Date: Thu, 19 Dec 2024 10:55:41 +1000 Subject: [PATCH 5/6] [CHANGELOG] clarify breaking changes (#8052) * clarify breaking changes in changelog Signed-off-by: Sally MacFarlane --------- Signed-off-by: Sally MacFarlane --- CHANGELOG.md | 4 +--- .../org/hyperledger/besu/evm/gascalculator/GasCalculator.java | 4 ++-- 2 files changed, 3 insertions(+), 5 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 9f0f3d40763..5202ffb9c8a 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -6,10 +6,8 @@ - `--host-whitelist` has been deprecated since 2020 and this option is removed. Use the equivalent `--host-allowlist` instead. ### Upcoming Breaking Changes -- Plugin API will be deprecating the BesuContext interface to be replaced with the ServiceManager interface. - `MetricSystem::createLabelledGauge` is deprecated and will be removed in a future release, replace it with `MetricSystem::createLabelledSuppliedGauge` -- k8s (KUBERNETES) Nat method is now deprecated and will be removed in a future release -- `--host-whitelist` has been deprecated in favor of `--host-allowlist` since 2020 and will be removed in a future release +- k8s (KUBERNETES) Nat method is now deprecated and will be removed in a future release. Use docker or none instead. - Sunsetting features - for more context on the reasoning behind the deprecation of these features, including alternative options, read [this blog post](https://www.lfdecentralizedtrust.org/blog/sunsetting-tessera-and-simplifying-hyperledger-besu) - Tessera privacy - Smart-contract-based (onchain) permissioning diff --git a/evm/src/main/java/org/hyperledger/besu/evm/gascalculator/GasCalculator.java b/evm/src/main/java/org/hyperledger/besu/evm/gascalculator/GasCalculator.java index 049b197d031..9859d1dd7d7 100644 --- a/evm/src/main/java/org/hyperledger/besu/evm/gascalculator/GasCalculator.java +++ b/evm/src/main/java/org/hyperledger/besu/evm/gascalculator/GasCalculator.java @@ -673,8 +673,8 @@ default long delegateCodeGasCost(final int delegateCodeListLength) { } /** - * Calculates the refund for proessing the 7702 code delegation list if an delegater account - * already exist in the trie. + * Calculates the refund for processing the 7702 code delegation list if a delegator account + * already exists in the trie. * * @param alreadyExistingAccountSize The number of accounts already in the trie * @return the gas refund From a03c98bf9e4e5edc1c4eb1d9ef0973130e6f8a89 Mon Sep 17 00:00:00 2001 From: Gabriel-Trintinalia Date: Thu, 19 Dec 2024 13:01:07 +0800 Subject: [PATCH 6/6] eth_simulateV1 - Add BlockSimulator feature (#7941) Signed-off-by: Gabriel-Trintinalia --- .../org/hyperledger/besu/cli/BesuCommand.java | 11 + .../services/BlockSimulatorServiceImpl.java | 158 +++++++ .../besu/services/BlockchainServiceImpl.java | 2 +- .../parameters/BlockOverridesParameter.java | 76 ++++ .../jsonrpc/internal/results/BlockResult.java | 19 + .../results/CallProcessingResult.java | 95 ++++ .../AbstractJsonRpcHttpServiceTest.java | 3 + .../transaction/BlockSimulationException.java | 21 + .../transaction/BlockSimulationResult.java | 58 +++ .../ethereum/transaction/BlockSimulator.java | 423 ++++++++++++++++++ .../ethereum/transaction/BlockStateCall.java | 61 +++ .../transaction/TransactionSimulator.java | 23 + .../TransactionSimulatorResult.java | 6 + .../transaction/BlockSimulatorTest.java | 251 +++++++++++ plugin-api/build.gradle | 2 +- .../besu/plugin/data/BlockOverrides.java | 382 ++++++++++++++++ .../data/PluginBlockSimulationResult.java | 80 ++++ .../services/BlockSimulationService.java | 59 +++ .../plugin/services/BlockchainService.java | 3 +- 19 files changed, 1730 insertions(+), 3 deletions(-) create mode 100644 besu/src/main/java/org/hyperledger/besu/services/BlockSimulatorServiceImpl.java create mode 100644 ethereum/api/src/main/java/org/hyperledger/besu/ethereum/api/jsonrpc/internal/parameters/BlockOverridesParameter.java create mode 100644 ethereum/api/src/main/java/org/hyperledger/besu/ethereum/api/jsonrpc/internal/results/CallProcessingResult.java create mode 100644 ethereum/core/src/main/java/org/hyperledger/besu/ethereum/transaction/BlockSimulationException.java create mode 100644 ethereum/core/src/main/java/org/hyperledger/besu/ethereum/transaction/BlockSimulationResult.java create mode 100644 ethereum/core/src/main/java/org/hyperledger/besu/ethereum/transaction/BlockSimulator.java create mode 100644 ethereum/core/src/main/java/org/hyperledger/besu/ethereum/transaction/BlockStateCall.java create mode 100644 ethereum/core/src/test/java/org/hyperledger/besu/ethereum/transaction/BlockSimulatorTest.java create mode 100644 plugin-api/src/main/java/org/hyperledger/besu/plugin/data/BlockOverrides.java create mode 100644 plugin-api/src/main/java/org/hyperledger/besu/plugin/data/PluginBlockSimulationResult.java create mode 100644 plugin-api/src/main/java/org/hyperledger/besu/plugin/services/BlockSimulationService.java diff --git a/besu/src/main/java/org/hyperledger/besu/cli/BesuCommand.java b/besu/src/main/java/org/hyperledger/besu/cli/BesuCommand.java index 5f7047dcae3..029f87b005b 100644 --- a/besu/src/main/java/org/hyperledger/besu/cli/BesuCommand.java +++ b/besu/src/main/java/org/hyperledger/besu/cli/BesuCommand.java @@ -152,6 +152,7 @@ import org.hyperledger.besu.plugin.data.EnodeURL; import org.hyperledger.besu.plugin.services.BesuConfiguration; import org.hyperledger.besu.plugin.services.BesuEvents; +import org.hyperledger.besu.plugin.services.BlockSimulationService; import org.hyperledger.besu.plugin.services.BlockchainService; import org.hyperledger.besu.plugin.services.MetricsSystem; import org.hyperledger.besu.plugin.services.PermissioningService; @@ -178,6 +179,7 @@ import org.hyperledger.besu.services.BesuConfigurationImpl; import org.hyperledger.besu.services.BesuEventsImpl; import org.hyperledger.besu.services.BesuPluginContextImpl; +import org.hyperledger.besu.services.BlockSimulatorServiceImpl; import org.hyperledger.besu.services.BlockchainServiceImpl; import org.hyperledger.besu.services.MiningServiceImpl; import org.hyperledger.besu.services.P2PServiceImpl; @@ -1288,6 +1290,15 @@ private void startPlugins(final Runner runner) { besuPluginContext.addService( MiningService.class, new MiningServiceImpl(besuController.getMiningCoordinator())); + besuPluginContext.addService( + BlockSimulationService.class, + new BlockSimulatorServiceImpl( + besuController.getProtocolContext().getWorldStateArchive(), + miningParametersSupplier.get(), + besuController.getTransactionSimulator(), + besuController.getProtocolSchedule(), + besuController.getProtocolContext().getBlockchain())); + besuController.getAdditionalPluginServices().appendPluginServices(besuPluginContext); besuPluginContext.startPlugins(); } diff --git a/besu/src/main/java/org/hyperledger/besu/services/BlockSimulatorServiceImpl.java b/besu/src/main/java/org/hyperledger/besu/services/BlockSimulatorServiceImpl.java new file mode 100644 index 00000000000..f840cd30273 --- /dev/null +++ b/besu/src/main/java/org/hyperledger/besu/services/BlockSimulatorServiceImpl.java @@ -0,0 +1,158 @@ +/* + * 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.services; + +import org.hyperledger.besu.datatypes.AccountOverrideMap; +import org.hyperledger.besu.datatypes.Transaction; +import org.hyperledger.besu.ethereum.chain.Blockchain; +import org.hyperledger.besu.ethereum.core.BlockHeader; +import org.hyperledger.besu.ethereum.core.MiningConfiguration; +import org.hyperledger.besu.ethereum.core.MutableWorldState; +import org.hyperledger.besu.ethereum.mainnet.ProtocolSchedule; +import org.hyperledger.besu.ethereum.transaction.BlockSimulationResult; +import org.hyperledger.besu.ethereum.transaction.BlockSimulator; +import org.hyperledger.besu.ethereum.transaction.BlockStateCall; +import org.hyperledger.besu.ethereum.transaction.CallParameter; +import org.hyperledger.besu.ethereum.transaction.TransactionSimulator; +import org.hyperledger.besu.ethereum.worldstate.WorldStateArchive; +import org.hyperledger.besu.plugin.Unstable; +import org.hyperledger.besu.plugin.data.BlockOverrides; +import org.hyperledger.besu.plugin.data.PluginBlockSimulationResult; +import org.hyperledger.besu.plugin.data.TransactionSimulationResult; +import org.hyperledger.besu.plugin.services.BlockSimulationService; + +import java.util.List; + +/** This class is a service that simulates the processing of a block */ +public class BlockSimulatorServiceImpl implements BlockSimulationService { + private final BlockSimulator blockSimulator; + private final WorldStateArchive worldStateArchive; + private final Blockchain blockchain; + + /** + * This constructor creates a BlockSimulatorServiceImpl object + * + * @param worldStateArchive the world state archive + * @param miningConfiguration the mining configuration + * @param transactionSimulator the transaction simulator + * @param protocolSchedule the protocol schedule + * @param blockchain the blockchain + */ + public BlockSimulatorServiceImpl( + final WorldStateArchive worldStateArchive, + final MiningConfiguration miningConfiguration, + final TransactionSimulator transactionSimulator, + final ProtocolSchedule protocolSchedule, + final Blockchain blockchain) { + this.blockchain = blockchain; + blockSimulator = + new BlockSimulator( + worldStateArchive, protocolSchedule, transactionSimulator, miningConfiguration); + this.worldStateArchive = worldStateArchive; + } + + /** + * Simulate the processing of a block given a header, a list of transactions, and blockOverrides. + * + * @param blockNumber the block number + * @param transactions the transactions to include in the block + * @param blockOverrides the blockSimulationOverride of the block + * @param accountOverrides state overrides of the block + * @return the block context + */ + @Override + public PluginBlockSimulationResult simulate( + final long blockNumber, + final List transactions, + final BlockOverrides blockOverrides, + final AccountOverrideMap accountOverrides) { + return processSimulation(blockNumber, transactions, blockOverrides, accountOverrides, false); + } + + /** + * This method is experimental and should be used with caution. Simulate the processing of a block + * given a header, a list of transactions, and blockOverrides and persist the WorldState + * + * @param blockNumber the block number + * @param transactions the transactions to include in the block + * @param blockOverrides block overrides for the block + * @param accountOverrides state overrides of the block + * @return the PluginBlockSimulationResult + */ + @Unstable + @Override + public PluginBlockSimulationResult simulateAndPersistWorldState( + final long blockNumber, + final List transactions, + final BlockOverrides blockOverrides, + final AccountOverrideMap accountOverrides) { + return processSimulation(blockNumber, transactions, blockOverrides, accountOverrides, true); + } + + private PluginBlockSimulationResult processSimulation( + final long blockNumber, + final List transactions, + final BlockOverrides blockOverrides, + final AccountOverrideMap accountOverrides, + final boolean persistWorldState) { + BlockHeader header = getBlockHeader(blockNumber); + List callParameters = + transactions.stream().map(CallParameter::fromTransaction).toList(); + BlockStateCall blockStateCall = + new BlockStateCall(callParameters, blockOverrides, accountOverrides, true); + try (final MutableWorldState ws = getWorldState(header, persistWorldState)) { + List results = + blockSimulator.process(header, List.of(blockStateCall), ws); + BlockSimulationResult result = results.getFirst(); + if (persistWorldState) { + ws.persist(result.getBlock().getHeader()); + } + return response(result); + } catch (final Exception e) { + throw new RuntimeException("Error simulating block", e); + } + } + + private BlockHeader getBlockHeader(final long blockNumber) { + return blockchain + .getBlockHeader(blockNumber) + .orElseThrow( + () -> + new IllegalArgumentException( + "Block header not found for block number: " + blockNumber)); + } + + private MutableWorldState getWorldState(final BlockHeader header, final boolean isPersisting) { + return worldStateArchive + .getMutable(header, isPersisting) + .orElseThrow( + () -> + new IllegalArgumentException( + "World state not available for block number (block hash): " + + header.toLogString())); + } + + private PluginBlockSimulationResult response(final BlockSimulationResult result) { + return new PluginBlockSimulationResult( + result.getBlockHeader(), + result.getBlockBody(), + result.getReceipts(), + result.getTransactionSimulations().stream() + .map( + simulation -> + new TransactionSimulationResult(simulation.transaction(), simulation.result())) + .toList()); + } +} diff --git a/besu/src/main/java/org/hyperledger/besu/services/BlockchainServiceImpl.java b/besu/src/main/java/org/hyperledger/besu/services/BlockchainServiceImpl.java index 76b4d7e1509..b1893ef37fb 100644 --- a/besu/src/main/java/org/hyperledger/besu/services/BlockchainServiceImpl.java +++ b/besu/src/main/java/org/hyperledger/besu/services/BlockchainServiceImpl.java @@ -108,7 +108,7 @@ public Optional> getReceiptsByBlockHash(final Hash bloc public void storeBlock( final BlockHeader blockHeader, final BlockBody blockBody, - final List receipts) { + final List receipts) { final org.hyperledger.besu.ethereum.core.BlockHeader coreHeader = (org.hyperledger.besu.ethereum.core.BlockHeader) blockHeader; final org.hyperledger.besu.ethereum.core.BlockBody coreBody = diff --git a/ethereum/api/src/main/java/org/hyperledger/besu/ethereum/api/jsonrpc/internal/parameters/BlockOverridesParameter.java b/ethereum/api/src/main/java/org/hyperledger/besu/ethereum/api/jsonrpc/internal/parameters/BlockOverridesParameter.java new file mode 100644 index 00000000000..9cd6e880b42 --- /dev/null +++ b/ethereum/api/src/main/java/org/hyperledger/besu/ethereum/api/jsonrpc/internal/parameters/BlockOverridesParameter.java @@ -0,0 +1,76 @@ +/* + * 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.api.jsonrpc.internal.parameters; + +import org.hyperledger.besu.datatypes.Address; +import org.hyperledger.besu.datatypes.Hash; +import org.hyperledger.besu.datatypes.Wei; +import org.hyperledger.besu.datatypes.parameters.UnsignedLongParameter; +import org.hyperledger.besu.plugin.data.BlockOverrides; + +import java.math.BigInteger; +import java.util.Optional; + +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonProperty; +import org.apache.tuweni.bytes.Bytes; +import org.apache.tuweni.bytes.Bytes32; + +public class BlockOverridesParameter extends BlockOverrides { + /** + * Constructs a new BlockOverrides instance. + * + * @param timestamp the optional timestamp + * @param blockNumber the optional block number + * @param blockHash the optional block hash + * @param prevRandao the optional previous Randao + * @param gasLimit the optional gas limit + * @param feeRecipient the optional fee recipient + * @param baseFeePerGas the optional base fee per gas + * @param blobBaseFee the optional blob base fee + * @param stateRoot the optional state root + * @param difficulty the optional difficulty + * @param extraData the optional extra data + * @param mixHashOrPrevRandao the optional mix hash or previous Randao + */ + @JsonCreator + public BlockOverridesParameter( + @JsonProperty("time") final Optional timestamp, + @JsonProperty("number") final Optional blockNumber, + @JsonProperty("hash") final Optional blockHash, + @JsonProperty("prevRandao") final Optional prevRandao, + @JsonProperty("gasLimit") final Optional gasLimit, + @JsonProperty("feeRecipient") final Optional
feeRecipient, + @JsonProperty("baseFeePerGas") final Optional baseFeePerGas, + @JsonProperty("blobBaseFee") final Optional blobBaseFee, + @JsonProperty("stateRoot") final Optional stateRoot, + @JsonProperty("difficulty") final Optional difficulty, + @JsonProperty("extraData") final Optional extraData, + @JsonProperty("mixHashOrPrevRandao") final Optional mixHashOrPrevRandao) { + super( + timestamp, + blockNumber, + blockHash, + prevRandao, + gasLimit, + feeRecipient, + baseFeePerGas, + blobBaseFee, + stateRoot, + difficulty, + extraData, + mixHashOrPrevRandao); + } +} diff --git a/ethereum/api/src/main/java/org/hyperledger/besu/ethereum/api/jsonrpc/internal/results/BlockResult.java b/ethereum/api/src/main/java/org/hyperledger/besu/ethereum/api/jsonrpc/internal/results/BlockResult.java index c2456f061de..e74cf2f4e0a 100644 --- a/ethereum/api/src/main/java/org/hyperledger/besu/ethereum/api/jsonrpc/internal/results/BlockResult.java +++ b/ethereum/api/src/main/java/org/hyperledger/besu/ethereum/api/jsonrpc/internal/results/BlockResult.java @@ -89,6 +89,7 @@ public class BlockResult implements JsonRpcResult { private final String excessBlobGas; private final String parentBeaconBlockRoot; private final String targetBlobsPerBlock; + private final List callProcessingResults; public BlockResult( final BlockHeader header, @@ -107,6 +108,18 @@ public BlockResult( final int size, final boolean includeCoinbase, final Optional> withdrawals) { + this(header, transactions, ommers, null, totalDifficulty, size, includeCoinbase, withdrawals); + } + + public BlockResult( + final BlockHeader header, + final List transactions, + final List ommers, + final List callProcessingResults, + final Difficulty totalDifficulty, + final int size, + final boolean includeCoinbase, + final Optional> withdrawals) { this.number = Quantity.create(header.getNumber()); this.hash = header.getHash().toString(); this.mixHash = header.getMixHash().toString(); @@ -128,6 +141,7 @@ public BlockResult( this.timestamp = Quantity.create(header.getTimestamp()); this.ommers = ommers; this.transactions = transactions; + this.callProcessingResults = callProcessingResults; this.coinbase = includeCoinbase ? header.getCoinbase().toString() : null; this.withdrawalsRoot = header.getWithdrawalsRoot().map(Hash::toString).orElse(null); this.withdrawals = @@ -282,4 +296,9 @@ public String getParentBeaconBlockRoot() { public String getTargetBlobsPerBlock() { return targetBlobsPerBlock; } + + @JsonGetter(value = "calls") + public List getTransactionProcessingResults() { + return callProcessingResults; + } } diff --git a/ethereum/api/src/main/java/org/hyperledger/besu/ethereum/api/jsonrpc/internal/results/CallProcessingResult.java b/ethereum/api/src/main/java/org/hyperledger/besu/ethereum/api/jsonrpc/internal/results/CallProcessingResult.java new file mode 100644 index 00000000000..9015a61c854 --- /dev/null +++ b/ethereum/api/src/main/java/org/hyperledger/besu/ethereum/api/jsonrpc/internal/results/CallProcessingResult.java @@ -0,0 +1,95 @@ +/* + * 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.api.jsonrpc.internal.results; + +import java.util.List; + +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import org.apache.tuweni.bytes.Bytes; + +public class CallProcessingResult { + @JsonProperty("status") + private final String status; + + @JsonProperty("returnData") + private final String returnData; + + @JsonProperty("gasUsed") + private final String gasUsed; + + @JsonProperty("error") + private final ErrorDetails error; + + @JsonProperty("logs") + private final List logs; + + public CallProcessingResult( + @JsonProperty("status") final int status, + @JsonProperty("returnData") final Bytes returnData, + @JsonProperty("gasUsed") final long gasUsed, + @JsonProperty("error") final ErrorDetails error, + @JsonProperty("logs") final List logs) { + this.status = Quantity.create(status); + this.returnData = returnData.toString(); + + this.gasUsed = Quantity.create(gasUsed); + this.error = error; + this.logs = logs; + } + + public String getStatus() { + return status; + } + + public String getReturnData() { + return returnData; + } + + public String getGasUsed() { + return gasUsed; + } + + @JsonInclude(JsonInclude.Include.NON_NULL) + public ErrorDetails getError() { + return error; + } + + @JsonInclude(JsonInclude.Include.NON_NULL) + public List getLogs() { + return logs; + } + + public record ErrorDetails( + @JsonProperty("code") long code, + @JsonProperty("message") String message, + @JsonProperty("data") Bytes data) { + + @Override + public long code() { + return code; + } + + @Override + public String message() { + return message; + } + + @Override + public Bytes data() { + return data; + } + } +} diff --git a/ethereum/api/src/test/java/org/hyperledger/besu/ethereum/api/jsonrpc/AbstractJsonRpcHttpServiceTest.java b/ethereum/api/src/test/java/org/hyperledger/besu/ethereum/api/jsonrpc/AbstractJsonRpcHttpServiceTest.java index 0da11a03528..5afbbbfebd8 100644 --- a/ethereum/api/src/test/java/org/hyperledger/besu/ethereum/api/jsonrpc/AbstractJsonRpcHttpServiceTest.java +++ b/ethereum/api/src/test/java/org/hyperledger/besu/ethereum/api/jsonrpc/AbstractJsonRpcHttpServiceTest.java @@ -21,6 +21,7 @@ import static org.mockito.Mockito.when; import org.hyperledger.besu.config.StubGenesisConfigOptions; +import org.hyperledger.besu.datatypes.Address; import org.hyperledger.besu.ethereum.ProtocolContext; import org.hyperledger.besu.ethereum.api.ApiConfiguration; import org.hyperledger.besu.ethereum.api.graphql.GraphQLConfiguration; @@ -147,6 +148,8 @@ protected Map getRpcMethods( .thenReturn(ValidationResult.invalid(TransactionInvalidReason.NONCE_TOO_LOW)); final PrivacyParameters privacyParameters = mock(PrivacyParameters.class); + when(miningConfiguration.getCoinbase()).thenReturn(Optional.of(Address.ZERO)); + final BlockchainQueries blockchainQueries = new BlockchainQueries( blockchainSetupUtil.getProtocolSchedule(), diff --git a/ethereum/core/src/main/java/org/hyperledger/besu/ethereum/transaction/BlockSimulationException.java b/ethereum/core/src/main/java/org/hyperledger/besu/ethereum/transaction/BlockSimulationException.java new file mode 100644 index 00000000000..c304ed9ae1a --- /dev/null +++ b/ethereum/core/src/main/java/org/hyperledger/besu/ethereum/transaction/BlockSimulationException.java @@ -0,0 +1,21 @@ +/* + * 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.transaction; + +public class BlockSimulationException extends RuntimeException { + public BlockSimulationException(final String message) { + super(message); + } +} diff --git a/ethereum/core/src/main/java/org/hyperledger/besu/ethereum/transaction/BlockSimulationResult.java b/ethereum/core/src/main/java/org/hyperledger/besu/ethereum/transaction/BlockSimulationResult.java new file mode 100644 index 00000000000..da0846890f6 --- /dev/null +++ b/ethereum/core/src/main/java/org/hyperledger/besu/ethereum/transaction/BlockSimulationResult.java @@ -0,0 +1,58 @@ +/* + * 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.transaction; + +import org.hyperledger.besu.ethereum.core.Block; +import org.hyperledger.besu.plugin.data.BlockBody; +import org.hyperledger.besu.plugin.data.BlockHeader; +import org.hyperledger.besu.plugin.data.TransactionReceipt; + +import java.util.ArrayList; +import java.util.List; + +public class BlockSimulationResult { + final Block block; + final List receipts; + List transactionSimulationResults; + + public BlockSimulationResult( + final Block block, + final List receipts, + final List transactionSimulationResults) { + this.block = block; + this.receipts = new ArrayList<>(receipts); + this.transactionSimulationResults = transactionSimulationResults; + } + + public BlockHeader getBlockHeader() { + return block.getHeader(); + } + + public BlockBody getBlockBody() { + return block.getBody(); + } + + public List getReceipts() { + return receipts; + } + + public List getTransactionSimulations() { + return transactionSimulationResults; + } + + public Block getBlock() { + return block; + } +} diff --git a/ethereum/core/src/main/java/org/hyperledger/besu/ethereum/transaction/BlockSimulator.java b/ethereum/core/src/main/java/org/hyperledger/besu/ethereum/transaction/BlockSimulator.java new file mode 100644 index 00000000000..018ce76ca7b --- /dev/null +++ b/ethereum/core/src/main/java/org/hyperledger/besu/ethereum/transaction/BlockSimulator.java @@ -0,0 +1,423 @@ +/* + * 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.transaction; + +import org.hyperledger.besu.datatypes.AccountOverride; +import org.hyperledger.besu.datatypes.AccountOverrideMap; +import org.hyperledger.besu.datatypes.Address; +import org.hyperledger.besu.datatypes.Hash; +import org.hyperledger.besu.datatypes.Wei; +import org.hyperledger.besu.ethereum.core.Block; +import org.hyperledger.besu.ethereum.core.BlockBody; +import org.hyperledger.besu.ethereum.core.BlockHeader; +import org.hyperledger.besu.ethereum.core.BlockHeaderBuilder; +import org.hyperledger.besu.ethereum.core.BlockHeaderFunctions; +import org.hyperledger.besu.ethereum.core.Difficulty; +import org.hyperledger.besu.ethereum.core.MiningConfiguration; +import org.hyperledger.besu.ethereum.core.MutableWorldState; +import org.hyperledger.besu.ethereum.core.ParsedExtraData; +import org.hyperledger.besu.ethereum.core.Transaction; +import org.hyperledger.besu.ethereum.core.TransactionReceipt; +import org.hyperledger.besu.ethereum.mainnet.BodyValidation; +import org.hyperledger.besu.ethereum.mainnet.ImmutableTransactionValidationParams; +import org.hyperledger.besu.ethereum.mainnet.MainnetBlockHeaderFunctions; +import org.hyperledger.besu.ethereum.mainnet.MiningBeneficiaryCalculator; +import org.hyperledger.besu.ethereum.mainnet.ProtocolSchedule; +import org.hyperledger.besu.ethereum.mainnet.ProtocolSpec; +import org.hyperledger.besu.ethereum.mainnet.TransactionValidationParams; +import org.hyperledger.besu.ethereum.mainnet.feemarket.BaseFeeMarket; +import org.hyperledger.besu.ethereum.mainnet.feemarket.FeeMarket; +import org.hyperledger.besu.ethereum.processing.TransactionProcessingResult; +import org.hyperledger.besu.ethereum.worldstate.WorldStateArchive; +import org.hyperledger.besu.evm.account.MutableAccount; +import org.hyperledger.besu.evm.tracing.OperationTracer; +import org.hyperledger.besu.evm.worldstate.WorldUpdater; +import org.hyperledger.besu.plugin.data.BlockOverrides; + +import java.util.ArrayList; +import java.util.List; +import java.util.Optional; + +import com.google.common.annotations.VisibleForTesting; +import org.apache.tuweni.bytes.Bytes; +import org.apache.tuweni.units.bigints.UInt256; + +/** + * Simulates the execution of a block, processing transactions and applying state overrides. This + * class is responsible for simulating the execution of a block, which involves processing + * transactions and applying state overrides. It provides a way to test and validate the behavior of + * a block without actually executing it on the blockchain. The simulator takes into account various + * factors, such as the block header, transaction calls, and state overrides, to simulate the + * execution of the block. It returns a list of simulation results, which include the final block + * header, transaction receipts, and other relevant information. + */ +public class BlockSimulator { + private final TransactionSimulator transactionSimulator; + private final WorldStateArchive worldStateArchive; + private final ProtocolSchedule protocolSchedule; + private final MiningConfiguration miningConfiguration; + + public BlockSimulator( + final WorldStateArchive worldStateArchive, + final ProtocolSchedule protocolSchedule, + final TransactionSimulator transactionSimulator, + final MiningConfiguration miningConfiguration) { + this.worldStateArchive = worldStateArchive; + this.protocolSchedule = protocolSchedule; + this.miningConfiguration = miningConfiguration; + this.transactionSimulator = transactionSimulator; + } + + /** + * Processes a list of BlockStateCalls sequentially, collecting the results. + * + * @param header The block header for all simulations. + * @param blockStateCalls The list of BlockStateCalls to process. + * @return A list of BlockSimulationResult objects from processing each BlockStateCall. + */ + public List process( + final BlockHeader header, final List blockStateCalls) { + try (final MutableWorldState ws = + worldStateArchive + .getMutable(header, false) + .orElseThrow( + () -> + new IllegalArgumentException( + "Public world state not available for block " + header.toLogString()))) { + return process(header, blockStateCalls, ws); + } catch (IllegalArgumentException e) { + throw e; + } catch (final Exception e) { + throw new RuntimeException("Error simulating block", e); + } + } + + /** + * Processes a list of BlockStateCalls sequentially, collecting the results. + * + * @param header The block header for all simulations. + * @param blockStateCalls The list of BlockStateCalls to process. + * @param worldState The initial MutableWorldState to start with. + * @return A list of BlockSimulationResult objects from processing each BlockStateCall. + */ + public List process( + final BlockHeader header, + final List blockStateCalls, + final MutableWorldState worldState) { + List simulationResults = new ArrayList<>(); + for (BlockStateCall blockStateCall : blockStateCalls) { + BlockSimulationResult simulationResult = + processSingleBlockStateCall(header, blockStateCall, worldState); + simulationResults.add(simulationResult); + } + return simulationResults; + } + + /** + * Processes a single BlockStateCall, simulating the block execution. + * + * @param header The block header for the simulation. + * @param blockStateCall The BlockStateCall to process. + * @param ws The MutableWorldState to use for the simulation. + * @return A BlockSimulationResult from processing the BlockStateCall. + */ + private BlockSimulationResult processSingleBlockStateCall( + final BlockHeader header, final BlockStateCall blockStateCall, final MutableWorldState ws) { + BlockOverrides blockOverrides = blockStateCall.getBlockOverrides(); + long timestamp = blockOverrides.getTimestamp().orElse(header.getTimestamp() + 1); + ProtocolSpec newProtocolSpec = protocolSchedule.getForNextBlockHeader(header, timestamp); + + // Apply block header overrides and state overrides + BlockHeader blockHeader = applyBlockHeaderOverrides(header, newProtocolSpec, blockOverrides); + blockStateCall.getAccountOverrides().ifPresent(overrides -> applyStateOverrides(overrides, ws)); + + // Override the mining beneficiary calculator if a fee recipient is specified, otherwise use the + // default + MiningBeneficiaryCalculator miningBeneficiaryCalculator = + getMiningBeneficiaryCalculator(blockOverrides, newProtocolSpec); + + List transactionSimulatorResults = + processTransactions(blockHeader, blockStateCall, ws, miningBeneficiaryCalculator); + + return finalizeBlock( + blockHeader, blockStateCall, ws, newProtocolSpec, transactionSimulatorResults); + } + + @VisibleForTesting + protected List processTransactions( + final BlockHeader blockHeader, + final BlockStateCall blockStateCall, + final MutableWorldState ws, + final MiningBeneficiaryCalculator miningBeneficiaryCalculator) { + + List transactionSimulations = new ArrayList<>(); + + for (CallParameter callParameter : blockStateCall.getCalls()) { + final WorldUpdater transactionUpdater = ws.updater(); + + final Optional transactionSimulatorResult = + transactionSimulator.processWithWorldUpdater( + callParameter, + Optional.empty(), // We have already applied state overrides on block level + buildTransactionValidationParams(blockStateCall.isValidate()), + OperationTracer.NO_TRACING, + blockHeader, + transactionUpdater, + miningBeneficiaryCalculator); + + if (transactionSimulatorResult.isEmpty()) { + throw new BlockSimulationException("Transaction simulator result is empty"); + } + + TransactionSimulatorResult result = transactionSimulatorResult.get(); + if (result.isInvalid()) { + throw new BlockSimulationException( + "Transaction simulator result is invalid: " + result.getInvalidReason().orElse(null)); + } + transactionSimulations.add(transactionSimulatorResult.get()); + transactionUpdater.commit(); + } + return transactionSimulations; + } + + @VisibleForTesting + protected BlockSimulationResult finalizeBlock( + final BlockHeader blockHeader, + final BlockStateCall blockStateCall, + final MutableWorldState ws, + final ProtocolSpec protocolSpec, + final List transactionSimulations) { + + long currentGasUsed = 0; + final var transactionReceiptFactory = protocolSpec.getTransactionReceiptFactory(); + + final List receipts = new ArrayList<>(); + final List transactions = new ArrayList<>(); + + for (TransactionSimulatorResult transactionSimulatorResult : transactionSimulations) { + + TransactionProcessingResult transactionProcessingResult = transactionSimulatorResult.result(); + final Transaction transaction = transactionSimulatorResult.transaction(); + + currentGasUsed += transaction.getGasLimit() - transactionProcessingResult.getGasRemaining(); + + final TransactionReceipt transactionReceipt = + transactionReceiptFactory.create( + transaction.getType(), transactionProcessingResult, ws, currentGasUsed); + + receipts.add(transactionReceipt); + transactions.add(transaction); + } + + BlockHeader finalBlockHeader = + createFinalBlockHeader( + blockHeader, + ws, + transactions, + blockStateCall.getBlockOverrides(), + receipts, + currentGasUsed); + Block block = new Block(finalBlockHeader, new BlockBody(transactions, List.of())); + return new BlockSimulationResult(block, receipts, transactionSimulations); + } + + /** + * Applies state overrides to the world state. + * + * @param accountOverrideMap The AccountOverrideMap containing the state overrides. + * @param ws The MutableWorldState to apply the overrides to. + */ + @VisibleForTesting + protected void applyStateOverrides( + final AccountOverrideMap accountOverrideMap, final MutableWorldState ws) { + var updater = ws.updater(); + for (Address accountToOverride : accountOverrideMap.keySet()) { + final AccountOverride override = accountOverrideMap.get(accountToOverride); + MutableAccount account = updater.getOrCreate(accountToOverride); + override.getNonce().ifPresent(account::setNonce); + if (override.getBalance().isPresent()) { + account.setBalance(override.getBalance().get()); + } + override.getCode().ifPresent(n -> account.setCode(Bytes.fromHexString(n))); + override + .getStateDiff() + .ifPresent( + d -> + d.forEach( + (key, value) -> + account.setStorageValue( + UInt256.fromHexString(key), UInt256.fromHexString(value)))); + } + updater.commit(); + } + + /** + * Applies block header overrides to the block header. + * + * @param header The original block header. + * @param newProtocolSpec The ProtocolSpec for the block. + * @param blockOverrides The BlockOverrides to apply. + * @return The modified block header. + */ + @VisibleForTesting + protected BlockHeader applyBlockHeaderOverrides( + final BlockHeader header, + final ProtocolSpec newProtocolSpec, + final BlockOverrides blockOverrides) { + long timestamp = blockOverrides.getTimestamp().orElse(header.getTimestamp() + 1); + long blockNumber = blockOverrides.getBlockNumber().orElse(header.getNumber() + 1); + + return BlockHeaderBuilder.createDefault() + .parentHash(header.getHash()) + .timestamp(timestamp) + .number(blockNumber) + .coinbase( + blockOverrides + .getFeeRecipient() + .orElseGet(() -> miningConfiguration.getCoinbase().orElseThrow())) + .difficulty( + blockOverrides.getDifficulty().isPresent() + ? Difficulty.of(blockOverrides.getDifficulty().get()) + : header.getDifficulty()) + .gasLimit( + blockOverrides + .getGasLimit() + .orElseGet(() -> getNextGasLimit(newProtocolSpec, header, blockNumber))) + .baseFee( + blockOverrides + .getBaseFeePerGas() + .orElseGet(() -> getNextBaseFee(newProtocolSpec, header, blockNumber))) + .mixHash(blockOverrides.getMixHashOrPrevRandao().orElse(Hash.EMPTY)) + .extraData(blockOverrides.getExtraData().orElse(Bytes.EMPTY)) + .blockHeaderFunctions(new SimulatorBlockHeaderFunctions(blockOverrides)) + .buildBlockHeader(); + } + + /** + * Creates the final block header after applying state changes and transaction processing. + * + * @param blockHeader The original block header. + * @param ws The MutableWorldState after applying state overrides. + * @param transactions The list of transactions in the block. + * @param blockOverrides The BlockOverrides to apply. + * @param receipts The list of transaction receipts. + * @param currentGasUsed The total gas used in the block. + * @return The final block header. + */ + private BlockHeader createFinalBlockHeader( + final BlockHeader blockHeader, + final MutableWorldState ws, + final List transactions, + final BlockOverrides blockOverrides, + final List receipts, + final long currentGasUsed) { + + return BlockHeaderBuilder.createDefault() + .populateFrom(blockHeader) + .ommersHash(BodyValidation.ommersHash(List.of())) + .stateRoot(blockOverrides.getStateRoot().orElse(ws.rootHash())) + .transactionsRoot(BodyValidation.transactionsRoot(transactions)) + .receiptsRoot(BodyValidation.receiptsRoot(receipts)) + .logsBloom(BodyValidation.logsBloom(receipts)) + .gasUsed(currentGasUsed) + .withdrawalsRoot(null) + .requestsHash(null) + .mixHash(blockOverrides.getMixHashOrPrevRandao().orElse(Hash.EMPTY)) + .extraData(blockOverrides.getExtraData().orElse(Bytes.EMPTY)) + .blockHeaderFunctions(new SimulatorBlockHeaderFunctions(blockOverrides)) + .buildBlockHeader(); + } + + /** + * Builds the TransactionValidationParams for the block simulation. + * + * @param shouldValidate Whether to validate transactions. + * @return The TransactionValidationParams for the block simulation. + */ + @VisibleForTesting + ImmutableTransactionValidationParams buildTransactionValidationParams( + final boolean shouldValidate) { + + if (shouldValidate) { + return ImmutableTransactionValidationParams.builder() + .from(TransactionValidationParams.processingBlock()) + .build(); + } + + return ImmutableTransactionValidationParams.builder() + .from(TransactionValidationParams.transactionSimulator()) + .isAllowExceedingBalance(true) + .build(); + } + + private long getNextGasLimit( + final ProtocolSpec protocolSpec, final BlockHeader parentHeader, final long blockNumber) { + return protocolSpec + .getGasLimitCalculator() + .nextGasLimit( + parentHeader.getGasLimit(), + miningConfiguration.getTargetGasLimit().orElse(parentHeader.getGasLimit()), + blockNumber); + } + + /** + * Override the mining beneficiary calculator if a fee recipient is specified, otherwise use the + * default + */ + private MiningBeneficiaryCalculator getMiningBeneficiaryCalculator( + final BlockOverrides blockOverrides, final ProtocolSpec newProtocolSpec) { + if (blockOverrides.getFeeRecipient().isPresent()) { + return blockHeader -> blockOverrides.getFeeRecipient().get(); + } else { + return newProtocolSpec.getMiningBeneficiaryCalculator(); + } + } + + private Wei getNextBaseFee( + final ProtocolSpec protocolSpec, final BlockHeader parentHeader, final long blockNumber) { + return Optional.of(protocolSpec.getFeeMarket()) + .filter(FeeMarket::implementsBaseFee) + .map(BaseFeeMarket.class::cast) + .map( + feeMarket -> + feeMarket.computeBaseFee( + blockNumber, + parentHeader.getBaseFee().orElse(Wei.ZERO), + parentHeader.getGasUsed(), + feeMarket.targetGasUsed(parentHeader))) + .orElse(null); + } + + private static class SimulatorBlockHeaderFunctions implements BlockHeaderFunctions { + + private final BlockOverrides blockOverrides; + private final MainnetBlockHeaderFunctions blockHeaderFunctions = + new MainnetBlockHeaderFunctions(); + + private SimulatorBlockHeaderFunctions(final BlockOverrides blockOverrides) { + this.blockOverrides = blockOverrides; + } + + @Override + public Hash hash(final BlockHeader header) { + return blockOverrides.getBlockHash().orElseGet(() -> blockHeaderFunctions.hash(header)); + } + + @Override + public ParsedExtraData parseExtraData(final BlockHeader header) { + return blockHeaderFunctions.parseExtraData(header); + } + } +} diff --git a/ethereum/core/src/main/java/org/hyperledger/besu/ethereum/transaction/BlockStateCall.java b/ethereum/core/src/main/java/org/hyperledger/besu/ethereum/transaction/BlockStateCall.java new file mode 100644 index 00000000000..5db5faee23c --- /dev/null +++ b/ethereum/core/src/main/java/org/hyperledger/besu/ethereum/transaction/BlockStateCall.java @@ -0,0 +1,61 @@ +/* + * 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.transaction; + +import org.hyperledger.besu.datatypes.AccountOverrideMap; +import org.hyperledger.besu.plugin.data.BlockOverrides; + +import java.util.ArrayList; +import java.util.List; +import java.util.Optional; + +public class BlockStateCall { + + private final BlockOverrides blockOverrides; + + private final List calls; + + private final AccountOverrideMap accountOverrides; + + private final boolean validation; + + public BlockStateCall( + final List calls, + final BlockOverrides blockOverrides, + final AccountOverrideMap accountOverrides, + final boolean validation) { + this.calls = calls != null ? calls : new ArrayList<>(); + this.blockOverrides = + blockOverrides != null ? blockOverrides : BlockOverrides.builder().build(); + this.accountOverrides = accountOverrides; + this.validation = validation; + } + + public boolean isValidate() { + return validation; + } + + public BlockOverrides getBlockOverrides() { + return blockOverrides; + } + + public Optional getAccountOverrides() { + return Optional.ofNullable(accountOverrides); + } + + public List getCalls() { + return calls; + } +} diff --git a/ethereum/core/src/main/java/org/hyperledger/besu/ethereum/transaction/TransactionSimulator.java b/ethereum/core/src/main/java/org/hyperledger/besu/ethereum/transaction/TransactionSimulator.java index 57cef89006a..a9161922a08 100644 --- a/ethereum/core/src/main/java/org/hyperledger/besu/ethereum/transaction/TransactionSimulator.java +++ b/ethereum/core/src/main/java/org/hyperledger/besu/ethereum/transaction/TransactionSimulator.java @@ -34,6 +34,7 @@ import org.hyperledger.besu.ethereum.core.ProcessableBlockHeader; import org.hyperledger.besu.ethereum.core.Transaction; import org.hyperledger.besu.ethereum.mainnet.MainnetTransactionProcessor; +import org.hyperledger.besu.ethereum.mainnet.MiningBeneficiaryCalculator; import org.hyperledger.besu.ethereum.mainnet.ProtocolSchedule; import org.hyperledger.besu.ethereum.mainnet.ProtocolSpec; import org.hyperledger.besu.ethereum.mainnet.TransactionValidationParams; @@ -341,6 +342,28 @@ private MutableWorldState getWorldState(final BlockHeader header) { "Public world state not available for block " + header.toLogString())); } + @Nonnull + public Optional processWithWorldUpdater( + final CallParameter callParams, + final Optional maybeStateOverrides, + final TransactionValidationParams transactionValidationParams, + final OperationTracer operationTracer, + final BlockHeader header, + final WorldUpdater updater, + final MiningBeneficiaryCalculator miningBeneficiaryCalculator) { + + final Address miningBeneficiary = miningBeneficiaryCalculator.calculateBeneficiary(header); + + return processWithWorldUpdater( + callParams, + maybeStateOverrides, + transactionValidationParams, + operationTracer, + header, + updater, + miningBeneficiary); + } + @Nonnull public Optional processWithWorldUpdater( final CallParameter callParams, diff --git a/ethereum/core/src/main/java/org/hyperledger/besu/ethereum/transaction/TransactionSimulatorResult.java b/ethereum/core/src/main/java/org/hyperledger/besu/ethereum/transaction/TransactionSimulatorResult.java index 853bc4611a3..d06c6722505 100644 --- a/ethereum/core/src/main/java/org/hyperledger/besu/ethereum/transaction/TransactionSimulatorResult.java +++ b/ethereum/core/src/main/java/org/hyperledger/besu/ethereum/transaction/TransactionSimulatorResult.java @@ -18,6 +18,8 @@ import org.hyperledger.besu.ethereum.mainnet.ValidationResult; import org.hyperledger.besu.ethereum.processing.TransactionProcessingResult; +import java.util.Optional; + import org.apache.tuweni.bytes.Bytes; public record TransactionSimulatorResult( @@ -42,4 +44,8 @@ public Bytes getOutput() { public ValidationResult getValidationResult() { return result.getValidationResult(); } + + public Optional getInvalidReason() { + return result.getInvalidReason(); + } } diff --git a/ethereum/core/src/test/java/org/hyperledger/besu/ethereum/transaction/BlockSimulatorTest.java b/ethereum/core/src/test/java/org/hyperledger/besu/ethereum/transaction/BlockSimulatorTest.java new file mode 100644 index 00000000000..bb1225107ec --- /dev/null +++ b/ethereum/core/src/test/java/org/hyperledger/besu/ethereum/transaction/BlockSimulatorTest.java @@ -0,0 +1,251 @@ +/* + * 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.transaction; + +import static org.assertj.core.api.AssertionsForClassTypes.assertThat; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.anyLong; +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +import org.hyperledger.besu.datatypes.AccountOverride; +import org.hyperledger.besu.datatypes.AccountOverrideMap; +import org.hyperledger.besu.datatypes.Address; +import org.hyperledger.besu.datatypes.Hash; +import org.hyperledger.besu.datatypes.Wei; +import org.hyperledger.besu.ethereum.GasLimitCalculator; +import org.hyperledger.besu.ethereum.core.BlockHeader; +import org.hyperledger.besu.ethereum.core.BlockHeaderBuilder; +import org.hyperledger.besu.ethereum.core.Difficulty; +import org.hyperledger.besu.ethereum.core.MiningConfiguration; +import org.hyperledger.besu.ethereum.core.MutableWorldState; +import org.hyperledger.besu.ethereum.mainnet.ImmutableTransactionValidationParams; +import org.hyperledger.besu.ethereum.mainnet.MiningBeneficiaryCalculator; +import org.hyperledger.besu.ethereum.mainnet.ProtocolSchedule; +import org.hyperledger.besu.ethereum.mainnet.ProtocolSpec; +import org.hyperledger.besu.ethereum.mainnet.TransactionValidationParams; +import org.hyperledger.besu.ethereum.mainnet.feemarket.FeeMarket; +import org.hyperledger.besu.ethereum.worldstate.WorldStateArchive; +import org.hyperledger.besu.evm.account.MutableAccount; +import org.hyperledger.besu.evm.worldstate.WorldUpdater; +import org.hyperledger.besu.plugin.data.BlockOverrides; + +import java.math.BigInteger; +import java.util.Collections; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Optional; +import java.util.Set; + +import org.apache.tuweni.bytes.Bytes; +import org.apache.tuweni.units.bigints.UInt256; +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; +import org.mockito.junit.jupiter.MockitoSettings; +import org.mockito.quality.Strictness; + +@ExtendWith(MockitoExtension.class) +@MockitoSettings(strictness = Strictness.LENIENT) +public class BlockSimulatorTest { + + @Mock private WorldStateArchive worldStateArchive; + @Mock private ProtocolSchedule protocolSchedule; + @Mock private TransactionSimulator transactionSimulator; + @Mock private MiningConfiguration miningConfiguration; + @Mock private MutableWorldState mutableWorldState; + private BlockHeader blockHeader; + + private BlockSimulator blockSimulator; + + @BeforeEach + public void setUp() { + blockSimulator = + new BlockSimulator( + worldStateArchive, protocolSchedule, transactionSimulator, miningConfiguration); + blockHeader = BlockHeaderBuilder.createDefault().buildBlockHeader(); + ProtocolSpec protocolSpec = mock(ProtocolSpec.class); + when(miningConfiguration.getCoinbase()) + .thenReturn(Optional.ofNullable(Address.fromHexString("0x1"))); + when(protocolSchedule.getForNextBlockHeader(any(), anyLong())).thenReturn(protocolSpec); + when(protocolSpec.getMiningBeneficiaryCalculator()) + .thenReturn(mock(MiningBeneficiaryCalculator.class)); + GasLimitCalculator gasLimitCalculator = mock(GasLimitCalculator.class); + when(protocolSpec.getGasLimitCalculator()).thenReturn(gasLimitCalculator); + when(gasLimitCalculator.nextGasLimit(anyLong(), anyLong(), anyLong())).thenReturn(1L); + when(protocolSpec.getFeeMarket()).thenReturn(mock(FeeMarket.class)); + } + + @Test + public void shouldProcessWithValidWorldState() { + when(worldStateArchive.getMutable(any(BlockHeader.class), eq(false))) + .thenReturn(Optional.of(mutableWorldState)); + + List results = + blockSimulator.process(blockHeader, Collections.emptyList()); + + assertNotNull(results); + verify(worldStateArchive).getMutable(any(BlockHeader.class), eq(false)); + } + + @Test + public void shouldNotProcessWithInvalidWorldState() { + when(worldStateArchive.getMutable(any(BlockHeader.class), eq(false))) + .thenReturn(Optional.empty()); + + IllegalArgumentException exception = + assertThrows( + IllegalArgumentException.class, + () -> blockSimulator.process(blockHeader, Collections.emptyList())); + + assertEquals( + String.format("Public world state not available for block %s", blockHeader.toLogString()), + exception.getMessage()); + } + + @Test + public void shouldStopWhenTransactionSimulationIsInvalid() { + + CallParameter callParameter = mock(CallParameter.class); + BlockStateCall blockStateCall = new BlockStateCall(List.of(callParameter), null, null, true); + + TransactionSimulatorResult transactionSimulatorResult = mock(TransactionSimulatorResult.class); + when(transactionSimulatorResult.isInvalid()).thenReturn(true); + when(transactionSimulatorResult.getInvalidReason()) + .thenReturn(Optional.of("Invalid Transaction")); + + when(transactionSimulator.processWithWorldUpdater( + any(), any(), any(), any(), any(), any(), any(MiningBeneficiaryCalculator.class))) + .thenReturn(Optional.of(transactionSimulatorResult)); + + BlockSimulationException exception = + assertThrows( + BlockSimulationException.class, + () -> blockSimulator.process(blockHeader, List.of(blockStateCall), mutableWorldState)); + + assertEquals( + "Transaction simulator result is invalid: Invalid Transaction", exception.getMessage()); + } + + @Test + public void shouldStopWhenTransactionSimulationIsEmpty() { + + CallParameter callParameter = mock(CallParameter.class); + BlockStateCall blockStateCall = new BlockStateCall(List.of(callParameter), null, null, true); + + when(transactionSimulator.processWithWorldUpdater( + any(), any(), any(), any(), any(), any(), any(MiningBeneficiaryCalculator.class))) + .thenReturn(Optional.empty()); + + BlockSimulationException exception = + assertThrows( + BlockSimulationException.class, + () -> blockSimulator.process(blockHeader, List.of(blockStateCall), mutableWorldState)); + + assertEquals("Transaction simulator result is empty", exception.getMessage()); + } + + @Test + public void shouldApplyStateOverridesCorrectly() { + AccountOverrideMap accountOverrideMap = mock(AccountOverrideMap.class); + Address address = mock(Address.class); + AccountOverride accountOverride = mock(AccountOverride.class); + MutableAccount mutableAccount = mock(MutableAccount.class); + + when(accountOverrideMap.keySet()).thenReturn(Set.of(address)); + when(accountOverrideMap.get(address)).thenReturn(accountOverride); + + WorldUpdater worldUpdater = mock(WorldUpdater.class); + when(mutableWorldState.updater()).thenReturn(worldUpdater); + + when(worldUpdater.getOrCreate(address)).thenReturn(mutableAccount); + + when(accountOverride.getNonce()).thenReturn(Optional.of(123L)); + when(accountOverride.getBalance()).thenReturn(Optional.of(Wei.of(456L))); + when(accountOverride.getCode()).thenReturn(Optional.of("")); + when(accountOverride.getStateDiff()) + .thenReturn(Optional.of(new HashMap<>(Map.of("0x0", "0x1")))); + + blockSimulator.applyStateOverrides(accountOverrideMap, mutableWorldState); + + verify(mutableAccount).setNonce(anyLong()); + verify(mutableAccount).setBalance(any(Wei.class)); + verify(mutableAccount).setCode(any(Bytes.class)); + verify(mutableAccount).setStorageValue(any(UInt256.class), any(UInt256.class)); + } + + @Test + public void shouldApplyBlockHeaderOverridesCorrectly() { + ProtocolSpec protocolSpec = mock(ProtocolSpec.class); + + var expectedTimestamp = 1L; + var expectedBlockNumber = 2L; + var expectedFeeRecipient = Address.fromHexString("0x1"); + var expectedBaseFeePerGas = Wei.of(7L); + var expectedGasLimit = 5L; + var expectedDifficulty = BigInteger.ONE; + var expectedMixHashOrPrevRandao = Hash.hash(Bytes.fromHexString("0x01")); + var expectedExtraData = Bytes.fromHexString("0x02"); + + BlockOverrides blockOverrides = + BlockOverrides.builder() + .timestamp(expectedTimestamp) + .blockNumber(expectedBlockNumber) + .feeRecipient(expectedFeeRecipient) + .baseFeePerGas(expectedBaseFeePerGas) + .gasLimit(expectedGasLimit) + .difficulty(expectedDifficulty) + .mixHashOrPrevRandao(expectedMixHashOrPrevRandao) + .extraData(expectedExtraData) + .build(); + + BlockHeader result = + blockSimulator.applyBlockHeaderOverrides(blockHeader, protocolSpec, blockOverrides); + + assertNotNull(result); + assertEquals(expectedTimestamp, result.getTimestamp()); + assertEquals(expectedBlockNumber, result.getNumber()); + assertEquals(expectedFeeRecipient, result.getCoinbase()); + assertEquals(Optional.of(expectedBaseFeePerGas), result.getBaseFee()); + assertEquals(expectedGasLimit, result.getGasLimit()); + assertThat(result.getDifficulty()).isEqualTo(Difficulty.of(expectedDifficulty)); + assertEquals(expectedMixHashOrPrevRandao, result.getMixHash()); + assertEquals(expectedExtraData, result.getExtraData()); + } + + @Test + public void testBuildTransactionValidationParams() { + var configWhenValidate = + ImmutableTransactionValidationParams.builder() + .from(TransactionValidationParams.processingBlock()) + .build(); + + ImmutableTransactionValidationParams params = + blockSimulator.buildTransactionValidationParams(true); + assertThat(params).isEqualTo(configWhenValidate); + assertThat(params.isAllowExceedingBalance()).isFalse(); + + params = blockSimulator.buildTransactionValidationParams(false); + assertThat(params.isAllowExceedingBalance()).isTrue(); + } +} diff --git a/plugin-api/build.gradle b/plugin-api/build.gradle index f8608f89325..070313150eb 100644 --- a/plugin-api/build.gradle +++ b/plugin-api/build.gradle @@ -71,7 +71,7 @@ Calculated : ${currentHash} tasks.register('checkAPIChanges', FileStateChecker) { description = "Checks that the API for the Plugin-API project does not change without deliberate thought" files = sourceSets.main.allJava.files - knownHash = 'TPCo4SZ61OrJxRAa2SIcAIOAOjVTdRw+UOeHMuiJP84=' + knownHash = '+YR9PYN+gPCvXzK2w52ypz9dZ0FOy0G3I1PljZasOkU=' } check.dependsOn('checkAPIChanges') diff --git a/plugin-api/src/main/java/org/hyperledger/besu/plugin/data/BlockOverrides.java b/plugin-api/src/main/java/org/hyperledger/besu/plugin/data/BlockOverrides.java new file mode 100644 index 00000000000..703bb64b373 --- /dev/null +++ b/plugin-api/src/main/java/org/hyperledger/besu/plugin/data/BlockOverrides.java @@ -0,0 +1,382 @@ +/* + * 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.plugin.data; + +import org.hyperledger.besu.datatypes.Address; +import org.hyperledger.besu.datatypes.Hash; +import org.hyperledger.besu.datatypes.Wei; +import org.hyperledger.besu.datatypes.parameters.UnsignedLongParameter; + +import java.math.BigInteger; +import java.util.Optional; + +import org.apache.tuweni.bytes.Bytes; +import org.apache.tuweni.bytes.Bytes32; + +/** BlockOverrides represents the block overrides for a block. */ +public class BlockOverrides { + private final Optional timestamp; + private final Optional blockNumber; + private final Optional blockHash; + private final Optional prevRandao; + private final Optional gasLimit; + private final Optional
feeRecipient; + private final Optional baseFeePerGas; + private final Optional blobBaseFee; + private final Optional stateRoot; + private final Optional difficulty; + private final Optional extraData; + private final Optional mixHashOrPrevRandao; + + /** + * Constructs a new BlockOverrides instance. + * + * @param timestamp the optional timestamp + * @param blockNumber the optional block number + * @param blockHash the optional block hash + * @param prevRandao the optional previous Randao + * @param gasLimit the optional gas limit + * @param feeRecipient the optional fee recipient + * @param baseFeePerGas the optional base fee per gas + * @param blobBaseFee the optional blob base fee + * @param stateRoot the optional state root + * @param difficulty the optional difficulty + * @param extraData the optional extra data + * @param mixHashOrPrevRandao the optional mix hash or previous Randao + */ + public BlockOverrides( + final Optional timestamp, + final Optional blockNumber, + final Optional blockHash, + final Optional prevRandao, + final Optional gasLimit, + final Optional
feeRecipient, + final Optional baseFeePerGas, + final Optional blobBaseFee, + final Optional stateRoot, + final Optional difficulty, + final Optional extraData, + final Optional mixHashOrPrevRandao) { + this.timestamp = timestamp.map(UnsignedLongParameter::getValue); + this.blockNumber = blockNumber.map(UnsignedLongParameter::getValue); + this.blockHash = blockHash; + this.prevRandao = prevRandao; + this.gasLimit = gasLimit.map(UnsignedLongParameter::getValue); + this.feeRecipient = feeRecipient; + this.baseFeePerGas = baseFeePerGas; + this.blobBaseFee = blobBaseFee.map(UnsignedLongParameter::getValue); + this.stateRoot = stateRoot; + this.difficulty = difficulty; + this.extraData = extraData; + this.mixHashOrPrevRandao = mixHashOrPrevRandao; + } + + /** + * Constructs a new BlockOverrides instance from a Builder. + * + * @param builder the builder to construct from + */ + private BlockOverrides(final Builder builder) { + this.blockNumber = Optional.ofNullable(builder.blockNumber); + this.blockHash = Optional.ofNullable(builder.blockHash); + this.prevRandao = Optional.ofNullable(builder.prevRandao); + this.timestamp = Optional.ofNullable(builder.timestamp); + this.gasLimit = Optional.ofNullable(builder.gasLimit); + this.feeRecipient = Optional.ofNullable(builder.feeRecipient); + this.baseFeePerGas = Optional.ofNullable(builder.baseFeePerGas); + this.blobBaseFee = Optional.ofNullable(builder.blobBaseFee); + this.stateRoot = Optional.ofNullable(builder.stateRoot); + this.difficulty = Optional.ofNullable(builder.difficulty); + this.extraData = Optional.ofNullable(builder.extraData); + this.mixHashOrPrevRandao = Optional.ofNullable(builder.mixHashOrPrevRandao); + } + + /** + * Gets the block number. + * + * @return the optional block number + */ + public Optional getBlockNumber() { + return blockNumber; + } + + /** + * Gets the block hash. + * + * @return the optional block hash + */ + public Optional getBlockHash() { + return blockHash; + } + + /** + * Gets the previous Randao. + * + * @return the optional previous Randao + */ + public Optional getPrevRandao() { + return prevRandao; + } + + /** + * Gets the timestamp. + * + * @return the optional timestamp + */ + public Optional getTimestamp() { + return timestamp; + } + + /** + * Gets the gas limit. + * + * @return the optional gas limit + */ + public Optional getGasLimit() { + return gasLimit; + } + + /** + * Gets the fee recipient. + * + * @return the optional fee recipient + */ + public Optional
getFeeRecipient() { + return feeRecipient; + } + + /** + * Gets the base fee per gas. + * + * @return the optional base fee per gas + */ + public Optional getBaseFeePerGas() { + return baseFeePerGas; + } + + /** + * Gets the blob base fee. + * + * @return the optional blob base fee + */ + public Optional getBlobBaseFee() { + return blobBaseFee; + } + + /** + * Gets the state root. + * + * @return the optional state root + */ + public Optional getStateRoot() { + return stateRoot; + } + + /** + * Gets the difficulty. + * + * @return the optional difficulty + */ + public Optional getDifficulty() { + return difficulty; + } + + /** + * Gets the extra data. + * + * @return the optional extra data + */ + public Optional getExtraData() { + return extraData; + } + + /** + * Gets the mix hash or previous Randao. + * + * @return the optional mix hash or previous Randao + */ + public Optional getMixHashOrPrevRandao() { + return mixHashOrPrevRandao; + } + + /** + * Creates a new Builder instance. + * + * @return a new Builder + */ + public static Builder builder() { + return new Builder(); + } + + /** Builder for BlockOverrides. */ + public static class Builder { + private Long timestamp; + private Long blockNumber; + private Hash blockHash; + private Bytes32 prevRandao; + private Long gasLimit; + private Address feeRecipient; + private Wei baseFeePerGas; + private Long blobBaseFee; + private Hash stateRoot; + private BigInteger difficulty; + private Bytes extraData; + private Hash mixHashOrPrevRandao; + + /** Constructs a new Builder instance. */ + public Builder() {} + + /** + * Sets the timestamp. + * + * @param timestamp the timestamp to set + * @return the builder instance + */ + public Builder timestamp(final Long timestamp) { + this.timestamp = timestamp; + return this; + } + + /** + * Sets the block number. + * + * @param blockNumber the block number to set + * @return the builder instance + */ + public Builder blockNumber(final Long blockNumber) { + this.blockNumber = blockNumber; + return this; + } + + /** + * Sets the block hash. + * + * @param blockHash the block hash to set + * @return the builder instance + */ + public Builder blockHash(final Hash blockHash) { + this.blockHash = blockHash; + return this; + } + + /** + * Sets the previous Randao. + * + * @param prevRandao the previous Randao to set + * @return the builder instance + */ + public Builder prevRandao(final Bytes32 prevRandao) { + this.prevRandao = prevRandao; + return this; + } + + /** + * Sets the gas limit. + * + * @param gasLimit the gas limit to set + * @return the builder instance + */ + public Builder gasLimit(final Long gasLimit) { + this.gasLimit = gasLimit; + return this; + } + + /** + * Sets the fee recipient. + * + * @param feeRecipient the fee recipient to set + * @return the builder instance + */ + public Builder feeRecipient(final Address feeRecipient) { + this.feeRecipient = feeRecipient; + return this; + } + + /** + * Sets the base fee per gas. + * + * @param baseFeePerGas the base fee per gas to set + * @return the builder instance + */ + public Builder baseFeePerGas(final Wei baseFeePerGas) { + this.baseFeePerGas = baseFeePerGas; + return this; + } + + /** + * Sets the blob base fee. + * + * @param blobBaseFee the blob base fee to set + * @return the builder instance + */ + public Builder blobBaseFee(final Long blobBaseFee) { + this.blobBaseFee = blobBaseFee; + return this; + } + + /** + * Sets the state root. + * + * @param stateRoot the state root to set + * @return the builder instance + */ + public Builder stateRoot(final Hash stateRoot) { + this.stateRoot = stateRoot; + return this; + } + + /** + * Sets the difficulty. + * + * @param difficulty the difficulty to set + * @return the builder instance + */ + public Builder difficulty(final BigInteger difficulty) { + this.difficulty = difficulty; + return this; + } + + /** + * Sets the extra data. + * + * @param extraData the extra data to set + * @return the builder instance + */ + public Builder extraData(final Bytes extraData) { + this.extraData = extraData; + return this; + } + + /** + * Sets the mix hash or previous Randao. + * + * @param mixHashOrPrevRandao the mix hash or previous Randao to set + * @return the builder instance + */ + public Builder mixHashOrPrevRandao(final Hash mixHashOrPrevRandao) { + this.mixHashOrPrevRandao = mixHashOrPrevRandao; + return this; + } + + /** + * Builds a new BlockOverrides instance. + * + * @return the new BlockOverrides instance + */ + public BlockOverrides build() { + return new BlockOverrides(this); + } + } +} diff --git a/plugin-api/src/main/java/org/hyperledger/besu/plugin/data/PluginBlockSimulationResult.java b/plugin-api/src/main/java/org/hyperledger/besu/plugin/data/PluginBlockSimulationResult.java new file mode 100644 index 00000000000..b2b2ab0e7be --- /dev/null +++ b/plugin-api/src/main/java/org/hyperledger/besu/plugin/data/PluginBlockSimulationResult.java @@ -0,0 +1,80 @@ +/* + * 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.plugin.data; + +import java.util.List; + +/** This class represents the result of simulating the processing of a block. */ +public class PluginBlockSimulationResult { + final BlockHeader blockHeader; + final BlockBody blockBody; + final List receipts; + final List transactionSimulationResults; + + /** + * Constructs a new BlockSimulationResult instance. + * + * @param blockHeader the block header + * @param blockBody the block body + * @param receipts the list of transaction receipts + * @param transactionSimulationResults the list of transaction simulation results + */ + public PluginBlockSimulationResult( + final BlockHeader blockHeader, + final BlockBody blockBody, + final List receipts, + final List transactionSimulationResults) { + this.blockHeader = blockHeader; + this.blockBody = blockBody; + this.receipts = receipts; + this.transactionSimulationResults = transactionSimulationResults; + } + + /** + * Gets the block header. + * + * @return the block header + */ + public BlockHeader getBlockHeader() { + return blockHeader; + } + + /** + * Gets the block body. + * + * @return the block body + */ + public BlockBody getBlockBody() { + return blockBody; + } + + /** + * Gets the list of transaction receipts. + * + * @return the list of transaction receipts + */ + public List getReceipts() { + return receipts; + } + + /** + * Gets the list of transaction simulation results. + * + * @return the list of transaction simulation results + */ + public List getTransactionSimulationResults() { + return transactionSimulationResults; + } +} diff --git a/plugin-api/src/main/java/org/hyperledger/besu/plugin/services/BlockSimulationService.java b/plugin-api/src/main/java/org/hyperledger/besu/plugin/services/BlockSimulationService.java new file mode 100644 index 00000000000..f0253186daf --- /dev/null +++ b/plugin-api/src/main/java/org/hyperledger/besu/plugin/services/BlockSimulationService.java @@ -0,0 +1,59 @@ +/* + * 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.plugin.services; + +import org.hyperledger.besu.datatypes.AccountOverrideMap; +import org.hyperledger.besu.datatypes.Transaction; +import org.hyperledger.besu.plugin.Unstable; +import org.hyperledger.besu.plugin.data.BlockOverrides; +import org.hyperledger.besu.plugin.data.PluginBlockSimulationResult; + +import java.util.List; + +/** This class is a service that simulates the processing of a block */ +public interface BlockSimulationService extends BesuService { + + /** + * Simulate the processing of a block given a header, a list of transactions, and blockOverrides. + * + * @param blockNumber the block number + * @param transactions the transactions to include in the block + * @param blockOverrides the blockSimulationOverride of the block + * @param accountOverrides state overrides of the block + * @return the block context + */ + PluginBlockSimulationResult simulate( + long blockNumber, + List transactions, + BlockOverrides blockOverrides, + AccountOverrideMap accountOverrides); + + /** + * This method is experimental and should be used with caution. Simulate the processing of a block + * given a header, a list of transactions, and blockOverrides and persist the WorldState + * + * @param blockNumber the block number + * @param transactions the transactions to include in the block + * @param blockOverrides block overrides for the block + * @param accountOverrides state overrides of the block + * @return the PluginBlockSimulationResult + */ + @Unstable + PluginBlockSimulationResult simulateAndPersistWorldState( + long blockNumber, + List transactions, + BlockOverrides blockOverrides, + AccountOverrideMap accountOverrides); +} diff --git a/plugin-api/src/main/java/org/hyperledger/besu/plugin/services/BlockchainService.java b/plugin-api/src/main/java/org/hyperledger/besu/plugin/services/BlockchainService.java index a89d1144af7..12d21d789b3 100644 --- a/plugin-api/src/main/java/org/hyperledger/besu/plugin/services/BlockchainService.java +++ b/plugin-api/src/main/java/org/hyperledger/besu/plugin/services/BlockchainService.java @@ -59,7 +59,8 @@ public interface BlockchainService extends BesuService { * @param blockBody the block body * @param receipts the transaction receipts */ - void storeBlock(BlockHeader blockHeader, BlockBody blockBody, List receipts); + void storeBlock( + BlockHeader blockHeader, BlockBody blockBody, List receipts); /** * Get the block header of the chain head