diff --git a/src/Nethermind/Ethereum.Test.Base/BlockchainTestBase.cs b/src/Nethermind/Ethereum.Test.Base/BlockchainTestBase.cs index 55dd7d7d3e6..8e3e3a147db 100644 --- a/src/Nethermind/Ethereum.Test.Base/BlockchainTestBase.cs +++ b/src/Nethermind/Ethereum.Test.Base/BlockchainTestBase.cs @@ -127,7 +127,7 @@ protected async Task RunTest(BlockchainTest test, Stopwatch? IEthereumEcdsa ecdsa = new EthereumEcdsa(specProvider.ChainId, _logManager); TrieStore trieStore = new(stateDb, _logManager); - IStateProvider stateProvider = new StateProvider(trieStore, codeDb, _logManager); + IWorldState stateProvider = new WorldState(trieStore, codeDb, _logManager); MemDb blockInfoDb = new MemDb(); IBlockTree blockTree = new BlockTree(new MemDb(), new MemDb(), blockInfoDb, new ChainLevelInfoRepository(blockInfoDb), specProvider, NullBloomStorage.Instance, _logManager); ITransactionComparerProvider transactionComparerProvider = new TransactionComparerProvider(specProvider, blockTree); @@ -141,7 +141,6 @@ protected async Task RunTest(BlockchainTest test, Stopwatch? IHeaderValidator headerValidator = new HeaderValidator(blockTree, Sealer, specProvider, _logManager); IUnclesValidator unclesValidator = new UnclesValidator(blockTree, headerValidator, _logManager); IBlockValidator blockValidator = new BlockValidator(txValidator, headerValidator, unclesValidator, specProvider, _logManager); - IStorageProvider storageProvider = new StorageProvider(trieStore, stateProvider, _logManager); IVirtualMachine virtualMachine = new VirtualMachine( blockhashProvider, specProvider, @@ -155,12 +154,10 @@ protected async Task RunTest(BlockchainTest test, Stopwatch? new TransactionProcessor( specProvider, stateProvider, - storageProvider, virtualMachine, _logManager), stateProvider), stateProvider, - storageProvider, receiptStorage, NullWitnessCollector.Instance, _logManager); @@ -173,7 +170,7 @@ protected async Task RunTest(BlockchainTest test, Stopwatch? _logManager, BlockchainProcessor.Options.NoReceipts); - InitializeTestState(test, stateProvider, storageProvider, specProvider); + InitializeTestState(test, stateProvider, specProvider); stopwatch?.Start(); List<(Block Block, string ExpectedException)> correctRlp = DecodeRlps(test, failOnInvalidRlp); @@ -239,7 +236,7 @@ protected async Task RunTest(BlockchainTest test, Stopwatch? await blockchainProcessor.StopAsync(true); stopwatch?.Stop(); - List differences = RunAssertions(test, blockTree.RetrieveHeadBlock(), storageProvider, stateProvider); + List differences = RunAssertions(test, blockTree.RetrieveHeadBlock(), stateProvider); Assert.Zero(differences.Count, "differences"); @@ -309,36 +306,32 @@ protected async Task RunTest(BlockchainTest test, Stopwatch? return correctRlp; } - private void InitializeTestState(BlockchainTest test, IStateProvider stateProvider, IStorageProvider storageProvider, ISpecProvider specProvider) + private void InitializeTestState(BlockchainTest test, IWorldState stateProvider, ISpecProvider specProvider) { foreach (KeyValuePair accountState in ((IEnumerable>)test.Pre ?? Array.Empty>())) { foreach (KeyValuePair storageItem in accountState.Value.Storage) { - storageProvider.Set(new StorageCell(accountState.Key, storageItem.Key), storageItem.Value); + stateProvider.Set(new StorageCell(accountState.Key, storageItem.Key), storageItem.Value); } stateProvider.CreateAccount(accountState.Key, accountState.Value.Balance); - Keccak codeHash = stateProvider.UpdateCode(accountState.Value.Code); - stateProvider.UpdateCodeHash(accountState.Key, codeHash, specProvider.GenesisSpec); + stateProvider.InsertCode(accountState.Key, accountState.Value.Code, specProvider.GenesisSpec); for (int i = 0; i < accountState.Value.Nonce; i++) { stateProvider.IncrementNonce(accountState.Key); } } - storageProvider.Commit(); stateProvider.Commit(specProvider.GenesisSpec); - storageProvider.CommitTrees(0); stateProvider.CommitTree(0); - storageProvider.Reset(); stateProvider.Reset(); } - private List RunAssertions(BlockchainTest test, Block headBlock, IStorageProvider storageProvider, IStateProvider stateProvider) + private List RunAssertions(BlockchainTest test, Block headBlock, IWorldState stateProvider) { if (test.PostStateRoot != null) { @@ -407,7 +400,7 @@ private List RunAssertions(BlockchainTest test, Block headBlock, IStorag foreach (KeyValuePair clearedStorage in clearedStorages) { - byte[] value = !stateProvider.AccountExists(acountAddress) ? Bytes.Empty : storageProvider.Get(new StorageCell(acountAddress, clearedStorage.Key)); + byte[] value = !stateProvider.AccountExists(acountAddress) ? Bytes.Empty : stateProvider.Get(new StorageCell(acountAddress, clearedStorage.Key)); if (!value.IsZero()) { differences.Add($"{acountAddress} storage[{clearedStorage.Key}] exp: 0x00, actual: {value.ToHexString(true)}"); @@ -416,7 +409,7 @@ private List RunAssertions(BlockchainTest test, Block headBlock, IStorag foreach (KeyValuePair storageItem in accountState.Storage) { - byte[] value = !stateProvider.AccountExists(acountAddress) ? Bytes.Empty : storageProvider.Get(new StorageCell(acountAddress, storageItem.Key)) ?? new byte[0]; + byte[] value = !stateProvider.AccountExists(acountAddress) ? Bytes.Empty : stateProvider.Get(new StorageCell(acountAddress, storageItem.Key)) ?? new byte[0]; if (!Bytes.AreEqual(storageItem.Value, value)) { differences.Add($"{acountAddress} storage[{storageItem.Key}] exp: {storageItem.Value.ToHexString(true)}, actual: {value.ToHexString(true)}"); diff --git a/src/Nethermind/Ethereum.Test.Base/GeneralTestBase.cs b/src/Nethermind/Ethereum.Test.Base/GeneralTestBase.cs index 136cb88338b..fc6382a4137 100644 --- a/src/Nethermind/Ethereum.Test.Base/GeneralTestBase.cs +++ b/src/Nethermind/Ethereum.Test.Base/GeneralTestBase.cs @@ -65,9 +65,8 @@ protected EthereumTestResult RunTest(GeneralStateTest test, ITxTracer txTracer) } TrieStore trieStore = new(stateDb, _logManager); - StateProvider stateProvider = new(trieStore, codeDb, _logManager); + WorldState stateProvider = new(trieStore, codeDb, _logManager); IBlockhashProvider blockhashProvider = new TestBlockhashProvider(); - IStorageProvider storageProvider = new StorageProvider(trieStore, stateProvider, _logManager); IVirtualMachine virtualMachine = new VirtualMachine( blockhashProvider, specProvider, @@ -76,11 +75,10 @@ protected EthereumTestResult RunTest(GeneralStateTest test, ITxTracer txTracer) TransactionProcessor transactionProcessor = new( specProvider, stateProvider, - storageProvider, virtualMachine, _logManager); - InitializeTestState(test, stateProvider, storageProvider, specProvider); + InitializeTestState(test, stateProvider, specProvider); BlockHeader header = new(test.PreviousHash, Keccak.OfAnEmptySequenceRlp, test.CurrentCoinbase, test.CurrentDifficulty, test.CurrentNumber, test.CurrentGasLimit, test.CurrentTimestamp, Array.Empty()); @@ -121,34 +119,27 @@ protected EthereumTestResult RunTest(GeneralStateTest test, ITxTracer txTracer) return testResult; } - private static void InitializeTestState(GeneralStateTest test, StateProvider stateProvider, - IStorageProvider storageProvider, ISpecProvider specProvider) + private static void InitializeTestState(GeneralStateTest test, WorldState stateProvider, ISpecProvider specProvider) { foreach (KeyValuePair accountState in test.Pre) { foreach (KeyValuePair storageItem in accountState.Value.Storage) { - storageProvider.Set(new StorageCell(accountState.Key, storageItem.Key), + stateProvider.Set(new StorageCell(accountState.Key, storageItem.Key), storageItem.Value.WithoutLeadingZeros().ToArray()); } stateProvider.CreateAccount(accountState.Key, accountState.Value.Balance); - Keccak codeHash = stateProvider.UpdateCode(accountState.Value.Code); - stateProvider.UpdateCodeHash(accountState.Key, codeHash, specProvider.GenesisSpec); + stateProvider.InsertCode(accountState.Key, accountState.Value.Code, specProvider.GenesisSpec); stateProvider.SetNonce(accountState.Key, accountState.Value.Nonce); } - storageProvider.Commit(); stateProvider.Commit(specProvider.GenesisSpec); - - storageProvider.CommitTrees(0); stateProvider.CommitTree(0); - - storageProvider.Reset(); stateProvider.Reset(); } - private List RunAssertions(GeneralStateTest test, IStateProvider stateProvider) + private List RunAssertions(GeneralStateTest test, IWorldState stateProvider) { List differences = new(); if (test.PostHash != stateProvider.StateRoot) diff --git a/src/Nethermind/Nethermind.AccountAbstraction.Test/AccountAbstractionPeerManagerTests.cs b/src/Nethermind/Nethermind.AccountAbstraction.Test/AccountAbstractionPeerManagerTests.cs index 98063c8e368..361e787a6a0 100644 --- a/src/Nethermind/Nethermind.AccountAbstraction.Test/AccountAbstractionPeerManagerTests.cs +++ b/src/Nethermind/Nethermind.AccountAbstraction.Test/AccountAbstractionPeerManagerTests.cs @@ -41,7 +41,7 @@ public class AccountAbstractionPeerManagerTests private IBlockTree _blockTree = Substitute.For(); private ILogger _logger = Substitute.For(); private ILogFinder _logFinder = Substitute.For(); - private IStateProvider _stateProvider = Substitute.For(); + private IWorldState _stateProvider = Substitute.For(); private ISpecProvider _specProvider = Substitute.For(); private readonly ISigner _signer = Substitute.For(); private readonly string[] _entryPointContractAddress = { "0x8595dd9e0438640b5e1254f9df579ac12a86865f", "0x96cc609c8f5458fb8a7da4d94b678e38ebf3d04e" }; diff --git a/src/Nethermind/Nethermind.AccountAbstraction.Test/AccountAbstractionRpcModuleTests.TestAccountAbstractionRpcBlockchain.cs b/src/Nethermind/Nethermind.AccountAbstraction.Test/AccountAbstractionRpcModuleTests.TestAccountAbstractionRpcBlockchain.cs index 42a86240801..44f0aef692c 100644 --- a/src/Nethermind/Nethermind.AccountAbstraction.Test/AccountAbstractionRpcModuleTests.TestAccountAbstractionRpcBlockchain.cs +++ b/src/Nethermind/Nethermind.AccountAbstraction.Test/AccountAbstractionRpcModuleTests.TestAccountAbstractionRpcBlockchain.cs @@ -190,7 +190,6 @@ protected override BlockProcessor CreateBlockProcessor() NoBlockRewards.Instance, new BlockProcessor.BlockValidationTransactionsExecutor(TxProcessor, State), State, - Storage, ReceiptStorage, NullWitnessCollector.Instance, LogManager); diff --git a/src/Nethermind/Nethermind.AccountAbstraction.Test/AccountAbstractionRpcModuleTests.cs b/src/Nethermind/Nethermind.AccountAbstraction.Test/AccountAbstractionRpcModuleTests.cs index ea515474e1c..87d3569ef23 100644 --- a/src/Nethermind/Nethermind.AccountAbstraction.Test/AccountAbstractionRpcModuleTests.cs +++ b/src/Nethermind/Nethermind.AccountAbstraction.Test/AccountAbstractionRpcModuleTests.cs @@ -226,8 +226,7 @@ public async Task Should_execute_well_formed_op_successfully_if_codehash_not_cha chain.SendUserOperation(entryPointAddress[0], op); if (changeCodeHash) { - Keccak codeHash = chain.State.UpdateCode(Bytes.Concat(chain.State.GetCode(walletAddress[0]!), 0x00)); - chain.State.UpdateCodeHash(walletAddress[0]!, codeHash, chain.SpecProvider.GenesisSpec); + chain.State.InsertCode(walletAddress[0]!, Bytes.Concat(chain.State.GetCode(walletAddress[0]!), 0x00), chain.SpecProvider.GenesisSpec); chain.State.Commit(chain.SpecProvider.GenesisSpec); chain.State.RecalculateStateRoot(); chain.State.CommitTree(chain.BlockTree.Head!.Number); diff --git a/src/Nethermind/Nethermind.AccountAbstraction.Test/UserOperationPoolTests.cs b/src/Nethermind/Nethermind.AccountAbstraction.Test/UserOperationPoolTests.cs index f52bb018a9d..b6bae30af9f 100644 --- a/src/Nethermind/Nethermind.AccountAbstraction.Test/UserOperationPoolTests.cs +++ b/src/Nethermind/Nethermind.AccountAbstraction.Test/UserOperationPoolTests.cs @@ -44,7 +44,7 @@ public class UserOperationPoolTests private IBlockTree _blockTree = Substitute.For(); private IReceiptFinder _receiptFinder = Substitute.For(); private ILogFinder _logFinder = Substitute.For(); - private IStateProvider _stateProvider = Substitute.For(); + private IWorldState _stateProvider = Substitute.For(); private ISpecProvider _specProvider = Substitute.For(); private readonly ISigner _signer = Substitute.For(); private readonly Keccak _userOperationEventTopic = new("0x33fd4d1f25a5461bea901784a6571de6debc16cd0831932c22c6969cd73ba994"); diff --git a/src/Nethermind/Nethermind.AccountAbstraction.Test/UserOperationTracerTests.cs b/src/Nethermind/Nethermind.AccountAbstraction.Test/UserOperationTracerTests.cs index 414893e933a..7e3288e2060 100644 --- a/src/Nethermind/Nethermind.AccountAbstraction.Test/UserOperationTracerTests.cs +++ b/src/Nethermind/Nethermind.AccountAbstraction.Test/UserOperationTracerTests.cs @@ -46,8 +46,7 @@ public void Should_fail_if_banned_opcode_is_used_when_call_depth_is_more_than_on .Done; TestState.CreateAccount(TestItem.AddressC, 1.Ether()); - Keccak deployedCodeHash = TestState.UpdateCode(deployedCode); - TestState.UpdateCodeHash(TestItem.AddressC, deployedCodeHash, Spec); + TestState.InsertCode(TestItem.AddressC, deployedCode, Spec); byte[] code = Prepare.EvmCode .Call(TestItem.AddressC, 50000) @@ -95,16 +94,14 @@ public void Should_allow_external_storage_access_only_with_whitelisted_paymaster .Done; TestState.CreateAccount(externalContractAddress, 1.Ether()); - Keccak externalContractDeployedCodeHash = TestState.UpdateCode(externalContractCalledByPaymasterCode); - TestState.UpdateCodeHash(externalContractAddress, externalContractDeployedCodeHash, Spec); + TestState.InsertCode(externalContractAddress, externalContractCalledByPaymasterCode, Spec); byte[] paymasterCode = Prepare.EvmCode .Call(externalContractAddress, 70000) .Done; TestState.CreateAccount(paymasterContractAddress, 1.Ether()); - Keccak paymasterDeployedCodeHash = TestState.UpdateCode(paymasterCode); - TestState.UpdateCodeHash(paymasterContractAddress, paymasterDeployedCodeHash, Spec); + TestState.InsertCode(paymasterContractAddress, paymasterCode, Spec); byte[] code = Prepare.EvmCode .Op(paymasterValidation ? Instruction.NUMBER : Instruction.BASEFEE) // switch to paymaster validation with NUMBER @@ -137,16 +134,14 @@ public void Should_make_sure_external_contract_extcodehashes_stays_same_after_si .Done; TestState.CreateAccount(externalContractAddress, 1.Ether()); - Keccak externalContractDeployedCodeHash = TestState.UpdateCode(externalContractCalledByPaymasterCode); - TestState.UpdateCodeHash(externalContractAddress, externalContractDeployedCodeHash, Spec); + TestState.InsertCode(externalContractAddress, externalContractCalledByPaymasterCode, Spec); byte[] paymasterCode = Prepare.EvmCode .Call(externalContractAddress, 70000) .Done; TestState.CreateAccount(paymasterContractAddress, 1.Ether()); - Keccak paymasterDeployedCodeHash = TestState.UpdateCode(paymasterCode); - TestState.UpdateCodeHash(paymasterContractAddress, paymasterDeployedCodeHash, Spec); + TestState.InsertCode(paymasterContractAddress, paymasterCode, Spec); byte[] code = Prepare.EvmCode .Op(paymasterValidation ? Instruction.NUMBER : Instruction.BASEFEE) // switch to paymaster validation with NUMBER @@ -181,8 +176,7 @@ public void Should_not_allow_inner_call_to_run_out_of_gas(long gasLimit, bool sh .Done; TestState.CreateAccount(externalContractAddress, 1.Ether()); - Keccak externalContractDeployedCodeHash = TestState.UpdateCode(externalContractCalledByPaymasterCode); - TestState.UpdateCodeHash(externalContractAddress, externalContractDeployedCodeHash, Spec); + TestState.InsertCode(externalContractAddress, externalContractCalledByPaymasterCode, Spec); byte[] paymasterCode = Prepare.EvmCode .Call(externalContractAddress, gasLimit) @@ -194,8 +188,7 @@ public void Should_not_allow_inner_call_to_run_out_of_gas(long gasLimit, bool sh .Done; TestState.CreateAccount(paymasterContractAddress, 1.Ether()); - Keccak paymasterDeployedCodeHash = TestState.UpdateCode(paymasterCode); - TestState.UpdateCodeHash(paymasterContractAddress, paymasterDeployedCodeHash, Spec); + TestState.InsertCode(paymasterContractAddress, paymasterCode, Spec); byte[] code = Prepare.EvmCode .Call(paymasterContractAddress, 100000) @@ -232,8 +225,7 @@ public void Should_allow_gas_only_if_followed_by_call(Instruction instruction, b .Done; TestState.CreateAccount(TestItem.AddressC, 1.Ether()); - Keccak deployedCodeHash = TestState.UpdateCode(deployedCode); - TestState.UpdateCodeHash(TestItem.AddressC, deployedCodeHash, Spec); + TestState.InsertCode(TestItem.AddressC, deployedCode, Spec); byte[] code = Prepare.EvmCode .Call(TestItem.AddressC, 70000) diff --git a/src/Nethermind/Nethermind.AccountAbstraction/Executor/AABlockProducerTransactionsExecutor.cs b/src/Nethermind/Nethermind.AccountAbstraction/Executor/AABlockProducerTransactionsExecutor.cs index 49100458ebd..a9bdcb0f1c0 100644 --- a/src/Nethermind/Nethermind.AccountAbstraction/Executor/AABlockProducerTransactionsExecutor.cs +++ b/src/Nethermind/Nethermind.AccountAbstraction/Executor/AABlockProducerTransactionsExecutor.cs @@ -18,15 +18,13 @@ namespace Nethermind.AccountAbstraction.Executor { public class AABlockProducerTransactionsExecutor : BlockProcessor.BlockProductionTransactionsExecutor { - private readonly IStateProvider _stateProvider; - private readonly IStorageProvider _storageProvider; + private readonly IWorldState _stateProvider; private readonly ISigner _signer; private readonly Address[] _entryPointAddresses; public AABlockProducerTransactionsExecutor( ITransactionProcessor transactionProcessor, - IStateProvider stateProvider, - IStorageProvider storageProvider, + IWorldState stateProvider, ISpecProvider specProvider, ILogManager logManager, ISigner signer, @@ -34,12 +32,10 @@ public AABlockProducerTransactionsExecutor( : base( transactionProcessor, stateProvider, - storageProvider, specProvider, logManager) { _stateProvider = stateProvider; - _storageProvider = storageProvider; _signer = signer; _entryPointAddresses = entryPointAddresses; } @@ -69,7 +65,6 @@ public override TxReceipt[] ProcessTransactions( } _stateProvider.Commit(spec, receiptsTracer); - _storageProvider.Commit(receiptsTracer); SetTransactions(block, transactionsInBlock); return receiptsTracer.TxReceipts.ToArray(); diff --git a/src/Nethermind/Nethermind.AccountAbstraction/Executor/AABlockProducerTransactionsExecutorFactory.cs b/src/Nethermind/Nethermind.AccountAbstraction/Executor/AABlockProducerTransactionsExecutorFactory.cs index 8cd954daffb..8dd11b9d59c 100644 --- a/src/Nethermind/Nethermind.AccountAbstraction/Executor/AABlockProducerTransactionsExecutorFactory.cs +++ b/src/Nethermind/Nethermind.AccountAbstraction/Executor/AABlockProducerTransactionsExecutorFactory.cs @@ -29,7 +29,6 @@ public IBlockProcessor.IBlockTransactionsExecutor Create(ReadOnlyTxProcessingEnv => new AABlockProducerTransactionsExecutor( readOnlyTxProcessingEnv.TransactionProcessor, readOnlyTxProcessingEnv.StateProvider, - readOnlyTxProcessingEnv.StorageProvider, _specProvider, _logManager, _signer, diff --git a/src/Nethermind/Nethermind.Api/IApiWithBlockchain.cs b/src/Nethermind/Nethermind.Api/IApiWithBlockchain.cs index ce5fef1528e..10612330c41 100644 --- a/src/Nethermind/Nethermind.Api/IApiWithBlockchain.cs +++ b/src/Nethermind/Nethermind.Api/IApiWithBlockchain.cs @@ -58,11 +58,10 @@ public interface IApiWithBlockchain : IApiWithStores, IBlockchainBridgeFactory /// /// DO NOT USE OUTSIDE OF PROCESSING BLOCK CONTEXT! /// - IStateProvider? StateProvider { get; set; } + IWorldState? WorldState { get; set; } IKeyValueStoreWithBatching? MainStateDbWithCache { get; set; } IReadOnlyStateProvider? ChainHeadStateProvider { get; set; } IStateReader? StateReader { get; set; } - IStorageProvider? StorageProvider { get; set; } ITransactionProcessor? TransactionProcessor { get; set; } ITrieStore? TrieStore { get; set; } ITxSender? TxSender { get; set; } diff --git a/src/Nethermind/Nethermind.Api/NethermindApi.cs b/src/Nethermind/Nethermind.Api/NethermindApi.cs index 938b1ff96cd..fe323844e39 100644 --- a/src/Nethermind/Nethermind.Api/NethermindApi.cs +++ b/src/Nethermind/Nethermind.Api/NethermindApi.cs @@ -189,10 +189,9 @@ public ISealEngine SealEngine public IPeerDifficultyRefreshPool? PeerDifficultyRefreshPool { get; set; } public ISynchronizer? Synchronizer { get; set; } public ISyncServer? SyncServer { get; set; } - public IStateProvider? StateProvider { get; set; } + public IWorldState? WorldState { get; set; } public IReadOnlyStateProvider? ChainHeadStateProvider { get; set; } public IStateReader? StateReader { get; set; } - public IStorageProvider? StorageProvider { get; set; } public IStaticNodesManager? StaticNodesManager { get; set; } public ITimestamper Timestamper { get; } = Core.Timestamper.Default; public ITimerFactory TimerFactory { get; } = Core.Timers.TimerFactory.Default; diff --git a/src/Nethermind/Nethermind.AuRa.Test/AuRaAdditionalBlockProcessorFactoryTests.cs b/src/Nethermind/Nethermind.AuRa.Test/AuRaAdditionalBlockProcessorFactoryTests.cs index 48b2342a9b5..8d4fcfd3768 100644 --- a/src/Nethermind/Nethermind.AuRa.Test/AuRaAdditionalBlockProcessorFactoryTests.cs +++ b/src/Nethermind/Nethermind.AuRa.Test/AuRaAdditionalBlockProcessorFactoryTests.cs @@ -34,7 +34,7 @@ public class AuRaAdditionalBlockProcessorFactoryTests public void returns_correct_validator_type(AuRaParameters.ValidatorType validatorType, Type expectedType) { AuRaValidatorFactory factory = new(Substitute.For(), - Substitute.For(), + Substitute.For(), Substitute.For(), Substitute.For(), Substitute.For(), diff --git a/src/Nethermind/Nethermind.AuRa.Test/AuRaBlockProducerTests.cs b/src/Nethermind/Nethermind.AuRa.Test/AuRaBlockProducerTests.cs index 639337c13b4..5a4be9c4946 100644 --- a/src/Nethermind/Nethermind.AuRa.Test/AuRaBlockProducerTests.cs +++ b/src/Nethermind/Nethermind.AuRa.Test/AuRaBlockProducerTests.cs @@ -43,7 +43,7 @@ private class Context public ISealer Sealer { get; } public IBlockTree BlockTree { get; } public IBlockProcessingQueue BlockProcessingQueue { get; } - public IStateProvider StateProvider { get; } + public IWorldState StateProvider { get; } public ITimestamper Timestamper { get; } public IAuRaStepCalculator AuRaStepCalculator { get; } public Address NodeAddress { get; } @@ -58,7 +58,7 @@ public Context() Sealer = Substitute.For(); BlockTree = Substitute.For(); BlockProcessingQueue = Substitute.For(); - StateProvider = Substitute.For(); + StateProvider = Substitute.For(); Timestamper = Substitute.For(); AuRaStepCalculator = Substitute.For(); NodeAddress = TestItem.AddressA; diff --git a/src/Nethermind/Nethermind.AuRa.Test/AuraBlockProcessorTests.cs b/src/Nethermind/Nethermind.AuRa.Test/AuraBlockProcessorTests.cs index 0f26649a0b9..60033b7820c 100644 --- a/src/Nethermind/Nethermind.AuRa.Test/AuraBlockProcessorTests.cs +++ b/src/Nethermind/Nethermind.AuRa.Test/AuraBlockProcessorTests.cs @@ -122,7 +122,7 @@ void Process(AuRaBlockProcessor auRaBlockProcessor, int blockNumber, Keccak stat }, }; - (AuRaBlockProcessor processor, IStateProvider stateProvider) = + (AuRaBlockProcessor processor, IWorldState stateProvider) = CreateProcessor(contractRewriter: new ContractRewriter(contractOverrides)); stateProvider.CreateAccount(TestItem.AddressA, UInt256.One); @@ -144,12 +144,12 @@ void Process(AuRaBlockProcessor auRaBlockProcessor, int blockNumber, Keccak stat stateProvider.GetCode(TestItem.AddressB).Should().BeEquivalentTo(Bytes.FromHexString("0x654")); } - private (AuRaBlockProcessor Processor, IStateProvider StateProvider) CreateProcessor(ITxFilter? txFilter = null, ContractRewriter? contractRewriter = null) + private (AuRaBlockProcessor Processor, IWorldState StateProvider) CreateProcessor(ITxFilter? txFilter = null, ContractRewriter? contractRewriter = null) { IDb stateDb = new MemDb(); IDb codeDb = new MemDb(); TrieStore trieStore = new(stateDb, LimboLogs.Instance); - IStateProvider stateProvider = new StateProvider(trieStore, codeDb, LimboLogs.Instance); + IWorldState stateProvider = new WorldState(trieStore, codeDb, LimboLogs.Instance); ITransactionProcessor transactionProcessor = Substitute.For(); AuRaBlockProcessor processor = new AuRaBlockProcessor( RinkebySpecProvider.Instance, @@ -157,7 +157,6 @@ void Process(AuRaBlockProcessor auRaBlockProcessor, int blockNumber, Keccak stat NoBlockRewards.Instance, new BlockProcessor.BlockValidationTransactionsExecutor(transactionProcessor, stateProvider), stateProvider, - new StorageProvider(trieStore, stateProvider, LimboLogs.Instance), NullReceiptStorage.Instance, LimboLogs.Instance, Substitute.For(), diff --git a/src/Nethermind/Nethermind.AuRa.Test/Contract/AuRaContractGasLimitOverrideTests.cs b/src/Nethermind/Nethermind.AuRa.Test/Contract/AuRaContractGasLimitOverrideTests.cs index 4b8e7607d71..c5f1a04d732 100644 --- a/src/Nethermind/Nethermind.AuRa.Test/Contract/AuRaContractGasLimitOverrideTests.cs +++ b/src/Nethermind/Nethermind.AuRa.Test/Contract/AuRaContractGasLimitOverrideTests.cs @@ -96,7 +96,6 @@ protected override BlockProcessor CreateBlockProcessor() new RewardCalculator(SpecProvider), new BlockProcessor.BlockValidationTransactionsExecutor(TxProcessor, State), State, - Storage, ReceiptStorage, LimboLogs.Instance, BlockTree, diff --git a/src/Nethermind/Nethermind.AuRa.Test/Contract/TestContractBlockchain.cs b/src/Nethermind/Nethermind.AuRa.Test/Contract/TestContractBlockchain.cs index c0881ba78d0..8da766372d6 100644 --- a/src/Nethermind/Nethermind.AuRa.Test/Contract/TestContractBlockchain.cs +++ b/src/Nethermind/Nethermind.AuRa.Test/Contract/TestContractBlockchain.cs @@ -45,7 +45,6 @@ protected override Block GetGenesisBlock() => ChainSpec, SpecProvider, State, - Storage, TxProcessor) .Load(); } diff --git a/src/Nethermind/Nethermind.AuRa.Test/Contract/ValidatorContractTests.cs b/src/Nethermind/Nethermind.AuRa.Test/Contract/ValidatorContractTests.cs index 1e6898597ea..9b287c3735f 100644 --- a/src/Nethermind/Nethermind.AuRa.Test/Contract/ValidatorContractTests.cs +++ b/src/Nethermind/Nethermind.AuRa.Test/Contract/ValidatorContractTests.cs @@ -27,7 +27,7 @@ public class ValidatorContractTests private readonly Address _contractAddress = Address.FromNumber(long.MaxValue); private IReadOnlyTransactionProcessor _transactionProcessor; private IReadOnlyTxProcessorSource _readOnlyTxProcessorSource; - private IStateProvider _stateProvider; + private IWorldState _stateProvider; [SetUp] public void SetUp() @@ -36,7 +36,7 @@ public void SetUp() _transactionProcessor = Substitute.For(); _readOnlyTxProcessorSource = Substitute.For(); _readOnlyTxProcessorSource.Build(TestItem.KeccakA).Returns(_transactionProcessor); - _stateProvider = Substitute.For(); + _stateProvider = Substitute.For(); _stateProvider.StateRoot.Returns(TestItem.KeccakA); } diff --git a/src/Nethermind/Nethermind.AuRa.Test/Transactions/TxCertifierFilterTests.cs b/src/Nethermind/Nethermind.AuRa.Test/Transactions/TxCertifierFilterTests.cs index d6a9e7c6268..887961a3c6d 100644 --- a/src/Nethermind/Nethermind.AuRa.Test/Transactions/TxCertifierFilterTests.cs +++ b/src/Nethermind/Nethermind.AuRa.Test/Transactions/TxCertifierFilterTests.cs @@ -153,7 +153,6 @@ protected override BlockProcessor CreateBlockProcessor() new RewardCalculator(SpecProvider), new BlockProcessor.BlockValidationTransactionsExecutor(TxProcessor, State), State, - Storage, ReceiptStorage, LimboLogs.Instance, BlockTree, diff --git a/src/Nethermind/Nethermind.AuRa.Test/Transactions/TxPermissionFilterTest.cs b/src/Nethermind/Nethermind.AuRa.Test/Transactions/TxPermissionFilterTest.cs index f3ee47bf15a..d6ba4a8ad7f 100644 --- a/src/Nethermind/Nethermind.AuRa.Test/Transactions/TxPermissionFilterTest.cs +++ b/src/Nethermind/Nethermind.AuRa.Test/Transactions/TxPermissionFilterTest.cs @@ -294,7 +294,6 @@ protected override BlockProcessor CreateBlockProcessor() new RewardCalculator(SpecProvider), new BlockProcessor.BlockValidationTransactionsExecutor(TxProcessor, State), State, - Storage, ReceiptStorage, LimboLogs.Instance, BlockTree, diff --git a/src/Nethermind/Nethermind.AuRa.Test/Validators/ContractBasedValidatorTests.cs b/src/Nethermind/Nethermind.AuRa.Test/Validators/ContractBasedValidatorTests.cs index 401370f1156..30d7123eeea 100644 --- a/src/Nethermind/Nethermind.AuRa.Test/Validators/ContractBasedValidatorTests.cs +++ b/src/Nethermind/Nethermind.AuRa.Test/Validators/ContractBasedValidatorTests.cs @@ -37,7 +37,7 @@ namespace Nethermind.AuRa.Test.Validators { public class ContractBasedValidatorTests { - private IStateProvider _stateProvider; + private IWorldState _stateProvider; private IAbiEncoder _abiEncoder; private ILogManager _logManager; private AuRaParameters.Validator _validator; @@ -61,7 +61,7 @@ public void SetUp() { _validatorStore = new ValidatorStore(new MemDb()); _validSealerStrategy = new ValidSealerStrategy(); - _stateProvider = Substitute.For(); + _stateProvider = Substitute.For(); _abiEncoder = Substitute.For(); _logManager = LimboLogs.Instance; _blockTree = Substitute.For(); diff --git a/src/Nethermind/Nethermind.AuRa.Test/Validators/ReportingContractBasedValidatorTests.cs b/src/Nethermind/Nethermind.AuRa.Test/Validators/ReportingContractBasedValidatorTests.cs index 03419992874..af37c7a7bbe 100644 --- a/src/Nethermind/Nethermind.AuRa.Test/Validators/ReportingContractBasedValidatorTests.cs +++ b/src/Nethermind/Nethermind.AuRa.Test/Validators/ReportingContractBasedValidatorTests.cs @@ -159,7 +159,7 @@ public void Report_ignores_duplicates_in_same_block() context.Validator.ReportMalicious(MaliciousMinerAddress, 100, Bytes.Empty, IReportingValidator.MaliciousCause.DuplicateStep); // ignored context.Validator.ReportMalicious(MaliciousMinerAddress, 100, Bytes.Empty, IReportingValidator.MaliciousCause.SiblingBlocksInSameStep); // ignored context.Validator.ReportMalicious(MaliciousMinerAddress, 100, Bytes.Empty, IReportingValidator.MaliciousCause.SiblingBlocksInSameStep); // ignored - context.Validator.ReportBenign(TestItem.AddressC, 100, IReportingValidator.BenignCause.FutureBlock); // sent + context.Validator.ReportBenign(TestItem.AddressC, 100, IReportingValidator.BenignCause.FutureBlock); // sent context.Validator.ReportBenign(TestItem.AddressC, 100, IReportingValidator.BenignCause.FutureBlock); // ignored context.Validator.ReportBenign(MaliciousMinerAddress, 101, IReportingValidator.BenignCause.FutureBlock); //sent context.Validator.ReportBenign(MaliciousMinerAddress, 101, IReportingValidator.BenignCause.IncorrectProposer); //ignored @@ -204,7 +204,7 @@ public TestContext(bool forSealing, ReportingContractBasedValidator.Cache cache TxSender = Substitute.For(); ITxPool txPool = Substitute.For(); - IStateProvider stateProvider = Substitute.For(); + IWorldState stateProvider = Substitute.For(); ISpecProvider specProvider = Substitute.For(); stateProvider.GetNonce(ReportingValidatorContract.NodeAddress).Returns(UInt256.One); diff --git a/src/Nethermind/Nethermind.Benchmark/State/StorageCellBenchmark.cs b/src/Nethermind/Nethermind.Benchmark/State/StorageCellBenchmark.cs index 1c87a3f768c..eb74cff4830 100644 --- a/src/Nethermind/Nethermind.Benchmark/State/StorageCellBenchmark.cs +++ b/src/Nethermind/Nethermind.Benchmark/State/StorageCellBenchmark.cs @@ -7,6 +7,7 @@ using Nethermind.Core; using Nethermind.Int256; using Nethermind.State; +using Nethermind.State.Tracing; namespace Nethermind.Benchmarks.State { diff --git a/src/Nethermind/Nethermind.Blockchain.Test/BlockProcessorTests.cs b/src/Nethermind/Nethermind.Blockchain.Test/BlockProcessorTests.cs index 019dff245b9..58c6fb51a53 100644 --- a/src/Nethermind/Nethermind.Blockchain.Test/BlockProcessorTests.cs +++ b/src/Nethermind/Nethermind.Blockchain.Test/BlockProcessorTests.cs @@ -41,7 +41,7 @@ public void Prepared_block_contains_author_field() IDb stateDb = new MemDb(); IDb codeDb = new MemDb(); TrieStore trieStore = new(stateDb, LimboLogs.Instance); - IStateProvider stateProvider = new StateProvider(trieStore, codeDb, LimboLogs.Instance); + IWorldState stateProvider = new WorldState(trieStore, codeDb, LimboLogs.Instance); ITransactionProcessor transactionProcessor = Substitute.For(); BlockProcessor processor = new( RinkebySpecProvider.Instance, @@ -49,7 +49,6 @@ public void Prepared_block_contains_author_field() NoBlockRewards.Instance, new BlockProcessor.BlockValidationTransactionsExecutor(transactionProcessor, stateProvider), stateProvider, - new StorageProvider(trieStore, stateProvider, LimboLogs.Instance), NullReceiptStorage.Instance, NullWitnessCollector.Instance, LimboLogs.Instance); @@ -72,7 +71,7 @@ public void Can_store_a_witness() IDb codeDb = new MemDb(); var trieStore = new TrieStore(stateDb, LimboLogs.Instance); - IStateProvider stateProvider = new StateProvider(trieStore, codeDb, LimboLogs.Instance); + IWorldState stateProvider = new WorldState(trieStore, codeDb, LimboLogs.Instance); ITransactionProcessor transactionProcessor = Substitute.For(); IWitnessCollector witnessCollector = Substitute.For(); BlockProcessor processor = new( @@ -81,7 +80,6 @@ public void Can_store_a_witness() NoBlockRewards.Instance, new BlockProcessor.BlockValidationTransactionsExecutor(transactionProcessor, stateProvider), stateProvider, - new StorageProvider(trieStore, stateProvider, LimboLogs.Instance), NullReceiptStorage.Instance, witnessCollector, LimboLogs.Instance); @@ -103,7 +101,7 @@ public void Recovers_state_on_cancel() IDb stateDb = new MemDb(); IDb codeDb = new MemDb(); TrieStore trieStore = new(stateDb, LimboLogs.Instance); - IStateProvider stateProvider = new StateProvider(trieStore, codeDb, LimboLogs.Instance); + IWorldState stateProvider = new WorldState(trieStore, codeDb, LimboLogs.Instance); ITransactionProcessor transactionProcessor = Substitute.For(); BlockProcessor processor = new( RinkebySpecProvider.Instance, @@ -111,7 +109,6 @@ public void Recovers_state_on_cancel() new RewardCalculator(MainnetSpecProvider.Instance), new BlockProcessor.BlockValidationTransactionsExecutor(transactionProcessor, stateProvider), stateProvider, - new StorageProvider(trieStore, stateProvider, LimboLogs.Instance), NullReceiptStorage.Instance, NullWitnessCollector.Instance, LimboLogs.Instance); diff --git a/src/Nethermind/Nethermind.Blockchain.Test/GenesisLoaderTests.cs b/src/Nethermind/Nethermind.Blockchain.Test/GenesisLoaderTests.cs index bad4a20a57a..ba0a26b1d87 100644 --- a/src/Nethermind/Nethermind.Blockchain.Test/GenesisLoaderTests.cs +++ b/src/Nethermind/Nethermind.Blockchain.Test/GenesisLoaderTests.cs @@ -60,14 +60,12 @@ private Block GetGenesisBlock(string chainspecPath) IDb stateDb = new MemDb(); IDb codeDb = new MemDb(); TrieStore trieStore = new(stateDb, LimboLogs.Instance); - IStateProvider stateProvider = new StateProvider(trieStore, codeDb, LimboLogs.Instance); + IWorldState stateProvider = new WorldState(trieStore, codeDb, LimboLogs.Instance); ISpecProvider specProvider = Substitute.For(); specProvider.GetSpec(Arg.Any()).Returns(Berlin.Instance); specProvider.GetSpec(Arg.Any()).Returns(Berlin.Instance); - StorageProvider storageProvider = new(trieStore, stateProvider, LimboLogs.Instance); ITransactionProcessor transactionProcessor = Substitute.For(); - GenesisLoader genesisLoader = new(chainSpec, specProvider, stateProvider, storageProvider, - transactionProcessor); + GenesisLoader genesisLoader = new(chainSpec, specProvider, stateProvider, transactionProcessor); return genesisLoader.Load(); } diff --git a/src/Nethermind/Nethermind.Blockchain.Test/Producers/BlockProducerBaseTests.IsProducingBlocks.cs b/src/Nethermind/Nethermind.Blockchain.Test/Producers/BlockProducerBaseTests.IsProducingBlocks.cs index e55d959af05..bf98d79c258 100644 --- a/src/Nethermind/Nethermind.Blockchain.Test/Producers/BlockProducerBaseTests.IsProducingBlocks.cs +++ b/src/Nethermind/Nethermind.Blockchain.Test/Producers/BlockProducerBaseTests.IsProducingBlocks.cs @@ -99,7 +99,7 @@ public async Task AuraTestBlockProducer_IsProducingBlocks_returns_expected_resul Substitute.For(), Substitute.For(), Substitute.For(), - Substitute.For(), + Substitute.For(), Substitute.For(), Substitute.For(), Substitute.For(), diff --git a/src/Nethermind/Nethermind.Blockchain.Test/Producers/BlockProducerBaseTests.cs b/src/Nethermind/Nethermind.Blockchain.Test/Producers/BlockProducerBaseTests.cs index 1c9fd74a71f..4a3f401c9a8 100644 --- a/src/Nethermind/Nethermind.Blockchain.Test/Producers/BlockProducerBaseTests.cs +++ b/src/Nethermind/Nethermind.Blockchain.Test/Producers/BlockProducerBaseTests.cs @@ -32,7 +32,7 @@ public ProducerUnderTest( ISealer sealer, IBlockTree blockTree, IBlockProductionTrigger blockProductionTrigger, - IStateProvider stateProvider, + IWorldState stateProvider, IGasLimitCalculator gasLimitCalculator, ITimestamper timestamper, ILogManager logManager, @@ -80,7 +80,7 @@ public void Time_passing_does_not_break_the_block() NullSealEngine.Instance, Build.A.BlockTree().TestObject, Substitute.For(), - Substitute.For(), + Substitute.For(), Substitute.For(), timestamper, LimboLogs.Instance, @@ -103,7 +103,7 @@ public void Parent_timestamp_is_used_consistently() NullSealEngine.Instance, Build.A.BlockTree().TestObject, Substitute.For(), - Substitute.For(), + Substitute.For(), Substitute.For(), timestamper, LimboLogs.Instance, diff --git a/src/Nethermind/Nethermind.Blockchain.Test/Producers/DevBlockproducerTests.cs b/src/Nethermind/Nethermind.Blockchain.Test/Producers/DevBlockproducerTests.cs index 38830d72a25..c8de8362917 100644 --- a/src/Nethermind/Nethermind.Blockchain.Test/Producers/DevBlockproducerTests.cs +++ b/src/Nethermind/Nethermind.Blockchain.Test/Producers/DevBlockproducerTests.cs @@ -53,12 +53,11 @@ public void Test() NoPruning.Instance, Archive.Instance, LimboLogs.Instance); - StateProvider stateProvider = new( + WorldState stateProvider = new( trieStore, dbProvider.RegisteredDbs[DbNames.Code], LimboLogs.Instance); StateReader stateReader = new(trieStore, dbProvider.GetDb(DbNames.State), LimboLogs.Instance); - StorageProvider storageProvider = new(trieStore, stateProvider, LimboLogs.Instance); BlockhashProvider blockhashProvider = new(blockTree, LimboLogs.Instance); VirtualMachine virtualMachine = new( blockhashProvider, @@ -67,7 +66,6 @@ public void Test() TransactionProcessor txProcessor = new( specProvider, stateProvider, - storageProvider, virtualMachine, LimboLogs.Instance); BlockProcessor blockProcessor = new( @@ -76,7 +74,6 @@ public void Test() NoBlockRewards.Instance, new BlockProcessor.BlockValidationTransactionsExecutor(txProcessor, stateProvider), stateProvider, - storageProvider, NullReceiptStorage.Instance, NullWitnessCollector.Instance, LimboLogs.Instance); diff --git a/src/Nethermind/Nethermind.Blockchain.Test/ReorgTests.cs b/src/Nethermind/Nethermind.Blockchain.Test/ReorgTests.cs index fe1bc5d7c59..8795add9d9c 100644 --- a/src/Nethermind/Nethermind.Blockchain.Test/ReorgTests.cs +++ b/src/Nethermind/Nethermind.Blockchain.Test/ReorgTests.cs @@ -44,9 +44,8 @@ public void Setup() { IDbProvider memDbProvider = TestMemDbProvider.Init(); TrieStore trieStore = new(new MemDb(), LimboLogs.Instance); - StateProvider stateProvider = new(trieStore, memDbProvider.CodeDb, LimboLogs.Instance); + WorldState stateProvider = new(trieStore, memDbProvider.CodeDb, LimboLogs.Instance); StateReader stateReader = new(trieStore, memDbProvider.CodeDb, LimboLogs.Instance); - StorageProvider storageProvider = new(trieStore, stateProvider, LimboLogs.Instance); ChainLevelInfoRepository chainLevelInfoRepository = new(memDbProvider); ISpecProvider specProvider = MainnetSpecProvider.Instance; IBloomStorage bloomStorage = NullBloomStorage.Instance; @@ -75,7 +74,6 @@ public void Setup() TransactionProcessor transactionProcessor = new( specProvider, stateProvider, - storageProvider, virtualMachine, LimboLogs.Instance); @@ -85,7 +83,6 @@ public void Setup() new RewardCalculator(specProvider), new BlockProcessor.BlockValidationTransactionsExecutor(transactionProcessor, stateProvider), stateProvider, - storageProvider, NullReceiptStorage.Instance, new WitnessCollector(memDbProvider.StateDb, LimboLogs.Instance), LimboLogs.Instance); diff --git a/src/Nethermind/Nethermind.Blockchain.Test/TransactionSelectorTests.cs b/src/Nethermind/Nethermind.Blockchain.Test/TransactionSelectorTests.cs index bbe339c01f7..66adabd5885 100644 --- a/src/Nethermind/Nethermind.Blockchain.Test/TransactionSelectorTests.cs +++ b/src/Nethermind/Nethermind.Blockchain.Test/TransactionSelectorTests.cs @@ -187,7 +187,7 @@ public void Proper_transactions_selected(ProperTransactionsSelectedTestCase test MemDb stateDb = new(); MemDb codeDb = new(); TrieStore trieStore = new(stateDb, LimboLogs.Instance); - StateProvider stateProvider = new(trieStore, codeDb, LimboLogs.Instance); + WorldState stateProvider = new(trieStore, codeDb, LimboLogs.Instance); StateReader stateReader = new(new TrieStore(stateDb, LimboLogs.Instance), codeDb, LimboLogs.Instance); ISpecProvider specProvider = Substitute.For(); diff --git a/src/Nethermind/Nethermind.Blockchain.Test/TransactionsExecutorTests.cs b/src/Nethermind/Nethermind.Blockchain.Test/TransactionsExecutorTests.cs index 689799d1be1..65c6d055cca 100644 --- a/src/Nethermind/Nethermind.Blockchain.Test/TransactionsExecutorTests.cs +++ b/src/Nethermind/Nethermind.Blockchain.Test/TransactionsExecutorTests.cs @@ -265,8 +265,7 @@ public void Proper_transactions_selected(TransactionSelectorTests.ProperTransact MemDb stateDb = new(); MemDb codeDb = new(); TrieStore trieStore = new(stateDb, LimboLogs.Instance); - StateProvider stateProvider = new(trieStore, codeDb, LimboLogs.Instance); - IStorageProvider storageProvider = Substitute.For(); + WorldState stateProvider = new(trieStore, codeDb, LimboLogs.Instance); ISpecProvider specProvider = Substitute.For(); IReleaseSpec spec = testCase.ReleaseSpec; @@ -322,7 +321,6 @@ void SetAccountStates(IEnumerable
missingAddresses) new( transactionProcessor, stateProvider, - storageProvider, specProvider, LimboLogs.Instance); diff --git a/src/Nethermind/Nethermind.Blockchain/Contracts/CallableContract.cs b/src/Nethermind/Nethermind.Blockchain/Contracts/CallableContract.cs index e04906115a7..41dff35a7c9 100644 --- a/src/Nethermind/Nethermind.Blockchain/Contracts/CallableContract.cs +++ b/src/Nethermind/Nethermind.Blockchain/Contracts/CallableContract.cs @@ -117,7 +117,7 @@ protected bool TryCall(BlockHeader header, string functionName, Address sender, /// Creates account if its not in current state. /// /// State provider. - protected void EnsureSystemAccount(IStateProvider stateProvider) + protected void EnsureSystemAccount(IWorldState stateProvider) { if (!stateProvider.AccountExists(Address.SystemUser)) { diff --git a/src/Nethermind/Nethermind.Blockchain/GenesisLoader.cs b/src/Nethermind/Nethermind.Blockchain/GenesisLoader.cs index a80d2f715a5..8cac17f0ed3 100644 --- a/src/Nethermind/Nethermind.Blockchain/GenesisLoader.cs +++ b/src/Nethermind/Nethermind.Blockchain/GenesisLoader.cs @@ -22,21 +22,18 @@ public class GenesisLoader { private readonly ChainSpec _chainSpec; private readonly ISpecProvider _specProvider; - private readonly IStateProvider _stateProvider; - private readonly IStorageProvider _storageProvider; + private readonly IWorldState _stateProvider; private readonly ITransactionProcessor _transactionProcessor; public GenesisLoader( ChainSpec chainSpec, ISpecProvider specProvider, - IStateProvider stateProvider, - IStorageProvider storageProvider, + IWorldState stateProvider, ITransactionProcessor transactionProcessor) { _chainSpec = chainSpec ?? throw new ArgumentNullException(nameof(chainSpec)); _specProvider = specProvider ?? throw new ArgumentNullException(nameof(specProvider)); _stateProvider = stateProvider ?? throw new ArgumentNullException(nameof(stateProvider)); - _storageProvider = storageProvider ?? throw new ArgumentNullException(nameof(storageProvider)); _transactionProcessor = transactionProcessor ?? throw new ArgumentNullException(nameof(transactionProcessor)); } @@ -48,10 +45,8 @@ public Block Load() // we no longer need the allocations - 0.5MB RAM, 9000 objects for mainnet _chainSpec.Allocations = null; - _storageProvider.Commit(); _stateProvider.Commit(_specProvider.GenesisSpec, true); - _storageProvider.CommitTrees(0); _stateProvider.CommitTree(0); genesis.Header.StateRoot = _stateProvider.StateRoot; @@ -68,15 +63,14 @@ private void Preallocate(Block genesis) if (allocation.Code is not null) { - Keccak codeHash = _stateProvider.UpdateCode(allocation.Code); - _stateProvider.UpdateCodeHash(address, codeHash, _specProvider.GenesisSpec, true); + _stateProvider.InsertCode(address, allocation.Code, _specProvider.GenesisSpec, true); } if (allocation.Storage is not null) { foreach (KeyValuePair storage in allocation.Storage) { - _storageProvider.Set(new StorageCell(address, storage.Key), + _stateProvider.Set(new StorageCell(address, storage.Key), storage.Value.WithoutLeadingZeros().ToArray()); } } diff --git a/src/Nethermind/Nethermind.Clique.Test/CliqueBlockProducerTests.cs b/src/Nethermind/Nethermind.Clique.Test/CliqueBlockProducerTests.cs index 302f58e2bcf..1a8ab589711 100644 --- a/src/Nethermind/Nethermind.Clique.Test/CliqueBlockProducerTests.cs +++ b/src/Nethermind/Nethermind.Clique.Test/CliqueBlockProducerTests.cs @@ -97,7 +97,7 @@ public On CreateNode(PrivateKey privateKey, bool withGenesisAlreadyProcessed = f var trieStore = new TrieStore(stateDb, nodeLogManager); StateReader stateReader = new(trieStore, codeDb, nodeLogManager); - StateProvider stateProvider = new(trieStore, codeDb, nodeLogManager); + WorldState stateProvider = new(trieStore, codeDb, nodeLogManager); stateProvider.CreateAccount(TestItem.PrivateKeyD.Address, 100.Ether()); GoerliSpecProvider goerliSpecProvider = GoerliSpecProvider.Instance; stateProvider.Commit(goerliSpecProvider.GenesisSpec); @@ -123,15 +123,13 @@ public On CreateNode(PrivateKey privateKey, bool withGenesisAlreadyProcessed = f _genesis.Header.Hash = _genesis.Header.CalculateHash(); _genesis3Validators.Header.Hash = _genesis3Validators.Header.CalculateHash(); - StorageProvider storageProvider = new(trieStore, stateProvider, nodeLogManager); - TransactionProcessor transactionProcessor = new(goerliSpecProvider, stateProvider, storageProvider, new VirtualMachine(blockhashProvider, specProvider, nodeLogManager), nodeLogManager); + TransactionProcessor transactionProcessor = new(goerliSpecProvider, stateProvider, new VirtualMachine(blockhashProvider, specProvider, nodeLogManager), nodeLogManager); BlockProcessor blockProcessor = new( goerliSpecProvider, Always.Valid, NoBlockRewards.Instance, new BlockProcessor.BlockValidationTransactionsExecutor(transactionProcessor, stateProvider), stateProvider, - storageProvider, NullReceiptStorage.Instance, NullWitnessCollector.Instance, nodeLogManager); @@ -141,18 +139,16 @@ public On CreateNode(PrivateKey privateKey, bool withGenesisAlreadyProcessed = f IReadOnlyTrieStore minerTrieStore = trieStore.AsReadOnly(); - StateProvider minerStateProvider = new(minerTrieStore, codeDb, nodeLogManager); - StorageProvider minerStorageProvider = new(minerTrieStore, minerStateProvider, nodeLogManager); + WorldState minerStateProvider = new(minerTrieStore, codeDb, nodeLogManager); VirtualMachine minerVirtualMachine = new(blockhashProvider, specProvider, nodeLogManager); - TransactionProcessor minerTransactionProcessor = new(goerliSpecProvider, minerStateProvider, minerStorageProvider, minerVirtualMachine, nodeLogManager); + TransactionProcessor minerTransactionProcessor = new(goerliSpecProvider, minerStateProvider, minerVirtualMachine, nodeLogManager); BlockProcessor minerBlockProcessor = new( goerliSpecProvider, Always.Valid, NoBlockRewards.Instance, - new BlockProcessor.BlockProductionTransactionsExecutor(minerTransactionProcessor, minerStateProvider, minerStorageProvider, goerliSpecProvider, _logManager), + new BlockProcessor.BlockProductionTransactionsExecutor(minerTransactionProcessor, minerStateProvider, goerliSpecProvider, _logManager), minerStateProvider, - minerStorageProvider, NullReceiptStorage.Instance, NullWitnessCollector.Instance, nodeLogManager); diff --git a/src/Nethermind/Nethermind.Clique.Test/CliqueRpcModuleTests.cs b/src/Nethermind/Nethermind.Clique.Test/CliqueRpcModuleTests.cs index 5beddb896bd..fd2c0ee9ba4 100644 --- a/src/Nethermind/Nethermind.Clique.Test/CliqueRpcModuleTests.cs +++ b/src/Nethermind/Nethermind.Clique.Test/CliqueRpcModuleTests.cs @@ -35,7 +35,7 @@ public void Sets_clique_block_producer_properly() CliqueBlockProducer producer = new( Substitute.For(), Substitute.For(), - Substitute.For(), + Substitute.For(), blockTree, Substitute.For(), Substitute.For(), diff --git a/src/Nethermind/Nethermind.Consensus.AuRa/AuRaBlockProcessor.cs b/src/Nethermind/Nethermind.Consensus.AuRa/AuRaBlockProcessor.cs index e269a6e030e..52dc575fab0 100644 --- a/src/Nethermind/Nethermind.Consensus.AuRa/AuRaBlockProcessor.cs +++ b/src/Nethermind/Nethermind.Consensus.AuRa/AuRaBlockProcessor.cs @@ -38,8 +38,7 @@ public AuRaBlockProcessor( IBlockValidator blockValidator, IRewardCalculator rewardCalculator, IBlockProcessor.IBlockTransactionsExecutor blockTransactionsExecutor, - IStateProvider stateProvider, - IStorageProvider storageProvider, + IWorldState stateProvider, IReceiptStorage receiptStorage, ILogManager logManager, IBlockTree blockTree, @@ -53,7 +52,6 @@ public AuRaBlockProcessor( rewardCalculator, blockTransactionsExecutor, stateProvider, - storageProvider, receiptStorage, NullWitnessCollector.Instance, logManager, diff --git a/src/Nethermind/Nethermind.Consensus.AuRa/AuRaBlockProducer.cs b/src/Nethermind/Nethermind.Consensus.AuRa/AuRaBlockProducer.cs index f6644e8d2f2..6a9b4207fe8 100644 --- a/src/Nethermind/Nethermind.Consensus.AuRa/AuRaBlockProducer.cs +++ b/src/Nethermind/Nethermind.Consensus.AuRa/AuRaBlockProducer.cs @@ -30,7 +30,7 @@ public class AuRaBlockProducer : BlockProducerBase public AuRaBlockProducer(ITxSource txSource, IBlockchainProcessor processor, IBlockProductionTrigger blockProductionTrigger, - IStateProvider stateProvider, + IWorldState stateProvider, ISealer sealer, IBlockTree blockTree, ITimestamper timestamper, diff --git a/src/Nethermind/Nethermind.Consensus.AuRa/AuRaValidatorFactory.cs b/src/Nethermind/Nethermind.Consensus.AuRa/AuRaValidatorFactory.cs index ef2922ee983..d140e9cb835 100644 --- a/src/Nethermind/Nethermind.Consensus.AuRa/AuRaValidatorFactory.cs +++ b/src/Nethermind/Nethermind.Consensus.AuRa/AuRaValidatorFactory.cs @@ -22,7 +22,7 @@ namespace Nethermind.Consensus.AuRa { public class AuRaValidatorFactory : IAuRaValidatorFactory { - private readonly IStateProvider _stateProvider; + private readonly IWorldState _stateProvider; private readonly IAbiEncoder _abiEncoder; private readonly ITransactionProcessor _transactionProcessor; private readonly IReadOnlyTxProcessorSource _readOnlyTxProcessorSource; @@ -42,7 +42,7 @@ public class AuRaValidatorFactory : IAuRaValidatorFactory private readonly bool _forSealing; public AuRaValidatorFactory(IAbiEncoder abiEncoder, - IStateProvider stateProvider, + IWorldState stateProvider, ITransactionProcessor transactionProcessor, IBlockTree blockTree, IReadOnlyTxProcessorSource readOnlyTxProcessorSource, diff --git a/src/Nethermind/Nethermind.Consensus.AuRa/ContractRewriter.cs b/src/Nethermind/Nethermind.Consensus.AuRa/ContractRewriter.cs index 42349819313..cd8c60a5263 100644 --- a/src/Nethermind/Nethermind.Consensus.AuRa/ContractRewriter.cs +++ b/src/Nethermind/Nethermind.Consensus.AuRa/ContractRewriter.cs @@ -18,14 +18,13 @@ public ContractRewriter(IDictionary> contract _contractOverrides = contractOverrides; } - public void RewriteContracts(long blockNumber, IStateProvider stateProvider, IReleaseSpec spec) + public void RewriteContracts(long blockNumber, IWorldState stateProvider, IReleaseSpec spec) { if (_contractOverrides.TryGetValue(blockNumber, out IDictionary overrides)) { foreach (KeyValuePair contractOverride in overrides) { - Keccak codeHash = stateProvider.UpdateCode(contractOverride.Value); - stateProvider.UpdateCodeHash(contractOverride.Key, codeHash, spec); + stateProvider.InsertCode(contractOverride.Key, contractOverride.Value, spec); } } } diff --git a/src/Nethermind/Nethermind.Consensus.AuRa/Contracts/ValidatorContract.cs b/src/Nethermind/Nethermind.Consensus.AuRa/Contracts/ValidatorContract.cs index 3f4c32a89b2..4f909a8442a 100644 --- a/src/Nethermind/Nethermind.Consensus.AuRa/Contracts/ValidatorContract.cs +++ b/src/Nethermind/Nethermind.Consensus.AuRa/Contracts/ValidatorContract.cs @@ -54,7 +54,7 @@ public partial interface IValidatorContract public sealed partial class ValidatorContract : CallableContract, IValidatorContract { - private readonly IStateProvider _stateProvider; + private readonly IWorldState _stateProvider; private readonly ISigner _signer; private IConstantContract Constant { get; } @@ -63,7 +63,7 @@ public ValidatorContract( ITransactionProcessor transactionProcessor, IAbiEncoder abiEncoder, Address contractAddress, - IStateProvider stateProvider, + IWorldState stateProvider, IReadOnlyTxProcessorSource readOnlyTxProcessorSource, ISigner signer) : base(transactionProcessor, abiEncoder, contractAddress ?? throw new ArgumentNullException(nameof(contractAddress))) diff --git a/src/Nethermind/Nethermind.Consensus.AuRa/InitializationSteps/InitializeBlockchainAuRa.cs b/src/Nethermind/Nethermind.Consensus.AuRa/InitializationSteps/InitializeBlockchainAuRa.cs index 0d37baabe47..4c9227a9331 100644 --- a/src/Nethermind/Nethermind.Consensus.AuRa/InitializationSteps/InitializeBlockchainAuRa.cs +++ b/src/Nethermind/Nethermind.Consensus.AuRa/InitializationSteps/InitializeBlockchainAuRa.cs @@ -53,8 +53,7 @@ protected override BlockProcessor CreateBlockProcessor() if (_api.RewardCalculatorSource is null) throw new StepDependencyException(nameof(_api.RewardCalculatorSource)); if (_api.TransactionProcessor is null) throw new StepDependencyException(nameof(_api.TransactionProcessor)); if (_api.DbProvider is null) throw new StepDependencyException(nameof(_api.DbProvider)); - if (_api.StateProvider is null) throw new StepDependencyException(nameof(_api.StateProvider)); - if (_api.StorageProvider is null) throw new StepDependencyException(nameof(_api.StorageProvider)); + if (_api.WorldState is null) throw new StepDependencyException(nameof(_api.WorldState)); if (_api.TxPool is null) throw new StepDependencyException(nameof(_api.TxPool)); if (_api.ReceiptStorage is null) throw new StepDependencyException(nameof(_api.ReceiptStorage)); if (_api.BlockTree is null) throw new StepDependencyException(nameof(_api.BlockTree)); @@ -92,9 +91,8 @@ protected virtual BlockProcessor NewBlockProcessor(AuRaNethermindApi api, ITxFil _api.SpecProvider, _api.BlockValidator, _api.RewardCalculatorSource.Get(_api.TransactionProcessor), - new BlockProcessor.BlockValidationTransactionsExecutor(_api.TransactionProcessor, _api.StateProvider), - _api.StateProvider, - _api.StorageProvider, + new BlockProcessor.BlockValidationTransactionsExecutor(_api.TransactionProcessor, _api.WorldState), + _api.WorldState, _api.ReceiptStorage, _api.LogManager, _api.BlockTree, @@ -132,7 +130,7 @@ private IAuRaValidator CreateAuRaValidator(IBlockProcessor processor, IReadOnlyT chainSpecAuRa.TwoThirdsMajorityTransition); IAuRaValidator validator = new AuRaValidatorFactory(_api.AbiEncoder, - _api.StateProvider, + _api.WorldState, _api.TransactionProcessor, _api.BlockTree, readOnlyTxProcessorSource, diff --git a/src/Nethermind/Nethermind.Consensus.AuRa/InitializationSteps/LoadGenesisBlockAuRa.cs b/src/Nethermind/Nethermind.Consensus.AuRa/InitializationSteps/LoadGenesisBlockAuRa.cs index 5732fdc270a..06890d4fefc 100644 --- a/src/Nethermind/Nethermind.Consensus.AuRa/InitializationSteps/LoadGenesisBlockAuRa.cs +++ b/src/Nethermind/Nethermind.Consensus.AuRa/InitializationSteps/LoadGenesisBlockAuRa.cs @@ -31,12 +31,10 @@ private void CreateSystemAccounts() bool hasConstructorAllocation = _api.ChainSpec.Allocations.Values.Any(a => a.Constructor is not null); if (hasConstructorAllocation) { - if (_api.StateProvider is null) throw new StepDependencyException(nameof(_api.StateProvider)); - if (_api.StorageProvider is null) throw new StepDependencyException(nameof(_api.StorageProvider)); + if (_api.WorldState is null) throw new StepDependencyException(nameof(_api.WorldState)); - _api.StateProvider.CreateAccount(Address.Zero, UInt256.Zero); - _api.StorageProvider.Commit(); - _api.StateProvider.Commit(Homestead.Instance); + _api.WorldState.CreateAccount(Address.Zero, UInt256.Zero); + _api.WorldState.Commit(Homestead.Instance); } } } diff --git a/src/Nethermind/Nethermind.Consensus.AuRa/InitializationSteps/StartBlockProducerAuRa.cs b/src/Nethermind/Nethermind.Consensus.AuRa/InitializationSteps/StartBlockProducerAuRa.cs index b88d1504194..c8bd56c76e6 100644 --- a/src/Nethermind/Nethermind.Consensus.AuRa/InitializationSteps/StartBlockProducerAuRa.cs +++ b/src/Nethermind/Nethermind.Consensus.AuRa/InitializationSteps/StartBlockProducerAuRa.cs @@ -155,7 +155,6 @@ private BlockProcessor CreateBlockProcessor(ReadOnlyTxProcessingEnv changeableTx _api.RewardCalculatorSource.Get(changeableTxProcessingEnv.TransactionProcessor), _api.BlockProducerEnvFactory.TransactionsExecutorFactory.Create(changeableTxProcessingEnv), changeableTxProcessingEnv.StateProvider, - changeableTxProcessingEnv.StorageProvider, _api.ReceiptStorage, _api.LogManager, changeableTxProcessingEnv.BlockTree, diff --git a/src/Nethermind/Nethermind.Consensus.Clique/CliqueBlockProducer.cs b/src/Nethermind/Nethermind.Consensus.Clique/CliqueBlockProducer.cs index 98cfbaeea27..d996f9674aa 100644 --- a/src/Nethermind/Nethermind.Consensus.Clique/CliqueBlockProducer.cs +++ b/src/Nethermind/Nethermind.Consensus.Clique/CliqueBlockProducer.cs @@ -29,7 +29,7 @@ namespace Nethermind.Consensus.Clique; public class CliqueBlockProducer : ICliqueBlockProducer, IDisposable { private readonly IBlockTree _blockTree; - private readonly IStateProvider _stateProvider; + private readonly IWorldState _stateProvider; private readonly ITimestamper _timestamper; private readonly ILogger _logger; private readonly ICryptoRandom _cryptoRandom; @@ -52,7 +52,7 @@ public class CliqueBlockProducer : ICliqueBlockProducer, IDisposable public CliqueBlockProducer( ITxSource txSource, IBlockchainProcessor blockchainProcessor, - IStateProvider stateProvider, + IWorldState stateProvider, IBlockTree blockTree, ITimestamper timestamper, ICryptoRandom cryptoRandom, diff --git a/src/Nethermind/Nethermind.Consensus.Clique/CliquePlugin.cs b/src/Nethermind/Nethermind.Consensus.Clique/CliquePlugin.cs index 751bd138ec4..4180bd2a69a 100644 --- a/src/Nethermind/Nethermind.Consensus.Clique/CliquePlugin.cs +++ b/src/Nethermind/Nethermind.Consensus.Clique/CliquePlugin.cs @@ -107,7 +107,6 @@ public Task InitBlockProducer(IBlockProductionTrigger? blockProd NoBlockRewards.Instance, getFromApi.BlockProducerEnvFactory.TransactionsExecutorFactory.Create(producerEnv), producerEnv.StateProvider, - producerEnv.StorageProvider, // do not remove transactions from the pool when preprocessing NullReceiptStorage.Instance, NullWitnessCollector.Instance, getFromApi.LogManager, diff --git a/src/Nethermind/Nethermind.Consensus.Ethash/MinedBlockProducer.cs b/src/Nethermind/Nethermind.Consensus.Ethash/MinedBlockProducer.cs index b9316a09cc3..b927e2b85c8 100644 --- a/src/Nethermind/Nethermind.Consensus.Ethash/MinedBlockProducer.cs +++ b/src/Nethermind/Nethermind.Consensus.Ethash/MinedBlockProducer.cs @@ -26,7 +26,7 @@ public MinedBlockProducer(ITxSource txSource, ISealer sealer, IBlockTree blockTree, IBlockProductionTrigger blockProductionTrigger, - IStateProvider stateProvider, + IWorldState stateProvider, IGasLimitCalculator gasLimitCalculator, ITimestamper timestamper, ISpecProvider specProvider, diff --git a/src/Nethermind/Nethermind.Consensus.Ethash/NethDevPlugin.cs b/src/Nethermind/Nethermind.Consensus.Ethash/NethDevPlugin.cs index 6d2b0f0ead6..4db8a7d0aa6 100644 --- a/src/Nethermind/Nethermind.Consensus.Ethash/NethDevPlugin.cs +++ b/src/Nethermind/Nethermind.Consensus.Ethash/NethDevPlugin.cs @@ -79,7 +79,6 @@ public Task InitBlockProducer(IBlockProductionTrigger? blockProd NoBlockRewards.Instance, new BlockProcessor.BlockProductionTransactionsExecutor(producerEnv, getFromApi!.SpecProvider, getFromApi.LogManager), producerEnv.StateProvider, - producerEnv.StorageProvider, NullReceiptStorage.Instance, NullWitnessCollector.Instance, getFromApi.LogManager); diff --git a/src/Nethermind/Nethermind.Consensus/Processing/BlockProcessor.BlockProductionTransactionPicker.cs b/src/Nethermind/Nethermind.Consensus/Processing/BlockProcessor.BlockProductionTransactionPicker.cs index 5122898ff67..f5a2e6bc030 100644 --- a/src/Nethermind/Nethermind.Consensus/Processing/BlockProcessor.BlockProductionTransactionPicker.cs +++ b/src/Nethermind/Nethermind.Consensus/Processing/BlockProcessor.BlockProductionTransactionPicker.cs @@ -26,7 +26,7 @@ public BlockProductionTransactionPicker(ISpecProvider specProvider) public event EventHandler? AddingTransaction; - public AddingTxEventArgs CanAddTransaction(Block block, Transaction currentTx, IReadOnlySet transactionsInBlock, IStateProvider stateProvider) + public AddingTxEventArgs CanAddTransaction(Block block, Transaction currentTx, IReadOnlySet transactionsInBlock, IWorldState stateProvider) { AddingTxEventArgs args = new(transactionsInBlock.Count, currentTx, block, transactionsInBlock); diff --git a/src/Nethermind/Nethermind.Consensus/Processing/BlockProcessor.BlockProductionTransactionsExecutor.cs b/src/Nethermind/Nethermind.Consensus/Processing/BlockProcessor.BlockProductionTransactionsExecutor.cs index 02262927df2..05b11f9d7b7 100644 --- a/src/Nethermind/Nethermind.Consensus/Processing/BlockProcessor.BlockProductionTransactionsExecutor.cs +++ b/src/Nethermind/Nethermind.Consensus/Processing/BlockProcessor.BlockProductionTransactionsExecutor.cs @@ -20,8 +20,7 @@ public partial class BlockProcessor public class BlockProductionTransactionsExecutor : IBlockProductionTransactionsExecutor { private readonly ITransactionProcessorAdapter _transactionProcessor; - private readonly IStateProvider _stateProvider; - private readonly IStorageProvider _storageProvider; + private readonly IWorldState _stateProvider; private readonly BlockProductionTransactionPicker _blockProductionTransactionPicker; private readonly ILogger _logger; @@ -32,7 +31,6 @@ public BlockProductionTransactionsExecutor( : this( readOnlyTxProcessingEnv.TransactionProcessor, readOnlyTxProcessingEnv.StateProvider, - readOnlyTxProcessingEnv.StorageProvider, specProvider, logManager) { @@ -40,14 +38,12 @@ public BlockProductionTransactionsExecutor( public BlockProductionTransactionsExecutor( ITransactionProcessor transactionProcessor, - IStateProvider stateProvider, - IStorageProvider storageProvider, + IWorldState stateProvider, ISpecProvider specProvider, ILogManager logManager) { _transactionProcessor = new BuildUpTransactionProcessorAdapter(transactionProcessor); _stateProvider = stateProvider; - _storageProvider = storageProvider; _blockProductionTransactionPicker = new BlockProductionTransactionPicker(specProvider); _logger = logManager.GetClassLogger(); } @@ -78,7 +74,6 @@ public virtual TxReceipt[] ProcessTransactions(Block block, ProcessingOptions pr } _stateProvider.Commit(spec, receiptsTracer); - _storageProvider.Commit(receiptsTracer); SetTransactions(block, transactionsInBlock); return receiptsTracer.TxReceipts.ToArray(); diff --git a/src/Nethermind/Nethermind.Consensus/Processing/BlockProcessor.BlockValidationTransactionsExecutor.cs b/src/Nethermind/Nethermind.Consensus/Processing/BlockProcessor.BlockValidationTransactionsExecutor.cs index 8c4d1b90394..4489c88109d 100644 --- a/src/Nethermind/Nethermind.Consensus/Processing/BlockProcessor.BlockValidationTransactionsExecutor.cs +++ b/src/Nethermind/Nethermind.Consensus/Processing/BlockProcessor.BlockValidationTransactionsExecutor.cs @@ -16,14 +16,14 @@ public partial class BlockProcessor public class BlockValidationTransactionsExecutor : IBlockProcessor.IBlockTransactionsExecutor { private readonly ITransactionProcessorAdapter _transactionProcessor; - private readonly IStateProvider _stateProvider; + private readonly IWorldState _stateProvider; - public BlockValidationTransactionsExecutor(ITransactionProcessor transactionProcessor, IStateProvider stateProvider) + public BlockValidationTransactionsExecutor(ITransactionProcessor transactionProcessor, IWorldState stateProvider) : this(new ExecuteTransactionProcessorAdapter(transactionProcessor), stateProvider) { } - public BlockValidationTransactionsExecutor(ITransactionProcessorAdapter transactionProcessor, IStateProvider stateProvider) + public BlockValidationTransactionsExecutor(ITransactionProcessorAdapter transactionProcessor, IWorldState stateProvider) { _transactionProcessor = transactionProcessor; _stateProvider = stateProvider; diff --git a/src/Nethermind/Nethermind.Consensus/Processing/BlockProcessor.cs b/src/Nethermind/Nethermind.Consensus/Processing/BlockProcessor.cs index 452c69d5f7f..dfdecd8f4d0 100644 --- a/src/Nethermind/Nethermind.Consensus/Processing/BlockProcessor.cs +++ b/src/Nethermind/Nethermind.Consensus/Processing/BlockProcessor.cs @@ -25,12 +25,11 @@ public partial class BlockProcessor : IBlockProcessor { private readonly ILogger _logger; private readonly ISpecProvider _specProvider; - protected readonly IStateProvider _stateProvider; + protected readonly IWorldState _stateProvider; private readonly IReceiptStorage _receiptStorage; private readonly IWitnessCollector _witnessCollector; private readonly IWithdrawalProcessor _withdrawalProcessor; private readonly IBlockValidator _blockValidator; - private readonly IStorageProvider _storageProvider; private readonly IRewardCalculator _rewardCalculator; private readonly IBlockProcessor.IBlockTransactionsExecutor _blockTransactionsExecutor; @@ -47,8 +46,7 @@ public BlockProcessor( IBlockValidator? blockValidator, IRewardCalculator? rewardCalculator, IBlockProcessor.IBlockTransactionsExecutor? blockTransactionsExecutor, - IStateProvider? stateProvider, - IStorageProvider? storageProvider, + IWorldState? stateProvider, IReceiptStorage? receiptStorage, IWitnessCollector? witnessCollector, ILogManager? logManager, @@ -58,7 +56,6 @@ public BlockProcessor( _specProvider = specProvider ?? throw new ArgumentNullException(nameof(specProvider)); _blockValidator = blockValidator ?? throw new ArgumentNullException(nameof(blockValidator)); _stateProvider = stateProvider ?? throw new ArgumentNullException(nameof(stateProvider)); - _storageProvider = storageProvider ?? throw new ArgumentNullException(nameof(storageProvider)); _receiptStorage = receiptStorage ?? throw new ArgumentNullException(nameof(receiptStorage)); _witnessCollector = witnessCollector ?? throw new ArgumentNullException(nameof(witnessCollector)); _withdrawalProcessor = withdrawalProcessor ?? new WithdrawalProcessor(stateProvider, logManager); @@ -159,7 +156,6 @@ by blocks that are being reorganized out.*/ if (incrementReorgMetric) Metrics.Reorganizations++; - _storageProvider.Reset(); _stateProvider.Reset(); _stateProvider.StateRoot = branchStateRoot; } @@ -175,7 +171,6 @@ private Keccak CreateCheckpoint() private void PreCommitBlock(Keccak newBranchStateRoot, long blockNumber) { if (_logger.IsTrace) _logger.Trace($"Committing the branch - {newBranchStateRoot}"); - _storageProvider.CommitTrees(blockNumber); _stateProvider.CommitTree(blockNumber); } @@ -183,7 +178,6 @@ private void PreCommitBlock(Keccak newBranchStateRoot, long blockNumber) private void RestoreBranch(Keccak branchingPointStateRoot) { if (_logger.IsTrace) _logger.Trace($"Restoring the branch checkpoint - {branchingPointStateRoot}"); - _storageProvider.Reset(); _stateProvider.Reset(); _stateProvider.StateRoot = branchingPointStateRoot; if (_logger.IsTrace) _logger.Trace($"Restored the branch checkpoint - {branchingPointStateRoot} | {_stateProvider.StateRoot}"); diff --git a/src/Nethermind/Nethermind.Consensus/Processing/ReadOnlyChainProcessingEnv.cs b/src/Nethermind/Nethermind.Consensus/Processing/ReadOnlyChainProcessingEnv.cs index ca963a9d692..da38938699c 100644 --- a/src/Nethermind/Nethermind.Consensus/Processing/ReadOnlyChainProcessingEnv.cs +++ b/src/Nethermind/Nethermind.Consensus/Processing/ReadOnlyChainProcessingEnv.cs @@ -24,7 +24,7 @@ public class ReadOnlyChainProcessingEnv : IDisposable public IBlockProcessor BlockProcessor { get; } public IBlockchainProcessor ChainProcessor { get; } public IBlockProcessingQueue BlockProcessingQueue { get; } - public IStateProvider StateProvider => _txEnv.StateProvider; + public IWorldState StateProvider => _txEnv.StateProvider; public ReadOnlyChainProcessingEnv( ReadOnlyTxProcessingEnv txEnv, @@ -48,7 +48,6 @@ public ReadOnlyChainProcessingEnv( rewardCalculator, transactionsExecutor, StateProvider, - _txEnv.StorageProvider, receiptStorage, NullWitnessCollector.Instance, logManager); diff --git a/src/Nethermind/Nethermind.Consensus/Processing/ReadOnlyTxProcessingEnv.cs b/src/Nethermind/Nethermind.Consensus/Processing/ReadOnlyTxProcessingEnv.cs index a6351f7393a..f99c5f01b12 100644 --- a/src/Nethermind/Nethermind.Consensus/Processing/ReadOnlyTxProcessingEnv.cs +++ b/src/Nethermind/Nethermind.Consensus/Processing/ReadOnlyTxProcessingEnv.cs @@ -19,10 +19,8 @@ namespace Nethermind.Consensus.Processing { public class ReadOnlyTxProcessingEnv : IReadOnlyTxProcessorSource { - private readonly ReadOnlyDb _codeDb; public IStateReader StateReader { get; } - public IStateProvider StateProvider { get; } - public IStorageProvider StorageProvider { get; } + public IWorldState StateProvider { get; } public ITransactionProcessor TransactionProcessor { get; set; } public IBlockTree BlockTree { get; } public IReadOnlyDbProvider DbProvider { get; } @@ -49,20 +47,18 @@ public ReadOnlyTxProcessingEnv( if (specProvider is null) throw new ArgumentNullException(nameof(specProvider)); DbProvider = readOnlyDbProvider ?? throw new ArgumentNullException(nameof(readOnlyDbProvider)); - _codeDb = readOnlyDbProvider.CodeDb.AsReadOnly(true); + ReadOnlyDb codeDb = readOnlyDbProvider.CodeDb.AsReadOnly(true); - StateReader = new StateReader(readOnlyTrieStore, _codeDb, logManager); - StateProvider = new StateProvider(readOnlyTrieStore, _codeDb, logManager); - StorageProvider = new StorageProvider(readOnlyTrieStore, StateProvider, logManager); - IWorldState worldState = new WorldState(StateProvider, StorageProvider); + StateReader = new StateReader(readOnlyTrieStore, codeDb, logManager); + StateProvider = new WorldState(readOnlyTrieStore, codeDb, logManager); BlockTree = readOnlyBlockTree ?? throw new ArgumentNullException(nameof(readOnlyBlockTree)); BlockhashProvider = new BlockhashProvider(BlockTree, logManager); Machine = new VirtualMachine(BlockhashProvider, specProvider, logManager); - TransactionProcessor = new TransactionProcessor(specProvider, worldState, Machine, logManager); + TransactionProcessor = new TransactionProcessor(specProvider, StateProvider, Machine, logManager); } - public IReadOnlyTransactionProcessor Build(Keccak stateRoot) => new ReadOnlyTransactionProcessor(TransactionProcessor, StateProvider, StorageProvider, _codeDb, stateRoot); + public IReadOnlyTransactionProcessor Build(Keccak stateRoot) => new ReadOnlyTransactionProcessor(TransactionProcessor, StateProvider, stateRoot); } } diff --git a/src/Nethermind/Nethermind.Consensus/Processing/TransactionProcessorAdapterExtensions.cs b/src/Nethermind/Nethermind.Consensus/Processing/TransactionProcessorAdapterExtensions.cs index 52c14ef0efd..d00b2b4fdf2 100644 --- a/src/Nethermind/Nethermind.Consensus/Processing/TransactionProcessorAdapterExtensions.cs +++ b/src/Nethermind/Nethermind.Consensus/Processing/TransactionProcessorAdapterExtensions.cs @@ -15,7 +15,7 @@ public static void ProcessTransaction(this ITransactionProcessorAdapter transact Transaction currentTx, BlockReceiptsTracer receiptsTracer, ProcessingOptions processingOptions, - IStateProvider stateProvider) + IWorldState stateProvider) { if (processingOptions.ContainsFlag(ProcessingOptions.DoNotVerifyNonce)) { diff --git a/src/Nethermind/Nethermind.Consensus/Producers/BlockProducerBase.cs b/src/Nethermind/Nethermind.Consensus/Producers/BlockProducerBase.cs index ac57326e0db..f3f54fb7849 100644 --- a/src/Nethermind/Nethermind.Consensus/Producers/BlockProducerBase.cs +++ b/src/Nethermind/Nethermind.Consensus/Producers/BlockProducerBase.cs @@ -41,7 +41,7 @@ public abstract class BlockProducerBase : IBlockProducer public event EventHandler? BlockProduced; private ISealer Sealer { get; } - private IStateProvider StateProvider { get; } + private IWorldState StateProvider { get; } private readonly IGasLimitCalculator _gasLimitCalculator; private readonly IDifficultyCalculator _difficultyCalculator; private readonly ISpecProvider _specProvider; @@ -62,7 +62,7 @@ protected BlockProducerBase( ISealer? sealer, IBlockTree? blockTree, IBlockProductionTrigger? trigger, - IStateProvider? stateProvider, + IWorldState? stateProvider, IGasLimitCalculator? gasLimitCalculator, ITimestamper? timestamper, ISpecProvider? specProvider, diff --git a/src/Nethermind/Nethermind.Consensus/Producers/BlockProducerEnvFactory.cs b/src/Nethermind/Nethermind.Consensus/Producers/BlockProducerEnvFactory.cs index e5f60e49974..3d88b53ba6a 100644 --- a/src/Nethermind/Nethermind.Consensus/Producers/BlockProducerEnvFactory.cs +++ b/src/Nethermind/Nethermind.Consensus/Producers/BlockProducerEnvFactory.cs @@ -146,7 +146,6 @@ protected virtual BlockProcessor CreateBlockProcessor(ReadOnlyTxProcessingEnv re rewardCalculatorSource.Get(readOnlyTxProcessingEnv.TransactionProcessor), TransactionsExecutorFactory.Create(readOnlyTxProcessingEnv), readOnlyTxProcessingEnv.StateProvider, - readOnlyTxProcessingEnv.StorageProvider, receiptStorage, NullWitnessCollector.Instance, logManager, diff --git a/src/Nethermind/Nethermind.Consensus/Producers/DevBlockProducer.cs b/src/Nethermind/Nethermind.Consensus/Producers/DevBlockProducer.cs index 57a9c38d7b9..162a9e2dfcb 100644 --- a/src/Nethermind/Nethermind.Consensus/Producers/DevBlockProducer.cs +++ b/src/Nethermind/Nethermind.Consensus/Producers/DevBlockProducer.cs @@ -21,7 +21,7 @@ public class DevBlockProducer : BlockProducerBase, IDisposable public DevBlockProducer( ITxSource? txSource, IBlockchainProcessor? processor, - IStateProvider? stateProvider, + IWorldState? stateProvider, IBlockTree? blockTree, IBlockProductionTrigger? trigger, ITimestamper? timestamper, diff --git a/src/Nethermind/Nethermind.Consensus/ReadOnlyChain.cs b/src/Nethermind/Nethermind.Consensus/ReadOnlyChain.cs index b3729213aa1..425687d29dd 100644 --- a/src/Nethermind/Nethermind.Consensus/ReadOnlyChain.cs +++ b/src/Nethermind/Nethermind.Consensus/ReadOnlyChain.cs @@ -12,7 +12,7 @@ public class BlockProducerEnv { public IBlockTree BlockTree { get; set; } public IBlockchainProcessor ChainProcessor { get; set; } - public IStateProvider ReadOnlyStateProvider { get; set; } + public IWorldState ReadOnlyStateProvider { get; set; } public ITxSource TxSource { get; set; } public ReadOnlyTxProcessingEnv ReadOnlyTxProcessingEnv { get; set; } } diff --git a/src/Nethermind/Nethermind.Consensus/Tracing/Tracer.cs b/src/Nethermind/Nethermind.Consensus/Tracing/Tracer.cs index 118c0bf40eb..0617ef7a073 100644 --- a/src/Nethermind/Nethermind.Consensus/Tracing/Tracer.cs +++ b/src/Nethermind/Nethermind.Consensus/Tracing/Tracer.cs @@ -13,11 +13,11 @@ namespace Nethermind.Consensus.Tracing { public class Tracer : ITracer { - private readonly IStateProvider _stateProvider; + private readonly IWorldState _stateProvider; private readonly IBlockchainProcessor _blockProcessor; private readonly ProcessingOptions _processingOptions; - public Tracer(IStateProvider stateProvider, IBlockchainProcessor blockProcessor, ProcessingOptions processingOptions = ProcessingOptions.Trace) + public Tracer(IWorldState stateProvider, IBlockchainProcessor blockProcessor, ProcessingOptions processingOptions = ProcessingOptions.Trace) { _stateProvider = stateProvider ?? throw new ArgumentNullException(nameof(stateProvider)); _blockProcessor = blockProcessor ?? throw new ArgumentNullException(nameof(blockProcessor)); diff --git a/src/Nethermind/Nethermind.Consensus/Withdrawals/WithdrawalProcessor.cs b/src/Nethermind/Nethermind.Consensus/Withdrawals/WithdrawalProcessor.cs index 55a729f51b4..907519834fc 100644 --- a/src/Nethermind/Nethermind.Consensus/Withdrawals/WithdrawalProcessor.cs +++ b/src/Nethermind/Nethermind.Consensus/Withdrawals/WithdrawalProcessor.cs @@ -14,9 +14,9 @@ namespace Nethermind.Consensus.Withdrawals; public class WithdrawalProcessor : IWithdrawalProcessor { private readonly ILogger _logger; - private readonly IStateProvider _stateProvider; + private readonly IWorldState _stateProvider; - public WithdrawalProcessor(IStateProvider stateProvider, ILogManager logManager) + public WithdrawalProcessor(IWorldState stateProvider, ILogManager logManager) { ArgumentNullException.ThrowIfNull(logManager); diff --git a/src/Nethermind/Nethermind.Core.Test/Blockchain/TestBlockProducer.cs b/src/Nethermind/Nethermind.Core.Test/Blockchain/TestBlockProducer.cs index ec3100b070d..78e03de4f2e 100644 --- a/src/Nethermind/Nethermind.Core.Test/Blockchain/TestBlockProducer.cs +++ b/src/Nethermind/Nethermind.Core.Test/Blockchain/TestBlockProducer.cs @@ -25,7 +25,7 @@ public class TestBlockProducer : BlockProducerBase public TestBlockProducer( ITxSource txSource, IBlockchainProcessor processor, - IStateProvider stateProvider, + IWorldState stateProvider, ISealer sealer, IBlockTree blockTree, IBlockProductionTrigger blockProductionTrigger, diff --git a/src/Nethermind/Nethermind.Core.Test/Blockchain/TestBlockchain.cs b/src/Nethermind/Nethermind.Core.Test/Blockchain/TestBlockchain.cs index 80b4e93ed7b..bfc07c08289 100644 --- a/src/Nethermind/Nethermind.Core.Test/Blockchain/TestBlockchain.cs +++ b/src/Nethermind/Nethermind.Core.Test/Blockchain/TestBlockchain.cs @@ -45,7 +45,6 @@ public class TestBlockchain : IDisposable public IEthereumEcdsa EthereumEcdsa { get; private set; } = null!; public INonceManager NonceManager { get; private set; } = null!; public TransactionProcessor TxProcessor { get; set; } = null!; - public IStorageProvider Storage { get; set; } = null!; public IReceiptStorage ReceiptStorage { get; set; } = null!; public ITxPool TxPool { get; set; } = null!; public IDb CodeDb => DbProvider.CodeDb; @@ -65,7 +64,7 @@ public IBlockFinder BlockFinder public ILogFinder LogFinder { get; private set; } = null!; public IJsonSerializer JsonSerializer { get; set; } = null!; - public IStateProvider State { get; set; } = null!; + public IWorldState State { get; set; } = null!; public IReadOnlyStateProvider ReadOnlyState { get; private set; } = null!; public IDb StateDb => DbProvider.StateDb; public TrieStore TrieStore { get; set; } = null!; @@ -116,19 +115,16 @@ protected virtual async Task Build(ISpecProvider? specProvider = EthereumEcdsa = new EthereumEcdsa(SpecProvider.ChainId, LogManager); DbProvider = await CreateDbProvider(); TrieStore = new TrieStore(StateDb, LogManager); - State = new StateProvider(TrieStore, DbProvider.CodeDb, LogManager); + State = new WorldState(TrieStore, DbProvider.CodeDb, LogManager); State.CreateAccount(TestItem.AddressA, (initialValues ?? InitialValue)); State.CreateAccount(TestItem.AddressB, (initialValues ?? InitialValue)); State.CreateAccount(TestItem.AddressC, (initialValues ?? InitialValue)); byte[] code = Bytes.FromHexString("0xabcd"); Keccak codeHash = Keccak.Compute(code); - State.UpdateCode(code); - State.UpdateCodeHash(TestItem.AddressA, codeHash, SpecProvider.GenesisSpec); + State.InsertCode(TestItem.AddressA, code, SpecProvider.GenesisSpec); - Storage = new StorageProvider(TrieStore, State, LogManager); - Storage.Set(new StorageCell(TestItem.AddressA, UInt256.One), Bytes.FromHexString("0xabcdef")); - Storage.Commit(); + State.Set(new StorageCell(TestItem.AddressA, UInt256.One), Bytes.FromHexString("0xabcdef")); State.Commit(SpecProvider.GenesisSpec); State.CommitTree(0); @@ -153,7 +149,7 @@ protected virtual async Task Build(ISpecProvider? specProvider = ReceiptStorage = new InMemoryReceiptStorage(); VirtualMachine virtualMachine = new(new BlockhashProvider(BlockTree, LogManager), SpecProvider, LogManager); - TxProcessor = new TransactionProcessor(SpecProvider, State, Storage, virtualMachine, LogManager); + TxProcessor = new TransactionProcessor(SpecProvider, State, virtualMachine, LogManager); BlockPreprocessorStep = new RecoverSignatures(EthereumEcdsa, TxPool, SpecProvider, LogManager); HeaderValidator = new HeaderValidator(BlockTree, Always.Valid, SpecProvider, LogManager); @@ -319,7 +315,6 @@ protected virtual IBlockProcessor CreateBlockProcessor() => NoBlockRewards.Instance, new BlockProcessor.BlockValidationTransactionsExecutor(TxProcessor, State), State, - Storage, ReceiptStorage, NullWitnessCollector.Instance, LogManager); diff --git a/src/Nethermind/Nethermind.Evm.Benchmark/EvmBenchmarks.cs b/src/Nethermind/Nethermind.Evm.Benchmark/EvmBenchmarks.cs index a2861e2652d..4eaddfd55df 100644 --- a/src/Nethermind/Nethermind.Evm.Benchmark/EvmBenchmarks.cs +++ b/src/Nethermind/Nethermind.Evm.Benchmark/EvmBenchmarks.cs @@ -30,9 +30,7 @@ public class EvmBenchmarks private BlockHeader _header = new BlockHeader(Keccak.Zero, Keccak.Zero, Address.Zero, UInt256.One, MainnetSpecProvider.IstanbulBlockNumber, Int64.MaxValue, 1UL, Bytes.Empty); private IBlockhashProvider _blockhashProvider = new TestBlockhashProvider(); private EvmState _evmState; - private StateProvider _stateProvider; - private StorageProvider _storageProvider; - private WorldState _worldState; + private WorldState _stateProvider; [GlobalSetup] public void GlobalSetup() @@ -43,14 +41,10 @@ public void GlobalSetup() TrieStore trieStore = new(new MemDb(), new OneLoggerLogManager(NullLogger.Instance)); IKeyValueStore codeDb = new MemDb(); - _stateProvider = new StateProvider(trieStore, codeDb, new OneLoggerLogManager(NullLogger.Instance)); + _stateProvider = new WorldState(trieStore, codeDb, new OneLoggerLogManager(NullLogger.Instance)); _stateProvider.CreateAccount(Address.Zero, 1000.Ether()); _stateProvider.Commit(_spec); - _storageProvider = new StorageProvider(trieStore, _stateProvider, new OneLoggerLogManager(NullLogger.Instance)); - - _worldState = new WorldState(_stateProvider, _storageProvider); - _virtualMachine = new VirtualMachine(_blockhashProvider, MainnetSpecProvider.Instance, LimboLogs.Instance); _environment = new ExecutionEnvironment @@ -65,15 +59,14 @@ public void GlobalSetup() inputData: default ); - _evmState = new EvmState(long.MaxValue, _environment, ExecutionType.Transaction, true, _worldState.TakeSnapshot(), false); + _evmState = new EvmState(long.MaxValue, _environment, ExecutionType.Transaction, true, _stateProvider.TakeSnapshot(), false); } [Benchmark] public void ExecuteCode() { - _virtualMachine.Run(_evmState, _worldState, _txTracer); + _virtualMachine.Run(_evmState, _stateProvider, _txTracer); _stateProvider.Reset(); - _storageProvider.Reset(); } } } diff --git a/src/Nethermind/Nethermind.Evm.Benchmark/MultipleUnsignedOperations.cs b/src/Nethermind/Nethermind.Evm.Benchmark/MultipleUnsignedOperations.cs index 6ea02063143..fa84e6b624f 100644 --- a/src/Nethermind/Nethermind.Evm.Benchmark/MultipleUnsignedOperations.cs +++ b/src/Nethermind/Nethermind.Evm.Benchmark/MultipleUnsignedOperations.cs @@ -29,9 +29,7 @@ public class MultipleUnsignedOperations private readonly BlockHeader _header = new(Keccak.Zero, Keccak.Zero, Address.Zero, UInt256.One, MainnetSpecProvider.MuirGlacierBlockNumber, Int64.MaxValue, 1UL, Bytes.Empty); private readonly IBlockhashProvider _blockhashProvider = new TestBlockhashProvider(); private EvmState _evmState; - private StateProvider _stateProvider; - private StorageProvider _storageProvider; - private WorldState _worldState; + private WorldState _stateProvider; private readonly byte[] _bytecode = Prepare.EvmCode .PushData(2) @@ -73,13 +71,10 @@ public void GlobalSetup() TrieStore trieStore = new(new MemDb(), new OneLoggerLogManager(NullLogger.Instance)); IKeyValueStore codeDb = new MemDb(); - _stateProvider = new StateProvider(trieStore, codeDb, new OneLoggerLogManager(NullLogger.Instance)); + _stateProvider = new WorldState(trieStore, codeDb, new OneLoggerLogManager(NullLogger.Instance)); _stateProvider.CreateAccount(Address.Zero, 1000.Ether()); _stateProvider.Commit(_spec); - _storageProvider = new StorageProvider(trieStore, _stateProvider, new OneLoggerLogManager(NullLogger.Instance)); - - _worldState = new WorldState(_stateProvider, _storageProvider); Console.WriteLine(MuirGlacier.Instance); _virtualMachine = new VirtualMachine(_blockhashProvider, MainnetSpecProvider.Instance, new OneLoggerLogManager(NullLogger.Instance)); @@ -95,21 +90,19 @@ public void GlobalSetup() inputData: default ); - _evmState = new EvmState(100_000_000L, _environment, ExecutionType.Transaction, true, _worldState.TakeSnapshot(), false); + _evmState = new EvmState(100_000_000L, _environment, ExecutionType.Transaction, true, _stateProvider.TakeSnapshot(), false); } [Benchmark] public void ExecuteCode() { - _virtualMachine.Run(_evmState, _worldState, _txTracer); + _virtualMachine.Run(_evmState, _stateProvider, _txTracer); _stateProvider.Reset(); - _storageProvider.Reset(); } [Benchmark(Baseline = true)] public void No_machine_running() { _stateProvider.Reset(); - _storageProvider.Reset(); } } diff --git a/src/Nethermind/Nethermind.Evm.Benchmark/StaticCallBenchmarks.cs b/src/Nethermind/Nethermind.Evm.Benchmark/StaticCallBenchmarks.cs index cc22b60e020..5d5254ed069 100644 --- a/src/Nethermind/Nethermind.Evm.Benchmark/StaticCallBenchmarks.cs +++ b/src/Nethermind/Nethermind.Evm.Benchmark/StaticCallBenchmarks.cs @@ -30,9 +30,7 @@ public class StaticCallBenchmarks private BlockHeader _header = new BlockHeader(Keccak.Zero, Keccak.Zero, Address.Zero, UInt256.One, MainnetSpecProvider.MuirGlacierBlockNumber, Int64.MaxValue, 1UL, Bytes.Empty); private IBlockhashProvider _blockhashProvider = new TestBlockhashProvider(); private EvmState _evmState; - private StateProvider _stateProvider; - private StorageProvider _storageProvider; - private WorldState _worldState; + private WorldState _stateProvider; public IEnumerable Bytecodes { @@ -84,13 +82,10 @@ public void GlobalSetup() TrieStore trieStore = new(new MemDb(), new OneLoggerLogManager(NullLogger.Instance)); IKeyValueStore codeDb = new MemDb(); - _stateProvider = new StateProvider(trieStore, codeDb, new OneLoggerLogManager(NullLogger.Instance)); + _stateProvider = new WorldState(trieStore, codeDb, new OneLoggerLogManager(NullLogger.Instance)); _stateProvider.CreateAccount(Address.Zero, 1000.Ether()); _stateProvider.Commit(_spec); - _storageProvider = new StorageProvider(trieStore, _stateProvider, new OneLoggerLogManager(NullLogger.Instance)); - - _worldState = new WorldState(_stateProvider, _storageProvider); Console.WriteLine(MuirGlacier.Instance); _virtualMachine = new VirtualMachine(_blockhashProvider, MainnetSpecProvider.Instance, new OneLoggerLogManager(NullLogger.Instance)); @@ -106,22 +101,20 @@ public void GlobalSetup() inputData: default ); - _evmState = new EvmState(100_000_000L, _environment, ExecutionType.Transaction, true, _worldState.TakeSnapshot(), false); + _evmState = new EvmState(100_000_000L, _environment, ExecutionType.Transaction, true, _stateProvider.TakeSnapshot(), false); } [Benchmark] public void ExecuteCode() { - _virtualMachine.Run(_evmState, _worldState, _txTracer); + _virtualMachine.Run(_evmState, _stateProvider, _txTracer); _stateProvider.Reset(); - _storageProvider.Reset(); } [Benchmark(Baseline = true)] public void No_machine_running() { _stateProvider.Reset(); - _storageProvider.Reset(); } } } diff --git a/src/Nethermind/Nethermind.Evm.Test/Eip1014Tests.cs b/src/Nethermind/Nethermind.Evm.Test/Eip1014Tests.cs index f1381af09e5..cc4bad71381 100644 --- a/src/Nethermind/Nethermind.Evm.Test/Eip1014Tests.cs +++ b/src/Nethermind/Nethermind.Evm.Test/Eip1014Tests.cs @@ -49,8 +49,7 @@ public void Test() .Create2(initCode, salt, 0).Done; TestState.CreateAccount(TestItem.AddressC, 1.Ether()); - Keccak createCodeHash = TestState.UpdateCode(createCode); - TestState.UpdateCodeHash(TestItem.AddressC, createCodeHash, Spec); + TestState.InsertCode(TestItem.AddressC, createCode, Spec); byte[] code = Prepare.EvmCode .Call(TestItem.AddressC, 50000) @@ -79,8 +78,7 @@ public void Test_out_of_gas_existing_account() TestState.CreateAccount(expectedAddress, 1.Ether()); TestState.CreateAccount(TestItem.AddressC, 1.Ether()); - Keccak createCodeHash = TestState.UpdateCode(createCode); - TestState.UpdateCodeHash(TestItem.AddressC, createCodeHash, Spec); + TestState.InsertCode(TestItem.AddressC, createCode, Spec); byte[] code = Prepare.EvmCode .Call(TestItem.AddressC, 32100) @@ -108,9 +106,7 @@ public void Test_out_of_gas_existing_account_with_storage() Address expectedAddress = ContractAddress.From(TestItem.AddressC, salt.PadLeft(32).AsSpan(), initCode.AsSpan()); TestState.CreateAccount(expectedAddress, 1.Ether()); - Storage.Set(new StorageCell(expectedAddress, 1), new byte[] { 1, 2, 3, 4, 5 }); - Storage.Commit(); - Storage.CommitTrees(0); + TestState.Set(new StorageCell(expectedAddress, 1), new byte[] { 1, 2, 3, 4, 5 }); TestState.Commit(Spec); TestState.CommitTree(0); @@ -119,8 +115,7 @@ public void Test_out_of_gas_existing_account_with_storage() TestState.CreateAccount(TestItem.AddressC, 1.Ether()); - Keccak createCodeHash = TestState.UpdateCode(createCode); - TestState.UpdateCodeHash(TestItem.AddressC, createCodeHash, Spec); + TestState.InsertCode(TestItem.AddressC, createCode, Spec); byte[] code = Prepare.EvmCode .Call(TestItem.AddressC, 32100) @@ -151,8 +146,7 @@ public void Test_out_of_gas_non_existing_account() // TestState.CreateAccount(expectedAddress, 1.Ether()); <-- non-existing TestState.CreateAccount(TestItem.AddressC, 1.Ether()); - Keccak createCodeHash = TestState.UpdateCode(createCode); - TestState.UpdateCodeHash(TestItem.AddressC, createCodeHash, Spec); + TestState.InsertCode(TestItem.AddressC, createCode, Spec); byte[] code = Prepare.EvmCode .Call(TestItem.AddressC, 32100) @@ -185,8 +179,7 @@ public void Examples_from_eip_spec_are_executed_correctly(string addressHex, str .Create2(initCode, salt, 0).Done; TestState.CreateAccount(TestItem.AddressC, 1.Ether()); - Keccak createCodeHash = TestState.UpdateCode(createCode); - TestState.UpdateCodeHash(TestItem.AddressC, createCodeHash, Spec); + TestState.InsertCode(TestItem.AddressC, createCode, Spec); byte[] code = Prepare.EvmCode .Call(TestItem.AddressC, 50000) diff --git a/src/Nethermind/Nethermind.Evm.Test/Eip1052Tests.cs b/src/Nethermind/Nethermind.Evm.Test/Eip1052Tests.cs index 62604295022..a809b73296b 100644 --- a/src/Nethermind/Nethermind.Evm.Test/Eip1052Tests.cs +++ b/src/Nethermind/Nethermind.Evm.Test/Eip1052Tests.cs @@ -111,8 +111,7 @@ public void Addresses_are_trimmed_properly() addressWithGarbage[11] = 88; TestState.CreateAccount(TestItem.AddressC, 1.Ether()); - Keccak codehash = Keccak.Compute("some code"); - TestState.UpdateCodeHash(TestItem.AddressC, codehash, Spec); + TestState.InsertCode(TestItem.AddressC, "some code"u8.ToArray(), Spec); byte[] code = Prepare.EvmCode .PushData(TestItem.AddressC) @@ -126,6 +125,7 @@ public void Addresses_are_trimmed_properly() .Done; Execute(code); + Keccak codehash = Keccak.Compute("some code"); AssertStorage(0, codehash.Bytes); AssertStorage(1, codehash.Bytes); } @@ -138,8 +138,7 @@ public void Self_destructed_returns_zero() .Op(Instruction.SELFDESTRUCT).Done; TestState.CreateAccount(TestItem.AddressC, 1.Ether()); - Keccak selfDestructCodeHash = TestState.UpdateCode(selfDestructCode); - TestState.UpdateCodeHash(TestItem.AddressC, selfDestructCodeHash, Spec); + TestState.InsertCode(TestItem.AddressC, selfDestructCode, Spec); byte[] code = Prepare.EvmCode .Call(TestItem.AddressC, 50000) @@ -150,7 +149,7 @@ public void Self_destructed_returns_zero() .Done; Execute(code); - AssertStorage(0, selfDestructCodeHash); + AssertStorage(0, Keccak.Compute(selfDestructCode)); } [Test] @@ -165,12 +164,10 @@ public void Self_destructed_and_reverted_returns_code_hash() .Op(Instruction.SELFDESTRUCT).Done; TestState.CreateAccount(TestItem.AddressD, 1.Ether()); - Keccak selfDestructCodeHash = TestState.UpdateCode(selfDestructCode); - TestState.UpdateCodeHash(TestItem.AddressD, selfDestructCodeHash, Spec); + TestState.InsertCode(TestItem.AddressD, selfDestructCode, Spec); TestState.CreateAccount(TestItem.AddressC, 1.Ether()); - Keccak revertCodeHash = TestState.UpdateCode(callAndRevertCode); - TestState.UpdateCodeHash(TestItem.AddressC, revertCodeHash, Spec); + TestState.InsertCode(TestItem.AddressC, callAndRevertCode, Spec); byte[] code = Prepare.EvmCode .Call(TestItem.AddressC, 50000) @@ -181,7 +178,7 @@ public void Self_destructed_and_reverted_returns_code_hash() .Done; Execute(code); - AssertStorage(0, selfDestructCodeHash); + AssertStorage(0, Keccak.Compute(selfDestructCode)); } [Test] @@ -241,8 +238,7 @@ public void Create_and_revert_returns_zero() .Op(Instruction.REVERT).Done; TestState.CreateAccount(TestItem.AddressC, 1.Ether()); - Keccak createCodeHash = TestState.UpdateCode(createCode); - TestState.UpdateCodeHash(TestItem.AddressC, createCodeHash, Spec); + TestState.InsertCode(TestItem.AddressC, createCode, Spec); byte[] code = Prepare.EvmCode .Call(TestItem.AddressC, 50000) @@ -269,8 +265,7 @@ public void Create_returns_code_hash() .Create(initCode, 0).Done; TestState.CreateAccount(TestItem.AddressC, 1.Ether()); - Keccak createCodeHash = TestState.UpdateCode(createCode); - TestState.UpdateCodeHash(TestItem.AddressC, createCodeHash, Spec); + TestState.InsertCode(TestItem.AddressC, createCode, Spec); byte[] code = Prepare.EvmCode .Call(TestItem.AddressC, 50000) diff --git a/src/Nethermind/Nethermind.Evm.Test/Eip1153Tests.cs b/src/Nethermind/Nethermind.Evm.Test/Eip1153Tests.cs index 2432e86973f..a2d702109ba 100644 --- a/src/Nethermind/Nethermind.Evm.Test/Eip1153Tests.cs +++ b/src/Nethermind/Nethermind.Evm.Test/Eip1153Tests.cs @@ -161,8 +161,7 @@ public void tload_from_different_contract() .Done; TestState.CreateAccount(TestItem.AddressD, 1.Ether()); - Keccak contractCodeHash = TestState.UpdateCode(contractCode); - TestState.UpdateCodeHash(TestItem.AddressD, contractCodeHash, Spec); + TestState.InsertCode(TestItem.AddressD, contractCode, Spec); // Store 8 at index 1 and call contract from above // Return the result received from the contract @@ -210,8 +209,7 @@ public void tload_from_reentrant_call() .Done; TestState.CreateAccount(TestItem.AddressD, 1.Ether()); - Keccak contractCodeHash = TestState.UpdateCode(contractCode); - TestState.UpdateCodeHash(TestItem.AddressD, contractCodeHash, Spec); + TestState.InsertCode(TestItem.AddressD, contractCode, Spec); // Return the result received from the contract byte[] code = Prepare.EvmCode @@ -257,8 +255,7 @@ public void tstore_from_reentrant_call() .Done; TestState.CreateAccount(TestItem.AddressD, 1.Ether()); - Keccak contractCodeHash = TestState.UpdateCode(contractCode); - TestState.UpdateCodeHash(TestItem.AddressD, contractCodeHash, Spec); + TestState.InsertCode(TestItem.AddressD, contractCode, Spec); // Return the result received from the contract byte[] code = Prepare.EvmCode @@ -303,8 +300,7 @@ public void tstore_from_reentrant_call_read_by_caller() .Done; TestState.CreateAccount(TestItem.AddressD, 1.Ether()); - Keccak contractCodeHash = TestState.UpdateCode(contractCode); - TestState.UpdateCodeHash(TestItem.AddressD, contractCodeHash, Spec); + TestState.InsertCode(TestItem.AddressD, contractCode, Spec); // Return the result received from the contract byte[] code = Prepare.EvmCode @@ -350,8 +346,7 @@ public void revert_resets_transient_state() .Done; TestState.CreateAccount(TestItem.AddressD, 1.Ether()); - Keccak contractCodeHash = TestState.UpdateCode(contractCode); - TestState.UpdateCodeHash(TestItem.AddressD, contractCodeHash, Spec); + TestState.InsertCode(TestItem.AddressD, contractCode, Spec); // Return the result received from the contract byte[] code = Prepare.EvmCode @@ -399,8 +394,7 @@ public void revert_resets_all_transient_state() .Done; TestState.CreateAccount(TestItem.AddressD, 1.Ether()); - Keccak contractCodeHash = TestState.UpdateCode(contractCode); - TestState.UpdateCodeHash(TestItem.AddressD, contractCodeHash, Spec); + TestState.InsertCode(TestItem.AddressD, contractCode, Spec); // Return the result received from the contract byte[] code = Prepare.EvmCode @@ -485,8 +479,7 @@ public void revert_resets_transient_state_from_succesful_calls() .Done; TestState.CreateAccount(TestItem.AddressD, 1.Ether()); - Keccak contractCodeHash = TestState.UpdateCode(contractCode); - TestState.UpdateCodeHash(TestItem.AddressD, contractCodeHash, Spec); + TestState.InsertCode(TestItem.AddressD, contractCode, Spec); // Return the result received from the contract byte[] code = Prepare.EvmCode @@ -517,8 +510,7 @@ public void tstore_in_staticcall(Instruction callType, int expectedResult) .Done; TestState.CreateAccount(TestItem.AddressD, 1.Ether()); - Keccak contractCodeHash = TestState.UpdateCode(contractCode); - TestState.UpdateCodeHash(TestItem.AddressD, contractCodeHash, Spec); + TestState.InsertCode(TestItem.AddressD, contractCode, Spec); // Return the result received from the contract (1 if successful) byte[] code = Prepare.EvmCode @@ -566,8 +558,7 @@ public void tstore_from_static_reentrant_call(Instruction callType, int expected .Done; TestState.CreateAccount(TestItem.AddressD, 1.Ether()); - Keccak contractCodeHash = TestState.UpdateCode(contractCode); - TestState.UpdateCodeHash(TestItem.AddressD, contractCodeHash, Spec); + TestState.InsertCode(TestItem.AddressD, contractCode, Spec); // Return the result received from the contract byte[] code = Prepare.EvmCode @@ -655,8 +646,7 @@ public void tstore_from_nonstatic_reentrant_call_with_static_intermediary(Instru .Done; TestState.CreateAccount(TestItem.AddressD, 1.Ether()); - Keccak contractCodeHash = TestState.UpdateCode(contractCode); - TestState.UpdateCodeHash(TestItem.AddressD, contractCodeHash, Spec); + TestState.InsertCode(TestItem.AddressD, contractCode, Spec); // Return the result received from the contract byte[] code = Prepare.EvmCode @@ -682,8 +672,7 @@ public void tstore_in_delegatecall(Instruction callType, int expectedResult) .Done; TestState.CreateAccount(TestItem.AddressD, 1.Ether()); - Keccak contractCodeHash = TestState.UpdateCode(contractCode); - TestState.UpdateCodeHash(TestItem.AddressD, contractCodeHash, Spec); + TestState.InsertCode(TestItem.AddressD, contractCode, Spec); byte[] code = Prepare.EvmCode .StoreDataInTransientStorage(1, 7) @@ -717,8 +706,7 @@ public void tload_in_delegatecall(Instruction callType, int expectedResult) .Done; TestState.CreateAccount(TestItem.AddressD, 1.Ether()); - Keccak contractCodeHash = TestState.UpdateCode(contractCode); - TestState.UpdateCodeHash(TestItem.AddressD, contractCodeHash, Spec); + TestState.InsertCode(TestItem.AddressD, contractCode, Spec); byte[] code = Prepare.EvmCode .StoreDataInTransientStorage(1, 7) @@ -820,8 +808,7 @@ public void tload_from_static_reentrant_call(Instruction callType, int expectedR .Done; TestState.CreateAccount(TestItem.AddressD, 1.Ether()); - Keccak contractCodeHash = TestState.UpdateCode(contractCode); - TestState.UpdateCodeHash(TestItem.AddressD, contractCodeHash, Spec); + TestState.InsertCode(TestItem.AddressD, contractCode, Spec); // Return the result received from the contract byte[] code = Prepare.EvmCode diff --git a/src/Nethermind/Nethermind.Evm.Test/Eip1283Tests.cs b/src/Nethermind/Nethermind.Evm.Test/Eip1283Tests.cs index d7670f60c58..45ebf69d97f 100644 --- a/src/Nethermind/Nethermind.Evm.Test/Eip1283Tests.cs +++ b/src/Nethermind/Nethermind.Evm.Test/Eip1283Tests.cs @@ -38,8 +38,7 @@ public class Eip1283Tests : VirtualMachineTestsBase public void Test(string codeHex, long gasUsed, long refund, byte originalValue) { TestState.CreateAccount(Recipient, 0); - Storage.Set(new StorageCell(Recipient, 0), new[] { originalValue }); - Storage.Commit(); + TestState.Set(new StorageCell(Recipient, 0), new[] { originalValue }); TestState.Commit(RopstenSpecProvider.Instance.GenesisSpec); TestAllTracerWithOutput receipt = Execute(Bytes.FromHexString(codeHex)); diff --git a/src/Nethermind/Nethermind.Evm.Test/Eip1884Tests.cs b/src/Nethermind/Nethermind.Evm.Test/Eip1884Tests.cs index 63e1ac2e220..85dc4dd5a27 100644 --- a/src/Nethermind/Nethermind.Evm.Test/Eip1884Tests.cs +++ b/src/Nethermind/Nethermind.Evm.Test/Eip1884Tests.cs @@ -27,13 +27,11 @@ public void after_istanbul_selfbalance_opcode_puts_current_address_balance_onto_ .Op(Instruction.SSTORE) .Done; - Keccak codeHash = TestState.UpdateCode(contractCode); - TestState.CreateAccount(TestItem.AddressC, 1.Ether()); - TestState.UpdateCodeHash(TestItem.AddressC, codeHash, Spec); + TestState.InsertCode(TestItem.AddressC, contractCode, Spec); TestState.CreateAccount(TestItem.AddressD, 1.Ether()); - TestState.UpdateCodeHash(TestItem.AddressD, codeHash, Spec); + TestState.InsertCode(TestItem.AddressD, contractCode, Spec); byte[] code = Prepare.EvmCode .Call(TestItem.AddressC, 50000) diff --git a/src/Nethermind/Nethermind.Evm.Test/Eip2200Tests.cs b/src/Nethermind/Nethermind.Evm.Test/Eip2200Tests.cs index 175f3ca62d8..292ad2b8e03 100644 --- a/src/Nethermind/Nethermind.Evm.Test/Eip2200Tests.cs +++ b/src/Nethermind/Nethermind.Evm.Test/Eip2200Tests.cs @@ -38,8 +38,7 @@ public class Eip2200Tests : VirtualMachineTestsBase public void Test(string codeHex, long gasUsed, long refund, byte originalValue) { TestState.CreateAccount(Recipient, 0); - Storage.Set(new StorageCell(Recipient, 0), new[] { originalValue }); - Storage.Commit(); + TestState.Set(new StorageCell(Recipient, 0), new[] { originalValue }); TestState.Commit(RopstenSpecProvider.Instance.GenesisSpec); TestAllTracerWithOutput receipt = Execute(Bytes.FromHexString(codeHex)); @@ -67,8 +66,7 @@ public void Test(string codeHex, long gasUsed, long refund, byte originalValue) public void Test_when_gas_at_stipend(string codeHex, long gasUsed, long refund, byte originalValue, bool outOfGasExpected) { TestState.CreateAccount(Recipient, 0); - Storage.Set(new StorageCell(Recipient, 0), new[] { originalValue }); - Storage.Commit(); + TestState.Set(new StorageCell(Recipient, 0), new[] { originalValue }); TestState.Commit(RopstenSpecProvider.Instance.GenesisSpec); TestAllTracerWithOutput receipt = Execute(BlockNumber, 21000 + gasUsed + (2300 - 800), Bytes.FromHexString(codeHex)); @@ -80,8 +78,7 @@ public void Test_when_gas_at_stipend(string codeHex, long gasUsed, long refund, public void Test_when_gas_just_above_stipend(string codeHex, long gasUsed, long refund, byte originalValue) { TestState.CreateAccount(Recipient, 0); - Storage.Set(new StorageCell(Recipient, 0), new[] { originalValue }); - Storage.Commit(); + TestState.Set(new StorageCell(Recipient, 0), new[] { originalValue }); TestState.Commit(RopstenSpecProvider.Instance.GenesisSpec); TestAllTracerWithOutput receipt = Execute(BlockNumber, 21000 + gasUsed + (2301 - 800), Bytes.FromHexString(codeHex)); @@ -93,8 +90,7 @@ public void Test_when_gas_just_above_stipend(string codeHex, long gasUsed, long public void Test_when_gas_just_below_stipend(string codeHex, long gasUsed, long refund, byte originalValue) { TestState.CreateAccount(Recipient, 0); - Storage.Set(new StorageCell(Recipient, 0), new[] { originalValue }); - Storage.Commit(); + TestState.Set(new StorageCell(Recipient, 0), new[] { originalValue }); TestState.Commit(RopstenSpecProvider.Instance.GenesisSpec); TestAllTracerWithOutput receipt = Execute(BlockNumber, 21000 + gasUsed + (2299 - 800), Bytes.FromHexString(codeHex)); diff --git a/src/Nethermind/Nethermind.Evm.Test/Eip3198BaseFeeTests.cs b/src/Nethermind/Nethermind.Evm.Test/Eip3198BaseFeeTests.cs index 026c91e7a82..218f7a27a55 100644 --- a/src/Nethermind/Nethermind.Evm.Test/Eip3198BaseFeeTests.cs +++ b/src/Nethermind/Nethermind.Evm.Test/Eip3198BaseFeeTests.cs @@ -30,7 +30,7 @@ public class Eip3198BaseFeeTests : VirtualMachineTestsBase [TestCase(false, 0, false)] public void Base_fee_opcode_should_return_expected_results(bool eip3198Enabled, int baseFee, bool send1559Tx) { - _processor = new TransactionProcessor(SpecProvider, TestState, Storage, Machine, LimboLogs.Instance); + _processor = new TransactionProcessor(SpecProvider, TestState, Machine, LimboLogs.Instance); byte[] code = Prepare.EvmCode .Op(Instruction.BASEFEE) .PushData(0) diff --git a/src/Nethermind/Nethermind.Evm.Test/Eip3529RefundsTests.cs b/src/Nethermind/Nethermind.Evm.Test/Eip3529RefundsTests.cs index 48eb873a08d..80aa0346126 100644 --- a/src/Nethermind/Nethermind.Evm.Test/Eip3529RefundsTests.cs +++ b/src/Nethermind/Nethermind.Evm.Test/Eip3529RefundsTests.cs @@ -72,11 +72,15 @@ public void After_introducing_eip3529(string codeHex, long gasUsed, long refund, private void Test(string codeHex, long gasUsed, long refund, byte originalValue, bool eip3529Enabled) { - TestState.CreateAccount(Recipient, 0); - Storage.Set(new StorageCell(Recipient, 0), new[] { originalValue }); - Storage.Commit(); + // the account value = 1.Ether() here because you cannot set a storageRoot for an empty account. + // EmptyAccount => Balance.IsZero && Nonce == _accountStartNonce && CodeHash == Keccak.OfAnEmptyString + // earlier it used to work - because the cache mapping address:storageTree was never cleared on account of + // Storage.CommitTrees() not being called. But now the WorldState.CommitTrees is called inside PrepareTx, + // which also calls Storage.CommitTrees, clearing the cache. + TestState.CreateAccount(Recipient, 1.Ether()); + TestState.Set(new StorageCell(Recipient, 0), new[] { originalValue }); TestState.Commit(eip3529Enabled ? London.Instance : Berlin.Instance); - _processor = new TransactionProcessor(SpecProvider, TestState, Storage, Machine, LimboLogs.Instance); + _processor = new TransactionProcessor(SpecProvider, TestState, Machine, LimboLogs.Instance); long blockNumber = eip3529Enabled ? MainnetSpecProvider.LondonBlockNumber : MainnetSpecProvider.LondonBlockNumber - 1; (Block block, Transaction transaction) = PrepareTx(blockNumber, 100000, Bytes.FromHexString(codeHex)); diff --git a/src/Nethermind/Nethermind.Evm.Test/Eip3541Tests.cs b/src/Nethermind/Nethermind.Evm.Test/Eip3541Tests.cs index f3c254e3677..bef8582a4be 100644 --- a/src/Nethermind/Nethermind.Evm.Test/Eip3541Tests.cs +++ b/src/Nethermind/Nethermind.Evm.Test/Eip3541Tests.cs @@ -100,7 +100,7 @@ void DeployCodeAndAssertTx(string code, bool eip3541Enabled, ContractDeployment break; } - _processor = new TransactionProcessor(SpecProvider, TestState, Storage, Machine, LimboLogs.Instance); + _processor = new TransactionProcessor(SpecProvider, TestState, Machine, LimboLogs.Instance); long blockNumber = eip3541Enabled ? MainnetSpecProvider.LondonBlockNumber : MainnetSpecProvider.LondonBlockNumber - 1; (Block block, Transaction transaction) = PrepareTx(blockNumber, 100000, createContract); diff --git a/src/Nethermind/Nethermind.Evm.Test/Eip3860Tests.cs b/src/Nethermind/Nethermind.Evm.Test/Eip3860Tests.cs index df053a71c39..f626f3ca333 100644 --- a/src/Nethermind/Nethermind.Evm.Test/Eip3860Tests.cs +++ b/src/Nethermind/Nethermind.Evm.Test/Eip3860Tests.cs @@ -35,8 +35,7 @@ public void Test_EIP_3860_GasCost_Create(string createCode, bool eip3860Enabled, .Done; TestState.CreateAccount(TestItem.AddressC, 1.Ether()); - Keccak createCodeHash = TestState.UpdateCode(byteCode); - TestState.UpdateCodeHash(TestItem.AddressC, createCodeHash, Spec); + TestState.InsertCode(TestItem.AddressC, byteCode, Spec); byte[] callCode = Prepare.EvmCode.Call(TestItem.AddressC, 100000).Done; @@ -58,8 +57,7 @@ public void Test_EIP_3860_InitCode_Create_Exceeds_Limit(string createCode) : Prepare.EvmCode.FromCode(dataPush.ToString("X") + dataLenghtHex + createCode).Done; TestState.CreateAccount(TestItem.AddressC, 1.Ether()); - Keccak createCodeHash = TestState.UpdateCode(evmCode); - TestState.UpdateCodeHash(TestItem.AddressC, createCodeHash, Spec); + TestState.InsertCode(TestItem.AddressC, evmCode, Spec); const int contractCreationGasLimit = 50000; byte[] callCode = Prepare.EvmCode.Call(TestItem.AddressC, contractCreationGasLimit).Done; diff --git a/src/Nethermind/Nethermind.Evm.Test/StorageAndSelfDestructTests.cs b/src/Nethermind/Nethermind.Evm.Test/StorageAndSelfDestructTests.cs index d79fc2e4a66..93328991347 100644 --- a/src/Nethermind/Nethermind.Evm.Test/StorageAndSelfDestructTests.cs +++ b/src/Nethermind/Nethermind.Evm.Test/StorageAndSelfDestructTests.cs @@ -357,12 +357,9 @@ public void Destroy_restore_store_different_cells_previously_existing() //TestState.CommitTree(0); TestState.CreateAccount(deploymentAddress, UInt256.One); - Keccak codeHash = TestState.UpdateCode(contractCode); - TestState.UpdateCodeHash(deploymentAddress, codeHash, MuirGlacier.Instance); + TestState.InsertCode(deploymentAddress, contractCode, MuirGlacier.Instance); - Storage.Set(new StorageCell(deploymentAddress, 7), new byte[] { 7 }); - Storage.Commit(); - Storage.CommitTrees(0); + TestState.Set(new StorageCell(deploymentAddress, 7), new byte[] { 7 }); TestState.Commit(MuirGlacier.Instance); TestState.CommitTree(0); diff --git a/src/Nethermind/Nethermind.Evm.Test/Tracing/GasEstimationTests.cs b/src/Nethermind/Nethermind.Evm.Test/Tracing/GasEstimationTests.cs index c91e53105ac..b7c0f6d2f32 100644 --- a/src/Nethermind/Nethermind.Evm.Test/Tracing/GasEstimationTests.cs +++ b/src/Nethermind/Nethermind.Evm.Test/Tracing/GasEstimationTests.cs @@ -236,7 +236,7 @@ private class TestEnvironment public ISpecProvider _specProvider; public IEthereumEcdsa _ethereumEcdsa; public TransactionProcessor _transactionProcessor; - public IStateProvider _stateProvider; + public IWorldState _stateProvider; public EstimateGasTracer tracer; public GasEstimator estimator; @@ -245,14 +245,13 @@ public TestEnvironment() _specProvider = MainnetSpecProvider.Instance; MemDb stateDb = new(); TrieStore trieStore = new(stateDb, LimboLogs.Instance); - _stateProvider = new StateProvider(trieStore, new MemDb(), LimboLogs.Instance); + _stateProvider = new WorldState(trieStore, new MemDb(), LimboLogs.Instance); _stateProvider.CreateAccount(TestItem.AddressA, 1.Ether()); _stateProvider.Commit(_specProvider.GenesisSpec); _stateProvider.CommitTree(0); - StorageProvider storageProvider = new(trieStore, _stateProvider, LimboLogs.Instance); VirtualMachine virtualMachine = new(TestBlockhashProvider.Instance, _specProvider, LimboLogs.Instance); - _transactionProcessor = new TransactionProcessor(_specProvider, _stateProvider, storageProvider, virtualMachine, LimboLogs.Instance); + _transactionProcessor = new TransactionProcessor(_specProvider, _stateProvider, virtualMachine, LimboLogs.Instance); _ethereumEcdsa = new EthereumEcdsa(_specProvider.ChainId, LimboLogs.Instance); tracer = new(); diff --git a/src/Nethermind/Nethermind.Evm.Test/Tracing/GethLikeTxTracerTests.cs b/src/Nethermind/Nethermind.Evm.Test/Tracing/GethLikeTxTracerTests.cs index 597030206f4..9345b3b9e78 100644 --- a/src/Nethermind/Nethermind.Evm.Test/Tracing/GethLikeTxTracerTests.cs +++ b/src/Nethermind/Nethermind.Evm.Test/Tracing/GethLikeTxTracerTests.cs @@ -127,8 +127,7 @@ public void Can_trace_call_depth() .Done; TestState.CreateAccount(TestItem.AddressC, 1.Ether()); - Keccak createCodeHash = TestState.UpdateCode(createCode); - TestState.UpdateCodeHash(TestItem.AddressC, createCodeHash, Spec); + TestState.InsertCode(TestItem.AddressC, createCode, Spec); byte[] code = Prepare.EvmCode .Call(TestItem.AddressC, 50000) @@ -141,7 +140,7 @@ public void Can_trace_call_depth() 1, 1, 1, 1, 1, 1, 1, 1, // STACK FOR CALL 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, // CALL 3, 3, 3, 3, 3, 3, // CREATE - 2, // STOP + 2, // STOP 1, // STOP }; @@ -168,8 +167,7 @@ public void Stack_is_cleared_and_restored_when_moving_between_call_levels() .Done; TestState.CreateAccount(TestItem.AddressC, 1.Ether()); - Keccak createCodeHash = TestState.UpdateCode(createCode); - TestState.UpdateCodeHash(TestItem.AddressC, createCodeHash, Spec); + TestState.InsertCode(TestItem.AddressC, createCode, Spec); byte[] code = Prepare.EvmCode .PushData(SampleHexData1) // just to test if stack is restored @@ -178,7 +176,7 @@ public void Stack_is_cleared_and_restored_when_moving_between_call_levels() .Done; GethLikeTxTrace trace = ExecuteAndTrace(code); - /* depths + /* depths { 1, 1, 1, 1, 1, 1, 1, 1, 1, // SAMPLE STACK + STACK FOR CALL [0..8] 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2 // SAMPLE STACK + CALL [9..19] @@ -213,8 +211,7 @@ public void Memory_is_cleared_and_restored_when_moving_between_call_levels() .Done; TestState.CreateAccount(TestItem.AddressC, 1.Ether()); - Keccak createCodeHash = TestState.UpdateCode(createCode); - TestState.UpdateCodeHash(TestItem.AddressC, createCodeHash, Spec); + TestState.InsertCode(TestItem.AddressC, createCode, Spec); byte[] code = Prepare.EvmCode .StoreDataInMemory(64, SampleHexData2.PadLeft(64, '0')) // just to test if memory is restored @@ -223,7 +220,7 @@ public void Memory_is_cleared_and_restored_when_moving_between_call_levels() .Done; GethLikeTxTrace trace = ExecuteAndTrace(code); - /* depths + /* depths { 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 // MEMORY + STACK FOR CALL [0..10] 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2 // MEMORY + CALL [11..23] @@ -258,8 +255,7 @@ public void Storage_is_cleared_and_restored_when_moving_between_call_levels() .Done; TestState.CreateAccount(TestItem.AddressC, 1.Ether()); - Keccak createCodeHash = TestState.UpdateCode(createCode); - TestState.UpdateCodeHash(TestItem.AddressC, createCodeHash, Spec); + TestState.InsertCode(TestItem.AddressC, createCode, Spec); byte[] code = Prepare.EvmCode .PersistData("0x2", HexZero) // just to test if storage is restored @@ -269,7 +265,7 @@ public void Storage_is_cleared_and_restored_when_moving_between_call_levels() .Done; GethLikeTxTrace trace = ExecuteAndTrace(code); - /* depths + /* depths { 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 // 2x SSTORE + STACK FOR CALL [0..13] 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2 // SSTORE + CALL [14..26] diff --git a/src/Nethermind/Nethermind.Evm.Test/Tracing/ParityLikeTxTracerTests.cs b/src/Nethermind/Nethermind.Evm.Test/Tracing/ParityLikeTxTracerTests.cs index fa9d230226c..28120bc5be1 100644 --- a/src/Nethermind/Nethermind.Evm.Test/Tracing/ParityLikeTxTracerTests.cs +++ b/src/Nethermind/Nethermind.Evm.Test/Tracing/ParityLikeTxTracerTests.cs @@ -231,8 +231,7 @@ public void Can_trace_nested_calls() .Done; TestState.CreateAccount(TestItem.AddressC, 1.Ether()); - Keccak createCodeHash = TestState.UpdateCode(createCode); - TestState.UpdateCodeHash(TestItem.AddressC, createCodeHash, Spec); + TestState.InsertCode(TestItem.AddressC, createCode, Spec); byte[] code = Prepare.EvmCode .Call(TestItem.AddressC, 50000) @@ -271,8 +270,7 @@ public void Can_trace_delegate_calls() .Done; TestState.CreateAccount(TestItem.AddressC, 1.Ether()); - Keccak createCodeHash = TestState.UpdateCode(createCode); - TestState.UpdateCodeHash(TestItem.AddressC, createCodeHash, Spec); + TestState.InsertCode(TestItem.AddressC, createCode, Spec); byte[] code = Prepare.EvmCode .DelegateCall(TestItem.AddressC, 50000) @@ -308,8 +306,7 @@ public void Can_trace_call_code_calls() .Done; TestState.CreateAccount(TestItem.AddressC, 1.Ether()); - Keccak createCodeHash = TestState.UpdateCode(createCode); - TestState.UpdateCodeHash(TestItem.AddressC, createCodeHash, Spec); + TestState.InsertCode(TestItem.AddressC, createCode, Spec); byte[] code = Prepare.EvmCode .CallCode(TestItem.AddressC, 50000) @@ -344,8 +341,7 @@ public void Can_trace_call_code_calls_with_large_data_offset() .Done; TestState.CreateAccount(TestItem.AddressC, 1.Ether()); - Keccak createCodeHash = TestState.UpdateCode(createCode); - TestState.UpdateCodeHash(TestItem.AddressC, createCodeHash, Spec); + TestState.InsertCode(TestItem.AddressC, createCode, Spec); byte[] code = Prepare.EvmCode .CallCode(TestItem.AddressC, 50000, UInt256.MaxValue, ulong.MaxValue) @@ -372,8 +368,7 @@ public void Can_trace_a_failing_static_call() .Done; TestState.CreateAccount(TestItem.AddressC, 1.Ether()); - Keccak createCodeHash = TestState.UpdateCode(createCode); - TestState.UpdateCodeHash(TestItem.AddressC, createCodeHash, Spec); + TestState.InsertCode(TestItem.AddressC, createCode, Spec); byte[] code = Prepare.EvmCode .CallWithValue(TestItem.AddressC, 50000, 1000000.Ether()) @@ -551,8 +546,7 @@ public void Can_trace_static_calls() .Done; TestState.CreateAccount(TestItem.AddressC, 1.Ether()); - Keccak createCodeHash = TestState.UpdateCode(createCode); - TestState.UpdateCodeHash(TestItem.AddressC, createCodeHash, Spec); + TestState.InsertCode(TestItem.AddressC, createCode, Spec); byte[] code = Prepare.EvmCode .StaticCall(TestItem.AddressC, 50000) @@ -603,8 +597,7 @@ public void Can_ignore_precompile_calls_in_contract() .Done; TestState.CreateAccount(TestItem.AddressC, 1.Ether()); - Keccak createCodeHash = TestState.UpdateCode(deployedCode); - TestState.UpdateCodeHash(TestItem.AddressC, createCodeHash, Spec); + TestState.InsertCode(TestItem.AddressC, deployedCode, Spec); byte[] code = Prepare.EvmCode .Call(IdentityPrecompile.Instance.Address, 50000) @@ -653,8 +646,7 @@ public void Can_trace_same_level_calls() .Done; TestState.CreateAccount(TestItem.AddressC, 1.Ether()); - Keccak createCodeHash = TestState.UpdateCode(createCode); - TestState.UpdateCodeHash(TestItem.AddressC, createCodeHash, Spec); + TestState.InsertCode(TestItem.AddressC, createCode, Spec); byte[] code = Prepare.EvmCode .Call(TestItem.AddressC, 40000) @@ -710,8 +702,7 @@ public void Can_trace_storage_changes() .Done; TestState.CreateAccount(TestItem.AddressC, 1.Ether()); - Keccak createCodeHash = TestState.UpdateCode(createCode); - TestState.UpdateCodeHash(TestItem.AddressC, createCodeHash, Spec); + TestState.InsertCode(TestItem.AddressC, createCode, Spec); byte[] code = Prepare.EvmCode .PersistData("0x2", SampleHexData1) @@ -749,8 +740,7 @@ public void Can_trace_code_changes() .Done; TestState.CreateAccount(TestItem.AddressC, 1.Ether()); - Keccak createCodeHash = TestState.UpdateCode(createCode); - TestState.UpdateCodeHash(TestItem.AddressC, createCodeHash, Spec); + TestState.InsertCode(TestItem.AddressC, createCode, Spec); byte[] code = Prepare.EvmCode .PersistData("0x2", SampleHexData1) diff --git a/src/Nethermind/Nethermind.Evm.Test/TransactionProcessorFeeTests.cs b/src/Nethermind/Nethermind.Evm.Test/TransactionProcessorFeeTests.cs index 584917c1d82..0ac0d44fa5d 100644 --- a/src/Nethermind/Nethermind.Evm.Test/TransactionProcessorFeeTests.cs +++ b/src/Nethermind/Nethermind.Evm.Test/TransactionProcessorFeeTests.cs @@ -26,7 +26,7 @@ public class TransactionProcessorFeeTests private TestSpecProvider _specProvider; private IEthereumEcdsa _ethereumEcdsa; private TransactionProcessor _transactionProcessor; - private IStateProvider _stateProvider; + private IWorldState _stateProvider; private OverridableReleaseSpec _spec; [SetUp] @@ -37,14 +37,13 @@ public void Setup() TrieStore trieStore = new(new MemDb(), LimboLogs.Instance); - _stateProvider = new StateProvider(trieStore, new MemDb(), LimboLogs.Instance); + _stateProvider = new WorldState(trieStore, new MemDb(), LimboLogs.Instance); _stateProvider.CreateAccount(TestItem.AddressA, 1.Ether()); _stateProvider.Commit(_specProvider.GenesisSpec); _stateProvider.CommitTree(0); - StorageProvider storageProvider = new(trieStore, _stateProvider, LimboLogs.Instance); VirtualMachine virtualMachine = new(TestBlockhashProvider.Instance, _specProvider, LimboLogs.Instance); - _transactionProcessor = new TransactionProcessor(_specProvider, _stateProvider, storageProvider, virtualMachine, + _transactionProcessor = new TransactionProcessor(_specProvider, _stateProvider, virtualMachine, LimboLogs.Instance); _ethereumEcdsa = new EthereumEcdsa(_specProvider.ChainId, LimboLogs.Instance); } diff --git a/src/Nethermind/Nethermind.Evm.Test/TransactionProcessorTests.cs b/src/Nethermind/Nethermind.Evm.Test/TransactionProcessorTests.cs index 36bbdf5eece..bfb4470881d 100644 --- a/src/Nethermind/Nethermind.Evm.Test/TransactionProcessorTests.cs +++ b/src/Nethermind/Nethermind.Evm.Test/TransactionProcessorTests.cs @@ -37,7 +37,7 @@ public class TransactionProcessorTests private readonly ISpecProvider _specProvider; private IEthereumEcdsa _ethereumEcdsa; private TransactionProcessor _transactionProcessor; - private IStateProvider _stateProvider; + private IWorldState _stateProvider; public TransactionProcessorTests(bool eip155Enabled) { @@ -50,14 +50,13 @@ public void Setup() { MemDb stateDb = new(); TrieStore trieStore = new(stateDb, LimboLogs.Instance); - _stateProvider = new StateProvider(trieStore, new MemDb(), LimboLogs.Instance); + _stateProvider = new WorldState(trieStore, new MemDb(), LimboLogs.Instance); _stateProvider.CreateAccount(TestItem.AddressA, 1.Ether()); _stateProvider.Commit(_specProvider.GenesisSpec); _stateProvider.CommitTree(0); - StorageProvider storageProvider = new(trieStore, _stateProvider, LimboLogs.Instance); VirtualMachine virtualMachine = new(TestBlockhashProvider.Instance, _specProvider, LimboLogs.Instance); - _transactionProcessor = new TransactionProcessor(_specProvider, _stateProvider, storageProvider, virtualMachine, LimboLogs.Instance); + _transactionProcessor = new TransactionProcessor(_specProvider, _stateProvider, virtualMachine, LimboLogs.Instance); _ethereumEcdsa = new EthereumEcdsa(_specProvider.ChainId, LimboLogs.Instance); } @@ -588,7 +587,7 @@ public void Balance_is_changed_on_buildup_and_restored() Transaction tx = Build.A.Transaction.SignedAndResolved(_ethereumEcdsa, TestItem.PrivateKeyA, _isEip155Enabled).WithValue(0).WithGasPrice(1).WithGasLimit(gasLimit).TestObject; Block block = Build.A.Block.WithNumber(MainnetSpecProvider.ByzantiumBlockNumber).WithTransactions(tx).WithGasLimit(gasLimit).TestObject; - int state = _stateProvider.TakeSnapshot(); + Snapshot state = _stateProvider.TakeSnapshot(); _transactionProcessor.BuildUp(tx, block.Header, NullTxTracer.Instance); _stateProvider.GetBalance(TestItem.PrivateKeyA.Address).Should().Be(1.Ether() - 21000); @@ -611,7 +610,7 @@ public void Account_is_not_created_on_buildup_and_restore() Block block = Build.A.Block.WithNumber(MainnetSpecProvider.ByzantiumBlockNumber).WithTransactions(tx).WithGasLimit(gasLimit).TestObject; _stateProvider.AccountExists(TestItem.PrivateKeyD.Address).Should().BeFalse(); - int state = _stateProvider.TakeSnapshot(); + Snapshot state = _stateProvider.TakeSnapshot(); _transactionProcessor.BuildUp(tx, block.Header, NullTxTracer.Instance); _stateProvider.AccountExists(TestItem.PrivateKeyD.Address).Should().BeTrue(); _stateProvider.Restore(state); @@ -627,7 +626,7 @@ public void Nonce_is_not_changed_on_buildup_and_restore() Transaction tx = Build.A.Transaction.SignedAndResolved(_ethereumEcdsa, TestItem.PrivateKeyA, _isEip155Enabled).WithValue(1.Ether() - (UInt256)gasLimit).WithGasPrice(1).WithGasLimit(gasLimit).TestObject; Block block = Build.A.Block.WithNumber(MainnetSpecProvider.ByzantiumBlockNumber).WithTransactions(tx).WithGasLimit(gasLimit).TestObject; - int state = _stateProvider.TakeSnapshot(); + Snapshot state = _stateProvider.TakeSnapshot(); _transactionProcessor.BuildUp(tx, block.Header, NullTxTracer.Instance); _stateProvider.GetNonce(TestItem.PrivateKeyA.Address).Should().Be(1); _stateProvider.Restore(state); @@ -644,7 +643,7 @@ public void State_changed_twice_in_buildup_should_have_correct_gas_cost() Transaction tx2 = Build.A.Transaction.SignedAndResolved(_ethereumEcdsa, TestItem.PrivateKeyA, _isEip155Enabled).WithValue(0).WithNonce(1).WithGasPrice(1).WithGasLimit(21000).TestObject; Block block = Build.A.Block.WithNumber(MainnetSpecProvider.ByzantiumBlockNumber).WithTransactions(tx1, tx2).WithGasLimit(gasLimit).TestObject; - int state = _stateProvider.TakeSnapshot(); + Snapshot state = _stateProvider.TakeSnapshot(); _transactionProcessor.BuildUp(tx1, block.Header, NullTxTracer.Instance); _stateProvider.GetBalance(TestItem.PrivateKeyA.Address).Should().Be(1.Ether() - 21000); diff --git a/src/Nethermind/Nethermind.Evm.Test/VirtualMachineTests.cs b/src/Nethermind/Nethermind.Evm.Test/VirtualMachineTests.cs index feffb7b878d..0a068e8ede8 100644 --- a/src/Nethermind/Nethermind.Evm.Test/VirtualMachineTests.cs +++ b/src/Nethermind/Nethermind.Evm.Test/VirtualMachineTests.cs @@ -154,7 +154,7 @@ public void Add_0_0() 0, (byte)Instruction.SSTORE); Assert.That(receipt.GasSpent, Is.EqualTo(GasCostOf.Transaction + 4 * GasCostOf.VeryLow + GasCostOf.SReset), "gas"); - Assert.That(Storage.Get(new StorageCell(Recipient, 0)), Is.EqualTo(new byte[] { 0 }), "storage"); + Assert.That(TestState.Get(new StorageCell(Recipient, 0)), Is.EqualTo(new byte[] { 0 }), "storage"); } [Test] @@ -170,7 +170,7 @@ public void Add_0_1() 0, (byte)Instruction.SSTORE); Assert.That(receipt.GasSpent, Is.EqualTo(GasCostOf.Transaction + 4 * GasCostOf.VeryLow + GasCostOf.SSet), "gas"); - Assert.That(Storage.Get(new StorageCell(Recipient, 0)), Is.EqualTo(new byte[] { 1 }), "storage"); + Assert.That(TestState.Get(new StorageCell(Recipient, 0)), Is.EqualTo(new byte[] { 1 }), "storage"); } [Test] @@ -186,7 +186,7 @@ public void Add_1_0() 0, (byte)Instruction.SSTORE); Assert.That(receipt.GasSpent, Is.EqualTo(GasCostOf.Transaction + 4 * GasCostOf.VeryLow + GasCostOf.SSet), "gas"); - Assert.That(Storage.Get(new StorageCell(Recipient, 0)), Is.EqualTo(new byte[] { 1 }), "storage"); + Assert.That(TestState.Get(new StorageCell(Recipient, 0)), Is.EqualTo(new byte[] { 1 }), "storage"); } [Test] @@ -302,7 +302,7 @@ public void Exp_2_160() 0, (byte)Instruction.SSTORE); Assert.That(receipt.GasSpent, Is.EqualTo(GasCostOf.Transaction + GasCostOf.VeryLow * 3 + GasCostOf.SSet + GasCostOf.Exp + GasCostOf.ExpByteEip160), "gas"); - Assert.That(Storage.Get(new StorageCell(Recipient, 0)), Is.EqualTo(BigInteger.Pow(2, 160).ToBigEndianByteArray()), "storage"); + Assert.That(TestState.Get(new StorageCell(Recipient, 0)), Is.EqualTo(BigInteger.Pow(2, 160).ToBigEndianByteArray()), "storage"); } [Test] @@ -318,7 +318,7 @@ public void Exp_0_0() 0, (byte)Instruction.SSTORE); Assert.That(receipt.GasSpent, Is.EqualTo(GasCostOf.Transaction + GasCostOf.VeryLow * 3 + GasCostOf.Exp + GasCostOf.SSet), "gas"); - Assert.That(Storage.Get(new StorageCell(Recipient, 0)), Is.EqualTo(BigInteger.One.ToBigEndianByteArray()), "storage"); + Assert.That(TestState.Get(new StorageCell(Recipient, 0)), Is.EqualTo(BigInteger.One.ToBigEndianByteArray()), "storage"); } [Test] @@ -334,7 +334,7 @@ public void Exp_0_160() 0, (byte)Instruction.SSTORE); Assert.That(receipt.GasSpent, Is.EqualTo(GasCostOf.Transaction + GasCostOf.VeryLow * 3 + GasCostOf.Exp + GasCostOf.ExpByteEip160 + GasCostOf.SReset), "gas"); - Assert.That(Storage.Get(new StorageCell(Recipient, 0)), Is.EqualTo(BigInteger.Zero.ToBigEndianByteArray()), "storage"); + Assert.That(TestState.Get(new StorageCell(Recipient, 0)), Is.EqualTo(BigInteger.Zero.ToBigEndianByteArray()), "storage"); } [Test] @@ -350,7 +350,7 @@ public void Exp_1_160() 0, (byte)Instruction.SSTORE); Assert.That(receipt.GasSpent, Is.EqualTo(GasCostOf.Transaction + GasCostOf.VeryLow * 3 + GasCostOf.Exp + GasCostOf.ExpByteEip160 + GasCostOf.SSet), "gas"); - Assert.That(Storage.Get(new StorageCell(Recipient, 0)), Is.EqualTo(BigInteger.One.ToBigEndianByteArray()), "storage"); + Assert.That(TestState.Get(new StorageCell(Recipient, 0)), Is.EqualTo(BigInteger.One.ToBigEndianByteArray()), "storage"); } [Test] @@ -366,7 +366,7 @@ public void Sub_0_0() 0, (byte)Instruction.SSTORE); Assert.That(receipt.GasSpent, Is.EqualTo(GasCostOf.Transaction + GasCostOf.VeryLow * 4 + GasCostOf.SReset), "gas"); - Assert.That(Storage.Get(new StorageCell(Recipient, 0)), Is.EqualTo(new byte[] { 0 }), "storage"); + Assert.That(TestState.Get(new StorageCell(Recipient, 0)), Is.EqualTo(new byte[] { 0 }), "storage"); } [Test] @@ -380,7 +380,7 @@ public void Not_0() 0, (byte)Instruction.SSTORE); Assert.That(receipt.GasSpent, Is.EqualTo(GasCostOf.Transaction + GasCostOf.VeryLow * 3 + GasCostOf.SSet), "gas"); - Assert.That(Storage.Get(new StorageCell(Recipient, 0)), Is.EqualTo((BigInteger.Pow(2, 256) - 1).ToBigEndianByteArray()), "storage"); + Assert.That(TestState.Get(new StorageCell(Recipient, 0)), Is.EqualTo((BigInteger.Pow(2, 256) - 1).ToBigEndianByteArray()), "storage"); } [Test] @@ -396,7 +396,7 @@ public void Or_0_0() 0, (byte)Instruction.SSTORE); Assert.That(receipt.GasSpent, Is.EqualTo(GasCostOf.Transaction + GasCostOf.VeryLow * 4 + GasCostOf.SReset), "gas"); - Assert.That(Storage.Get(new StorageCell(Recipient, 0)), Is.EqualTo(BigInteger.Zero.ToBigEndianByteArray()), "storage"); + Assert.That(TestState.Get(new StorageCell(Recipient, 0)), Is.EqualTo(BigInteger.Zero.ToBigEndianByteArray()), "storage"); } [Test] @@ -409,7 +409,7 @@ public void Sstore_twice_0_same_storage_should_refund_only_once() 0, (byte)Instruction.SSTORE); Assert.That(receipt.GasSpent, Is.EqualTo(GasCostOf.Transaction + GasCostOf.VeryLow * 2 + GasCostOf.SReset), "gas"); - Assert.That(Storage.Get(new StorageCell(Recipient, 0)), Is.EqualTo(BigInteger.Zero.ToBigEndianByteArray()), "storage"); + Assert.That(TestState.Get(new StorageCell(Recipient, 0)), Is.EqualTo(BigInteger.Zero.ToBigEndianByteArray()), "storage"); } /// diff --git a/src/Nethermind/Nethermind.Evm.Test/VirtualMachineTestsBase.cs b/src/Nethermind/Nethermind.Evm.Test/VirtualMachineTestsBase.cs index a53bc11e59d..d9b4ce524a2 100644 --- a/src/Nethermind/Nethermind.Evm.Test/VirtualMachineTestsBase.cs +++ b/src/Nethermind/Nethermind.Evm.Test/VirtualMachineTestsBase.cs @@ -34,9 +34,7 @@ public class VirtualMachineTestsBase private IDb _stateDb; protected VirtualMachine Machine { get; private set; } - protected IStateProvider TestState { get; private set; } - protected IStorageProvider Storage { get; private set; } - + protected IWorldState TestState { get; private set; } protected static Address Contract { get; } = new("0xd75a3a95360e44a3874e691fb48d77855f127069"); protected static Address Sender { get; } = TestItem.AddressA; protected static Address Recipient { get; } = TestItem.AddressB; @@ -64,12 +62,11 @@ public virtual void Setup() IDb codeDb = new MemDb(); _stateDb = new MemDb(); ITrieStore trieStore = new TrieStore(_stateDb, logManager); - TestState = new StateProvider(trieStore, codeDb, logManager); - Storage = new StorageProvider(trieStore, TestState, logManager); + TestState = new WorldState(trieStore, codeDb, logManager); _ethereumEcdsa = new EthereumEcdsa(SpecProvider.ChainId, logManager); IBlockhashProvider blockhashProvider = TestBlockhashProvider.Instance; Machine = new VirtualMachine(blockhashProvider, SpecProvider, logManager); - _processor = new TransactionProcessor(SpecProvider, TestState, Storage, Machine, logManager); + _processor = new TransactionProcessor(SpecProvider, TestState, Machine, logManager); } protected GethLikeTxTrace ExecuteAndTrace(params byte[] code) @@ -129,10 +126,21 @@ protected TestAllTracerWithOutput Execute(long blockNumber, long gasLimit, byte[ byte[][] blobVersionedHashes = null) { senderRecipientAndMiner ??= SenderRecipientAndMiner.Default; - TestState.CreateAccount(senderRecipientAndMiner.Sender, 100.Ether()); - TestState.CreateAccount(senderRecipientAndMiner.Recipient, 100.Ether()); - Keccak codeHash = TestState.UpdateCode(code); - TestState.UpdateCodeHash(senderRecipientAndMiner.Recipient, codeHash, SpecProvider.GenesisSpec); + + // checking if account exists - because creating new accounts overwrites already existing accounts, + // thus overwriting storage roots - essentially clearing the storage slots + // earlier it used to work - because the cache mapping address:storageTree was never cleared on account of + // TestState.CommitTrees() not being called. But now the WorldState.CommitTrees which also calls TestState.CommitTrees, clearing the cache. + if (!TestState.AccountExists(senderRecipientAndMiner.Sender)) + TestState.CreateAccount(senderRecipientAndMiner.Sender, 100.Ether()); + else + TestState.AddToBalance(senderRecipientAndMiner.Sender, 100.Ether(), SpecProvider.GenesisSpec); + + if (!TestState.AccountExists(senderRecipientAndMiner.Recipient)) + TestState.CreateAccount(senderRecipientAndMiner.Recipient, 100.Ether()); + else + TestState.AddToBalance(senderRecipientAndMiner.Recipient, 100.Ether(), SpecProvider.GenesisSpec); + TestState.InsertCode(senderRecipientAndMiner.Recipient, code, SpecProvider.GenesisSpec); GetLogManager().GetClassLogger().Debug("Committing initial state"); TestState.Commit(SpecProvider.GenesisSpec); @@ -146,6 +154,7 @@ protected TestAllTracerWithOutput Execute(long blockNumber, long gasLimit, byte[ .WithGasPrice(1) .WithValue(value) .WithBlobVersionedHashes(blobVersionedHashes) + .WithNonce(TestState.GetNonce(senderRecipientAndMiner.Sender)) .To(senderRecipientAndMiner.Recipient) .SignedAndResolved(_ethereumEcdsa, senderRecipientAndMiner.SenderKey) .TestObject; @@ -157,16 +166,28 @@ protected TestAllTracerWithOutput Execute(long blockNumber, long gasLimit, byte[ protected (Block block, Transaction transaction) PrepareTx(long blockNumber, long gasLimit, byte[] code, byte[] input, UInt256 value, SenderRecipientAndMiner senderRecipientAndMiner = null) { senderRecipientAndMiner ??= SenderRecipientAndMiner.Default; - TestState.CreateAccount(senderRecipientAndMiner.Sender, 100.Ether()); - TestState.CreateAccount(senderRecipientAndMiner.Recipient, 100.Ether()); - Keccak codeHash = TestState.UpdateCode(code); - TestState.UpdateCodeHash(senderRecipientAndMiner.Recipient, codeHash, SpecProvider.GenesisSpec); + + // checking if account exists - because creating new accounts overwrites already existing accounts, + // thus overwriting storage roots - essentially clearing the storage slots + // earlier it used to work - because the cache mapping address:storageTree was never cleared on account of + // TestState.CommitTrees() not being called. But now the WorldState.CommitTrees which also calls TestState.CommitTrees, clearing the cache. + if (!TestState.AccountExists(senderRecipientAndMiner.Sender)) + TestState.CreateAccount(senderRecipientAndMiner.Sender, 100.Ether()); + else + TestState.AddToBalance(senderRecipientAndMiner.Sender, 100.Ether(), SpecProvider.GenesisSpec); + + if (!TestState.AccountExists(senderRecipientAndMiner.Recipient)) + TestState.CreateAccount(senderRecipientAndMiner.Recipient, 100.Ether()); + else + TestState.AddToBalance(senderRecipientAndMiner.Recipient, 100.Ether(), SpecProvider.GenesisSpec); + TestState.InsertCode(senderRecipientAndMiner.Recipient, code, SpecProvider.GenesisSpec); TestState.Commit(SpecProvider.GenesisSpec); Transaction transaction = Build.A.Transaction .WithGasLimit(gasLimit) .WithGasPrice(1) + .WithNonce(TestState.GetNonce(senderRecipientAndMiner.Sender)) .WithData(input) .WithValue(value) .To(senderRecipientAndMiner.Recipient) @@ -220,22 +241,22 @@ protected void AssertGas(TestAllTracerWithOutput receipt, long gas) protected void AssertStorage(UInt256 address, Address value) { - Assert.That(Storage.Get(new StorageCell(Recipient, address)).PadLeft(32), Is.EqualTo(value.Bytes.PadLeft(32)), "storage"); + Assert.That(TestState.Get(new StorageCell(Recipient, address)).PadLeft(32), Is.EqualTo(value.Bytes.PadLeft(32)), "storage"); } protected void AssertStorage(UInt256 address, Keccak value) { - Assert.That(Storage.Get(new StorageCell(Recipient, address)).PadLeft(32), Is.EqualTo(value.Bytes), "storage"); + Assert.That(TestState.Get(new StorageCell(Recipient, address)).PadLeft(32), Is.EqualTo(value.Bytes), "storage"); } protected void AssertStorage(UInt256 address, ReadOnlySpan value) { - Assert.That(Storage.Get(new StorageCell(Recipient, address)).PadLeft(32), Is.EqualTo(new ZeroPaddedSpan(value, 32 - value.Length, PadDirection.Left).ToArray()), "storage"); + Assert.That(TestState.Get(new StorageCell(Recipient, address)).PadLeft(32), Is.EqualTo(new ZeroPaddedSpan(value, 32 - value.Length, PadDirection.Left).ToArray()), "storage"); } protected void AssertStorage(UInt256 address, BigInteger expectedValue) { - byte[] actualValue = Storage.Get(new StorageCell(Recipient, address)); + byte[] actualValue = TestState.Get(new StorageCell(Recipient, address)); byte[] expected = expectedValue < 0 ? expectedValue.ToBigEndianByteArray(32) : expectedValue.ToBigEndianByteArray(); Assert.That(actualValue, Is.EqualTo(expected), "storage"); } @@ -244,7 +265,7 @@ protected void AssertStorage(UInt256 address, UInt256 expectedValue) { byte[] bytes = ((BigInteger)expectedValue).ToBigEndianByteArray(); - byte[] actualValue = Storage.Get(new StorageCell(Recipient, address)); + byte[] actualValue = TestState.Get(new StorageCell(Recipient, address)); Assert.That(actualValue, Is.EqualTo(bytes), "storage"); } @@ -259,7 +280,7 @@ protected void AssertStorage(StorageCell storageCell, UInt256 expectedValue) } else { - byte[] actualValue = Storage.Get(storageCell); + byte[] actualValue = TestState.Get(storageCell); Assert.That(actualValue, Is.EqualTo(expectedValue.ToBigEndian().WithoutLeadingZeros().ToArray()), $"storage {storageCell}, call {_callIndex}"); } } diff --git a/src/Nethermind/Nethermind.Evm.Test/VmCodeDepositTests.cs b/src/Nethermind/Nethermind.Evm.Test/VmCodeDepositTests.cs index 4d46d7e3c55..5d3e4e59bc9 100644 --- a/src/Nethermind/Nethermind.Evm.Test/VmCodeDepositTests.cs +++ b/src/Nethermind/Nethermind.Evm.Test/VmCodeDepositTests.cs @@ -50,19 +50,18 @@ public void Regression_mainnet_6108276() .Done; TestState.CreateAccount(TestItem.AddressC, 1.Ether()); - Keccak createCodeHash = TestState.UpdateCode(createCode); - TestState.UpdateCodeHash(TestItem.AddressC, createCodeHash, Spec); + TestState.InsertCode(TestItem.AddressC, createCode, Spec); byte[] code = Prepare.EvmCode .Call(TestItem.AddressC, 32000 + 20003 + 20000 + 5000 + 500 + 0) // not enough .Done; TestAllTracerWithOutput receipt = Execute(code); - byte[] result = Storage.Get(storageCell); + byte[] result = TestState.Get(storageCell); Assert.That(result, Is.EqualTo(new byte[] { 0 }), "storage reverted"); Assert.That(receipt.GasSpent, Is.EqualTo(98777), "no refund"); - byte[] returnData = Storage.Get(new StorageCell(TestItem.AddressC, 0)); + byte[] returnData = TestState.Get(new StorageCell(TestItem.AddressC, 0)); Assert.That(returnData, Is.EqualTo(new byte[1]), "address returned"); } @@ -91,19 +90,18 @@ public void Regression_mainnet_226522() .Done; TestState.CreateAccount(TestItem.AddressC, 1.Ether()); - Keccak createCodeHash = TestState.UpdateCode(createCode); - TestState.UpdateCodeHash(TestItem.AddressC, createCodeHash, Spec); + TestState.InsertCode(TestItem.AddressC, createCode, Spec); byte[] code = Prepare.EvmCode .Call(TestItem.AddressC, 32000 + 20003 + 20000 + 5000 + 500 + 0) // not enough .Done; TestAllTracerWithOutput receipt = Execute(code); - byte[] result = Storage.Get(storageCell); + byte[] result = TestState.Get(storageCell); Assert.That(result, Is.EqualTo(new byte[] { 0 }), "storage reverted"); Assert.That(receipt.GasSpent, Is.EqualTo(83199), "with refund"); - byte[] returnData = Storage.Get(new StorageCell(TestItem.AddressC, 0)); + byte[] returnData = TestState.Get(new StorageCell(TestItem.AddressC, 0)); Assert.That(returnData, Is.EqualTo(deployed.Bytes), "address returned"); } } diff --git a/src/Nethermind/Nethermind.Evm/Tracing/GethStyle/GethLikeTxTracer.cs b/src/Nethermind/Nethermind.Evm/Tracing/GethStyle/GethLikeTxTracer.cs index eca64e0617e..6d9b2454e01 100644 --- a/src/Nethermind/Nethermind.Evm/Tracing/GethStyle/GethLikeTxTracer.cs +++ b/src/Nethermind/Nethermind.Evm/Tracing/GethStyle/GethLikeTxTracer.cs @@ -8,6 +8,7 @@ using Nethermind.Core.Extensions; using Nethermind.Int256; using Nethermind.State; +using Nethermind.State.Tracing; namespace Nethermind.Evm.Tracing.GethStyle { diff --git a/src/Nethermind/Nethermind.Evm/Tracing/ITxTracer.cs b/src/Nethermind/Nethermind.Evm/Tracing/ITxTracer.cs index f6400a3a87b..5d5b3ac06fb 100644 --- a/src/Nethermind/Nethermind.Evm/Tracing/ITxTracer.cs +++ b/src/Nethermind/Nethermind.Evm/Tracing/ITxTracer.cs @@ -8,10 +8,11 @@ using Nethermind.Core.Crypto; using Nethermind.Int256; using Nethermind.State; +using Nethermind.State.Tracing; namespace Nethermind.Evm.Tracing { - public interface ITxTracer : IStateTracer, IStorageTracer + public interface ITxTracer : IWorldStateTracer { /// /// Defines whether MarkAsSuccess or MarkAsFailed will be called diff --git a/src/Nethermind/Nethermind.Evm/TransactionProcessing/ReadOnlyTransactionProcessor.cs b/src/Nethermind/Nethermind.Evm/TransactionProcessing/ReadOnlyTransactionProcessor.cs index fb24e986dbd..09cda3ea1ca 100644 --- a/src/Nethermind/Nethermind.Evm/TransactionProcessing/ReadOnlyTransactionProcessor.cs +++ b/src/Nethermind/Nethermind.Evm/TransactionProcessing/ReadOnlyTransactionProcessor.cs @@ -13,17 +13,13 @@ namespace Nethermind.Evm.TransactionProcessing public class ReadOnlyTransactionProcessor : IReadOnlyTransactionProcessor { private readonly ITransactionProcessor _transactionProcessor; - private readonly IStateProvider _stateProvider; - private readonly IStorageProvider _storageProvider; - private readonly ReadOnlyDb _codeDb; + private readonly IWorldState _stateProvider; private readonly Keccak _stateBefore; - public ReadOnlyTransactionProcessor(ITransactionProcessor transactionProcessor, IStateProvider stateProvider, IStorageProvider storageProvider, ReadOnlyDb codeDb, Keccak startState) + public ReadOnlyTransactionProcessor(ITransactionProcessor transactionProcessor, IWorldState stateProvider, Keccak startState) { _transactionProcessor = transactionProcessor ?? throw new ArgumentNullException(nameof(transactionProcessor)); _stateProvider = stateProvider ?? throw new ArgumentNullException(nameof(stateProvider)); - _storageProvider = storageProvider ?? throw new ArgumentNullException(nameof(storageProvider)); - _codeDb = codeDb ?? throw new ArgumentNullException(nameof(codeDb)); _stateBefore = _stateProvider.StateRoot; _stateProvider.StateRoot = startState ?? throw new ArgumentNullException(nameof(startState)); } @@ -47,8 +43,6 @@ public void Dispose() { _stateProvider.StateRoot = _stateBefore; _stateProvider.Reset(); - _storageProvider.Reset(); - _codeDb.ClearTempChanges(); } } } diff --git a/src/Nethermind/Nethermind.Evm/TransactionProcessing/TransactionProcessor.cs b/src/Nethermind/Nethermind.Evm/TransactionProcessing/TransactionProcessor.cs index fed1f20e0ab..4610042986e 100644 --- a/src/Nethermind/Nethermind.Evm/TransactionProcessing/TransactionProcessor.cs +++ b/src/Nethermind/Nethermind.Evm/TransactionProcessing/TransactionProcessor.cs @@ -14,6 +14,7 @@ using Nethermind.Logging; using Nethermind.Specs; using Nethermind.State; +using Nethermind.State.Tracing; using Transaction = Nethermind.Core.Transaction; namespace Nethermind.Evm.TransactionProcessing @@ -22,8 +23,6 @@ public class TransactionProcessor : ITransactionProcessor { private readonly EthereumEcdsa _ecdsa; private readonly ILogger _logger; - private readonly IStateProvider _stateProvider; - private readonly IStorageProvider _storageProvider; private readonly ISpecProvider _specProvider; private readonly IWorldState _worldState; private readonly IVirtualMachine _virtualMachine; @@ -57,14 +56,6 @@ private enum ExecutionOptions CommitAndRestore = Commit | Restore | NoValidation } - public TransactionProcessor( - ISpecProvider? specProvider, - IStateProvider? stateProvider, - IStorageProvider? storageProvider, - IVirtualMachine? virtualMachine, - ILogManager? logManager) - : this(specProvider, new WorldState(stateProvider, storageProvider), virtualMachine, logManager) { } - public TransactionProcessor( ISpecProvider? specProvider, IWorldState? worldState, @@ -74,8 +65,6 @@ public TransactionProcessor( _logger = logManager?.GetClassLogger() ?? throw new ArgumentNullException(nameof(logManager)); _specProvider = specProvider ?? throw new ArgumentNullException(nameof(specProvider)); _worldState = worldState ?? throw new ArgumentNullException(nameof(worldState)); - _stateProvider = worldState.StateProvider; - _storageProvider = worldState.StorageProvider; _virtualMachine = virtualMachine ?? throw new ArgumentNullException(nameof(virtualMachine)); _ecdsa = new EthereumEcdsa(specProvider.ChainId, logManager); } @@ -110,15 +99,15 @@ private void QuickFail(Transaction tx, BlockHeader block, ITxTracer txTracer, bo Address recipient = tx.To ?? ContractAddress.From( tx.SenderAddress ?? Address.Zero, - _stateProvider.GetNonce(tx.SenderAddress ?? Address.Zero)); + _worldState.GetNonce(tx.SenderAddress ?? Address.Zero)); if (txTracer.IsTracingReceipt) { Keccak? stateRoot = null; if (eip658NotEnabled) { - _stateProvider.RecalculateStateRoot(); - stateRoot = _stateProvider.StateRoot; + _worldState.RecalculateStateRoot(); + stateRoot = _worldState.StateRoot; } txTracer.MarkAsFailed(recipient, tx.GasLimit, Array.Empty(), reason ?? "invalid", stateRoot); @@ -172,7 +161,7 @@ private void Execute(Transaction transaction, BlockHeader block, ITxTracer txTra return; } - if (!noValidation && _stateProvider.IsInvalidContractSender(spec, caller)) + if (!noValidation && _worldState.IsInvalidContractSender(spec, caller)) { TraceLogInvalidTx(transaction, "SENDER_IS_CONTRACT"); QuickFail(transaction, block, txTracer, eip658NotEnabled, "sender has deployed code"); @@ -219,7 +208,7 @@ private void Execute(Transaction transaction, BlockHeader block, ITxTracer txTra } } - if (!_stateProvider.AccountExists(caller)) + if (!_worldState.AccountExists(caller)) { // hacky fix for the potential recovery issue if (transaction.Signature is not null) @@ -240,7 +229,7 @@ private void Execute(Transaction transaction, BlockHeader block, ITxTracer txTra if (!commit || noValidation || effectiveGasPrice == UInt256.Zero) { deleteCallerAccount = !commit || restore; - _stateProvider.CreateAccount(caller, UInt256.Zero); + _worldState.CreateAccount(caller, UInt256.Zero); } } @@ -255,7 +244,7 @@ private void Execute(Transaction transaction, BlockHeader block, ITxTracer txTra if (notSystemTransaction) { - UInt256 senderBalance = _stateProvider.GetBalance(caller); + UInt256 senderBalance = _worldState.GetBalance(caller); if (!noValidation && ((ulong)intrinsicGas * effectiveGasPrice + value > senderBalance || senderReservedGasPayment + value > senderBalance)) { @@ -275,28 +264,28 @@ private void Execute(Transaction transaction, BlockHeader block, ITxTracer txTra return; } - if (transaction.Nonce != _stateProvider.GetNonce(caller)) + if (transaction.Nonce != _worldState.GetNonce(caller)) { TraceLogInvalidTx(transaction, - $"WRONG_TRANSACTION_NONCE: {transaction.Nonce} (expected {_stateProvider.GetNonce(caller)})"); + $"WRONG_TRANSACTION_NONCE: {transaction.Nonce} (expected {_worldState.GetNonce(caller)})"); QuickFail(transaction, block, txTracer, eip658NotEnabled, "wrong transaction nonce"); return; } - _stateProvider.IncrementNonce(caller); + _worldState.IncrementNonce(caller); } - _stateProvider.SubtractFromBalance(caller, senderReservedGasPayment, spec); + _worldState.SubtractFromBalance(caller, senderReservedGasPayment, spec); if (commit) { - _stateProvider.Commit(spec, txTracer.IsTracingState ? txTracer : NullTxTracer.Instance); + _worldState.Commit(spec, txTracer.IsTracingState ? txTracer : NullTxTracer.Instance); } long unspentGas = gasLimit - intrinsicGas; long spentGas = gasLimit; Snapshot snapshot = _worldState.TakeSnapshot(); - _stateProvider.SubtractFromBalance(caller, value, spec); + _worldState.SubtractFromBalance(caller, value, spec); byte statusCode = StatusCode.Failure; TransactionSubstate substate = null; @@ -304,7 +293,7 @@ private void Execute(Transaction transaction, BlockHeader block, ITxTracer txTra try { Address? recipient = - transaction.GetRecipient(transaction.IsContractCreation ? _stateProvider.GetNonce(caller) : 0); + transaction.GetRecipient(transaction.IsContractCreation ? _worldState.GetNonce(caller) : 0); if (transaction.IsContractCreation) { // if transaction is a contract creation then recipient address is the contract deployment address @@ -387,8 +376,7 @@ private void Execute(Transaction transaction, BlockHeader block, ITxTracer txTra if (unspentGas >= codeDepositGasCost) { - Keccak codeHash = _stateProvider.UpdateCode(substate.Output); - _stateProvider.UpdateCodeHash(recipient, codeHash, spec); + _worldState.InsertCode(recipient, substate.Output, spec); unspentGas -= codeDepositGasCost; } } @@ -396,8 +384,8 @@ private void Execute(Transaction transaction, BlockHeader block, ITxTracer txTra foreach (Address toBeDestroyed in substate.DestroyList) { if (_logger.IsTrace) _logger.Trace($"Destroying account {toBeDestroyed}"); - _storageProvider.ClearStorage(toBeDestroyed); - _stateProvider.DeleteAccount(toBeDestroyed); + _worldState.ClearStorage(toBeDestroyed); + _worldState.DeleteAccount(toBeDestroyed); if (txTracer.IsTracingRefunds) txTracer.ReportRefund(RefundOf.Destroy(spec.IsEip3529Enabled)); } @@ -422,13 +410,13 @@ private void Execute(Transaction transaction, BlockHeader block, ITxTracer txTra if (notSystemTransaction) { UInt256 fees = (ulong)spentGas * premiumPerGas; - if (_stateProvider.AccountExists(gasBeneficiary)) + if (_worldState.AccountExists(gasBeneficiary)) { - _stateProvider.AddToBalance(gasBeneficiary, fees, spec); + _worldState.AddToBalance(gasBeneficiary, fees, spec); } else { - _stateProvider.CreateAccount(gasBeneficiary, fees); + _worldState.CreateAccount(gasBeneficiary, fees); } UInt256 burntFees = !transaction.IsFree() ? (ulong)spentGas * block.BaseFeePerGas : 0; @@ -437,13 +425,13 @@ private void Execute(Transaction transaction, BlockHeader block, ITxTracer txTra { if (!burntFees.IsZero) { - if (_stateProvider.AccountExists(spec.Eip1559FeeCollector)) + if (_worldState.AccountExists(spec.Eip1559FeeCollector)) { - _stateProvider.AddToBalance(spec.Eip1559FeeCollector, burntFees, spec); + _worldState.AddToBalance(spec.Eip1559FeeCollector, burntFees, spec); } else { - _stateProvider.CreateAccount(spec.Eip1559FeeCollector, burntFees); + _worldState.CreateAccount(spec.Eip1559FeeCollector, burntFees); } } } @@ -457,27 +445,25 @@ private void Execute(Transaction transaction, BlockHeader block, ITxTracer txTra if (restore) { - _storageProvider.Reset(); - _stateProvider.Reset(); + _worldState.Reset(); if (deleteCallerAccount) { - _stateProvider.DeleteAccount(caller); + _worldState.DeleteAccount(caller); } else { - _stateProvider.AddToBalance(caller, senderReservedGasPayment, spec); + _worldState.AddToBalance(caller, senderReservedGasPayment, spec); if (notSystemTransaction) { - _stateProvider.DecrementNonce(caller); + _worldState.DecrementNonce(caller); } - _stateProvider.Commit(spec); + _worldState.Commit(spec); } } else if (commit) { - _storageProvider.Commit(txTracer.IsTracingState ? txTracer : NullStorageTracer.Instance); - _stateProvider.Commit(spec, txTracer.IsTracingState ? txTracer : NullStateTracer.Instance); + _worldState.Commit(spec, txTracer.IsTracingState ? txTracer : NullStateTracer.Instance); } if (!noValidation && notSystemTransaction) @@ -490,8 +476,8 @@ private void Execute(Transaction transaction, BlockHeader block, ITxTracer txTra Keccak stateRoot = null; if (eip658NotEnabled) { - _stateProvider.RecalculateStateRoot(); - stateRoot = _stateProvider.StateRoot; + _worldState.RecalculateStateRoot(); + stateRoot = _worldState.StateRoot; } if (statusCode == StatusCode.Failure) @@ -510,11 +496,11 @@ private void Execute(Transaction transaction, BlockHeader block, ITxTracer txTra private void PrepareAccountForContractDeployment(Address contractAddress, IReleaseSpec spec) { - if (_stateProvider.AccountExists(contractAddress)) + if (_worldState.AccountExists(contractAddress)) { CodeInfo codeInfo = _virtualMachine.GetCachedCodeInfo(_worldState, contractAddress, spec); bool codeIsNotEmpty = codeInfo.MachineCode.Length != 0; - bool accountNonceIsNotZero = _stateProvider.GetNonce(contractAddress) != 0; + bool accountNonceIsNotZero = _worldState.GetNonce(contractAddress) != 0; // TODO: verify what should happen if code info is a precompile // (but this would generally be a hash collision) @@ -529,7 +515,7 @@ private void PrepareAccountForContractDeployment(Address contractAddress, IRelea } // we clean any existing storage (in case of a previously called self destruct) - _stateProvider.UpdateStorageRoot(contractAddress, Keccak.EmptyTreeHash); + _worldState.UpdateStorageRoot(contractAddress, Keccak.EmptyTreeHash); } } @@ -552,7 +538,7 @@ private long Refund(long gasLimit, long unspentGas, TransactionSubstate substate if (_logger.IsTrace) _logger.Trace("Refunding unused gas of " + unspentGas + " and refund of " + refund); - _stateProvider.AddToBalance(sender, (ulong)(unspentGas + refund) * gasPrice, spec); + _worldState.AddToBalance(sender, (ulong)(unspentGas + refund) * gasPrice, spec); spentGas -= refund; } diff --git a/src/Nethermind/Nethermind.Evm/VirtualMachine.cs b/src/Nethermind/Nethermind.Evm/VirtualMachine.cs index b5e9a3121e1..e084ad78aa7 100644 --- a/src/Nethermind/Nethermind.Evm/VirtualMachine.cs +++ b/src/Nethermind/Nethermind.Evm/VirtualMachine.cs @@ -61,9 +61,8 @@ public class VirtualMachine : IVirtualMachine private static readonly LruCache _codeCache = new(MemoryAllowance.CodeCacheSize, MemoryAllowance.CodeCacheSize, "VM bytecodes"); private readonly ILogger _logger; private IWorldState _worldState; - private IStateProvider _state; + private IWorldState _state; private readonly Stack _stateStack = new(); - private IStorageProvider _storage; private (Address Address, bool ShouldDelete) _parityTouchBugAccount = (Address.FromNumber(3), false); private Dictionary? _precompiles; private byte[] _returnDataBuffer = Array.Empty(); @@ -85,8 +84,7 @@ public TransactionSubstate Run(EvmState state, IWorldState worldState, ITxTracer { _txTracer = txTracer; - _state = worldState.StateProvider; - _storage = worldState.StorageProvider; + _state = worldState; _worldState = worldState; IReleaseSpec spec = _specProvider.GetSpec(state.Env.TxExecutionContext.Header.Number, state.Env.TxExecutionContext.Header.Timestamp); @@ -252,8 +250,7 @@ public TransactionSubstate Run(EvmState state, IWorldState worldState, ITxTracer bool invalidCode = CodeDepositHandler.CodeIsInvalid(spec, callResult.Output); if (gasAvailableForCodeDeposit >= codeDepositGasCost && !invalidCode) { - Keccak codeHash = _state.UpdateCode(callResult.Output); - _state.UpdateCodeHash(callCodeOwner, codeHash, spec); + _state.InsertCode(callCodeOwner, callResult.Output, spec); currentState.GasAvailable -= codeDepositGasCost; if (_txTracer.IsTracingActions) @@ -376,7 +373,6 @@ private void RevertParityTouchBugAccount(IReleaseSpec spec) public CodeInfo GetCachedCodeInfo(IWorldState worldState, Address codeSource, IReleaseSpec vmSpec) { - IStateProvider state = worldState.StateProvider; if (codeSource.IsPrecompile(vmSpec)) { if (_precompiles is null) @@ -387,11 +383,11 @@ public CodeInfo GetCachedCodeInfo(IWorldState worldState, Address codeSource, IR return _precompiles[codeSource]; } - Keccak codeHash = state.GetCodeHash(codeSource); + Keccak codeHash = worldState.GetCodeHash(codeSource); CodeInfo cachedCodeInfo = _codeCache.Get(codeHash); if (cachedCodeInfo is null) { - byte[] code = state.GetCode(codeHash); + byte[] code = worldState.GetCode(codeHash); if (code is null) { @@ -404,7 +400,7 @@ public CodeInfo GetCachedCodeInfo(IWorldState worldState, Address codeSource, IR else { // need to touch code so that any collectors that track database access are informed - state.TouchCode(codeHash); + worldState.TouchCode(codeHash); } return cachedCodeInfo; @@ -1498,7 +1494,7 @@ static void UpdateCurrentState(EvmState state, int pc, long gas, int stackHead) StorageAccessType.SLOAD, spec)) goto OutOfGas; - byte[] value = _storage.Get(storageCell); + byte[] value = _state.Get(storageCell); stack.PushBytes(value); if (_txTracer.IsTracingOpLevelStorage) @@ -1544,7 +1540,7 @@ static void UpdateCurrentState(EvmState state, int pc, long gas, int stackHead) StorageAccessType.SSTORE, spec)) goto OutOfGas; - Span currentValue = _storage.Get(storageCell); + Span currentValue = _state.Get(storageCell); // Console.WriteLine($"current: {currentValue.ToHexString()} newValue {newValue.ToHexString()}"); bool currentIsZero = currentValue.IsZero(); @@ -1574,7 +1570,7 @@ static void UpdateCurrentState(EvmState state, int pc, long gas, int stackHead) } else // net metered, C != N { - Span originalValue = _storage.GetOriginal(storageCell); + Span originalValue = _state.GetOriginal(storageCell); bool originalIsZero = originalValue.IsZero(); bool currentSameAsOriginal = Bytes.AreEqual(originalValue, currentValue); @@ -1638,7 +1634,7 @@ static void UpdateCurrentState(EvmState state, int pc, long gas, int stackHead) if (!newSameAsCurrent) { Span valueToStore = newIsZero ? BytesZero : newValue; - _storage.Set(storageCell, valueToStore.ToArray()); + _state.Set(storageCell, valueToStore.ToArray()); } if (_txTracer.IsTracingInstructions) @@ -1667,7 +1663,7 @@ static void UpdateCurrentState(EvmState state, int pc, long gas, int stackHead) stack.PopUInt256(out UInt256 storageIndex); StorageCell storageCell = new(env.ExecutingAccount, storageIndex); - byte[] value = _storage.GetTransientState(storageCell); + byte[] value = _state.GetTransientState(storageCell); stack.PushBytes(value); if (_txTracer.IsTracingOpLevelStorage) @@ -1701,7 +1697,7 @@ static void UpdateCurrentState(EvmState state, int pc, long gas, int stackHead) StorageCell storageCell = new(env.ExecutingAccount, storageIndex); byte[] currentValue = newValue.ToArray(); - _storage.SetTransientState(storageCell, currentValue); + _state.SetTransientState(storageCell, currentValue); if (_txTracer.IsTracingOpLevelStorage) { @@ -2008,7 +2004,7 @@ static void UpdateCurrentState(EvmState state, int pc, long gas, int stackHead) } else if (_state.IsDeadAccount(contractAddress)) { - _storage.ClearStorage(contractAddress); + _state.ClearStorage(contractAddress); } _state.SubtractFromBalance(env.ExecutingAccount, value, spec); diff --git a/src/Nethermind/Nethermind.Init/Steps/InitializeBlockchain.cs b/src/Nethermind/Nethermind.Init/Steps/InitializeBlockchain.cs index 6ec42bee114..23a17d39cca 100644 --- a/src/Nethermind/Nethermind.Init/Steps/InitializeBlockchain.cs +++ b/src/Nethermind/Nethermind.Init/Steps/InitializeBlockchain.cs @@ -148,7 +148,7 @@ private Task InitBlockchain() ITrieStore readOnlyTrieStore = setApi.ReadOnlyTrieStore = trieStore.AsReadOnly(cachedStateDb); - IStateProvider stateProvider = setApi.StateProvider = new StateProvider( + IWorldState worldState = setApi.WorldState = new WorldState( trieStore, codeDb, getApi.LogManager); @@ -161,7 +161,7 @@ private Task InitBlockchain() setApi.ChainHeadStateProvider = new ChainHeadReadOnlyStateProvider(getApi.BlockTree, stateReader); Account.AccountStartNonce = getApi.ChainSpec.Parameters.AccountStartNonce; - stateProvider.StateRoot = getApi.BlockTree!.Head?.StateRoot ?? Keccak.EmptyTreeHash; + worldState.StateRoot = getApi.BlockTree!.Head?.StateRoot ?? Keccak.EmptyTreeHash; if (_api.Config().DiagnosticMode == DiagnosticMode.VerifyTrie) { @@ -171,7 +171,7 @@ private Task InitBlockchain() { _logger!.Info("Collecting trie stats and verifying that no nodes are missing..."); TrieStore noPruningStore = new(stateWitnessedBy, No.Pruning, Persist.EveryBlock, getApi.LogManager); - IStateProvider diagStateProvider = new StateProvider(noPruningStore, codeDb, getApi.LogManager) + IWorldState diagStateProvider = new WorldState(noPruningStore, codeDb, getApi.LogManager) { StateRoot = getApi.BlockTree!.Head?.StateRoot ?? Keccak.EmptyTreeHash }; @@ -188,7 +188,7 @@ private Task InitBlockchain() // Init state if we need system calls before actual processing starts if (getApi.BlockTree!.Head?.StateRoot is not null) { - stateProvider.StateRoot = getApi.BlockTree.Head.StateRoot; + worldState.StateRoot = getApi.BlockTree.Head.StateRoot; } TxValidator txValidator = setApi.TxValidator = new TxValidator(getApi.SpecProvider.ChainId); @@ -202,11 +202,6 @@ private Task InitBlockchain() _api.BlockPreprocessor.AddFirst( new RecoverSignatures(getApi.EthereumEcdsa, txPool, getApi.SpecProvider, getApi.LogManager)); - IStorageProvider storageProvider = setApi.StorageProvider = new StorageProvider( - trieStore, - stateProvider, - getApi.LogManager); - // blockchain processing BlockhashProvider blockhashProvider = new( getApi.BlockTree, getApi.LogManager); @@ -216,7 +211,6 @@ private Task InitBlockchain() getApi.SpecProvider, getApi.LogManager); - WorldState worldState = new(stateProvider, storageProvider); _api.TransactionProcessor = new TransactionProcessor( getApi.SpecProvider, worldState, @@ -359,9 +353,8 @@ protected virtual BlockProcessor CreateBlockProcessor() _api.SpecProvider, _api.BlockValidator, _api.RewardCalculatorSource.Get(_api.TransactionProcessor!), - new BlockProcessor.BlockValidationTransactionsExecutor(_api.TransactionProcessor, _api.StateProvider!), - _api.StateProvider, - _api.StorageProvider, + new BlockProcessor.BlockValidationTransactionsExecutor(_api.TransactionProcessor, _api.WorldState!), + _api.WorldState, _api.ReceiptStorage, _api.WitnessCollector, _api.LogManager); diff --git a/src/Nethermind/Nethermind.Init/Steps/LoadGenesisBlock.cs b/src/Nethermind/Nethermind.Init/Steps/LoadGenesisBlock.cs index 10dc631f617..a543747edc6 100644 --- a/src/Nethermind/Nethermind.Init/Steps/LoadGenesisBlock.cs +++ b/src/Nethermind/Nethermind.Init/Steps/LoadGenesisBlock.cs @@ -55,8 +55,7 @@ protected virtual void Load() { if (_api.ChainSpec is null) throw new StepDependencyException(nameof(_api.ChainSpec)); if (_api.BlockTree is null) throw new StepDependencyException(nameof(_api.BlockTree)); - if (_api.StateProvider is null) throw new StepDependencyException(nameof(_api.StateProvider)); - if (_api.StorageProvider is null) throw new StepDependencyException(nameof(_api.StorageProvider)); + if (_api.WorldState is null) throw new StepDependencyException(nameof(_api.WorldState)); if (_api.SpecProvider is null) throw new StepDependencyException(nameof(_api.SpecProvider)); if (_api.DbProvider is null) throw new StepDependencyException(nameof(_api.DbProvider)); if (_api.TransactionProcessor is null) throw new StepDependencyException(nameof(_api.TransactionProcessor)); @@ -64,8 +63,7 @@ protected virtual void Load() Block genesis = new GenesisLoader( _api.ChainSpec, _api.SpecProvider, - _api.StateProvider, - _api.StorageProvider, + _api.WorldState, _api.TransactionProcessor) .Load(); @@ -96,13 +94,13 @@ void GenesisProcessed(object? sender, BlockEventArgs args) /// private void ValidateGenesisHash(Keccak? expectedGenesisHash) { - if (_api.StateProvider is null) throw new StepDependencyException(nameof(_api.StateProvider)); + if (_api.WorldState is null) throw new StepDependencyException(nameof(_api.WorldState)); if (_api.BlockTree is null) throw new StepDependencyException(nameof(_api.BlockTree)); BlockHeader genesis = _api.BlockTree.Genesis!; if (expectedGenesisHash is not null && genesis.Hash != expectedGenesisHash) { - if (_logger.IsWarn) _logger.Warn(_api.StateProvider.DumpState()); + if (_logger.IsWarn) _logger.Warn(_api.WorldState.DumpState()); if (_logger.IsWarn) _logger.Warn(genesis.ToString(BlockHeader.Format.Full)); if (_logger.IsError) _logger.Error($"Unexpected genesis hash, expected {expectedGenesisHash}, but was {genesis.Hash}"); } diff --git a/src/Nethermind/Nethermind.JsonRpc.Benchmark/EthModuleBenchmarks.cs b/src/Nethermind/Nethermind.JsonRpc.Benchmark/EthModuleBenchmarks.cs index 26f653372f2..24130353de8 100644 --- a/src/Nethermind/Nethermind.JsonRpc.Benchmark/EthModuleBenchmarks.cs +++ b/src/Nethermind/Nethermind.JsonRpc.Benchmark/EthModuleBenchmarks.cs @@ -60,12 +60,11 @@ public void GlobalSetup() IReleaseSpec spec = MainnetSpecProvider.Instance.GenesisSpec; var trieStore = new TrieStore(stateDb, LimboLogs.Instance); - StateProvider stateProvider = new(trieStore, codeDb, LimboLogs.Instance); + WorldState stateProvider = new(trieStore, codeDb, LimboLogs.Instance); stateProvider.CreateAccount(Address.Zero, 1000.Ether()); stateProvider.Commit(spec); stateProvider.CommitTree(0); - StorageProvider storageProvider = new(trieStore, stateProvider, LimboLogs.Instance); StateReader stateReader = new(trieStore, codeDb, LimboLogs.Instance); ChainLevelInfoRepository chainLevelInfoRepository = new(blockInfoDb); @@ -80,11 +79,11 @@ public void GlobalSetup() blockTree.SuggestBlock(block1); TransactionProcessor transactionProcessor - = new(MainnetSpecProvider.Instance, stateProvider, storageProvider, _virtualMachine, LimboLogs.Instance); + = new(MainnetSpecProvider.Instance, stateProvider, _virtualMachine, LimboLogs.Instance); IBlockProcessor.IBlockTransactionsExecutor transactionsExecutor = new BlockProcessor.BlockValidationTransactionsExecutor(transactionProcessor, stateProvider); BlockProcessor blockProcessor = new(specProvider, Always.Valid, new RewardCalculator(specProvider), transactionsExecutor, - stateProvider, storageProvider, NullReceiptStorage.Instance, NullWitnessCollector.Instance, LimboLogs.Instance); + stateProvider, NullReceiptStorage.Instance, NullWitnessCollector.Instance, LimboLogs.Instance); EthereumEcdsa ecdsa = new(specProvider.ChainId, LimboLogs.Instance); BlockchainProcessor blockchainProcessor = new( diff --git a/src/Nethermind/Nethermind.JsonRpc.Test/Modules/Eth/EthRpcModuleTests.EstimateGas.cs b/src/Nethermind/Nethermind.JsonRpc.Test/Modules/Eth/EthRpcModuleTests.EstimateGas.cs index 9a9c37f2311..d2a7986c505 100644 --- a/src/Nethermind/Nethermind.JsonRpc.Test/Modules/Eth/EthRpcModuleTests.EstimateGas.cs +++ b/src/Nethermind/Nethermind.JsonRpc.Test/Modules/Eth/EthRpcModuleTests.EstimateGas.cs @@ -250,7 +250,7 @@ public async Task should_estimate_transaction_with_deployed_code_when_eip3607_en Transaction tx = Build.A.Transaction.SignedAndResolved(TestItem.PrivateKeyA).TestObject; TransactionForRpc transaction = new(Keccak.Zero, 1L, 1, tx); - ctx.Test.State.UpdateCodeHash(TestItem.AddressA, TestItem.KeccakH, London.Instance); + ctx.Test.State.InsertCode(TestItem.AddressA, "H"u8.ToArray(), London.Instance); transaction.To = TestItem.AddressB; string serialized = diff --git a/src/Nethermind/Nethermind.JsonRpc.Test/Modules/Eth/EthRpcModuleTests.EthCall.cs b/src/Nethermind/Nethermind.JsonRpc.Test/Modules/Eth/EthRpcModuleTests.EthCall.cs index 8fbdbd96925..5e495305b66 100644 --- a/src/Nethermind/Nethermind.JsonRpc.Test/Modules/Eth/EthRpcModuleTests.EthCall.cs +++ b/src/Nethermind/Nethermind.JsonRpc.Test/Modules/Eth/EthRpcModuleTests.EthCall.cs @@ -106,7 +106,7 @@ public async Task should_not_reject_transactions_with_deployed_code_when_eip3607 Transaction tx = Build.A.Transaction.SignedAndResolved(TestItem.PrivateKeyA).TestObject; TransactionForRpc transaction = new(Keccak.Zero, 1L, 1, tx); - ctx.Test.State.UpdateCodeHash(TestItem.AddressA, TestItem.KeccakH, London.Instance); + ctx.Test.State.InsertCode(TestItem.AddressA, "H"u8.ToArray(), London.Instance); transaction.To = TestItem.AddressB; string serialized = diff --git a/src/Nethermind/Nethermind.JsonRpc.Test/Modules/ParityRpcModuleTests.cs b/src/Nethermind/Nethermind.JsonRpc.Test/Modules/ParityRpcModuleTests.cs index 320d58a1e3b..1691cdc8cc4 100644 --- a/src/Nethermind/Nethermind.JsonRpc.Test/Modules/ParityRpcModuleTests.cs +++ b/src/Nethermind/Nethermind.JsonRpc.Test/Modules/ParityRpcModuleTests.cs @@ -63,8 +63,7 @@ public void Initialize() peerManager.ConnectedPeers.Returns(new List { peerA, peerB, peerA, peerC, peerB }); peerManager.MaxActivePeers.Returns(15); - StateProvider stateProvider = new(new TrieStore(new MemDb(), LimboLogs.Instance), new MemDb(), LimboLogs.Instance); - StateReader stateReader = new(new TrieStore(new MemDb(), LimboLogs.Instance), new MemDb(), LimboLogs.Instance); + WorldState stateProvider = new(new TrieStore(new MemDb(), LimboLogs.Instance), new MemDb(), LimboLogs.Instance); IDb blockDb = new MemDb(); IDb headerDb = new MemDb(); @@ -346,7 +345,7 @@ public void parity_netPeers_empty_ActivePeers() ITransactionComparerProvider transactionComparerProvider = new TransactionComparerProvider(specProvider, blockTree); - TxPool.TxPool txPool = new(ethereumEcdsa, new ChainHeadInfoProvider(new FixedForkActivationChainHeadSpecProvider(specProvider), blockTree, new StateProvider(new TrieStore(new MemDb(), LimboLogs.Instance), new MemDb(), LimboLogs.Instance)), new TxPoolConfig(), + TxPool.TxPool txPool = new(ethereumEcdsa, new ChainHeadInfoProvider(new FixedForkActivationChainHeadSpecProvider(specProvider), blockTree, new WorldState(new TrieStore(new MemDb(), LimboLogs.Instance), new MemDb(), LimboLogs.Instance)), new TxPoolConfig(), new TxValidator(specProvider.ChainId), LimboLogs.Instance, transactionComparerProvider.GetDefaultComparer()); IReceiptStorage receiptStorage = new InMemoryReceiptStorage(); diff --git a/src/Nethermind/Nethermind.JsonRpc.Test/Modules/Proof/ProofRpcModuleTests.cs b/src/Nethermind/Nethermind.JsonRpc.Test/Modules/Proof/ProofRpcModuleTests.cs index 1546039465d..bab7705398e 100644 --- a/src/Nethermind/Nethermind.JsonRpc.Test/Modules/Proof/ProofRpcModuleTests.cs +++ b/src/Nethermind/Nethermind.JsonRpc.Test/Modules/Proof/ProofRpcModuleTests.cs @@ -27,6 +27,7 @@ using NUnit.Framework; using System.Threading.Tasks; using Nethermind.Consensus.Processing; +using Nethermind.State.Tracing; using NSubstitute; namespace Nethermind.JsonRpc.Test.Modules.Proof @@ -231,7 +232,7 @@ public void Get_receipt_when_block_has_few_receipts(bool withHeader, string expe [Test] public void Can_call() { - StateProvider stateProvider = CreateInitialState(null); + WorldState stateProvider = CreateInitialState(null); Keccak root = stateProvider.StateRoot; Block block = Build.A.Block.WithParent(_blockTree.Head).WithStateRoot(root).TestObject; @@ -256,7 +257,7 @@ public void Can_call() [Test] public void Can_call_by_hash() { - StateProvider stateProvider = CreateInitialState(null); + WorldState stateProvider = CreateInitialState(null); Keccak root = stateProvider.StateRoot; Block block = Build.A.Block.WithParent(_blockTree.Head).WithStateRoot(root).TestObject; @@ -758,7 +759,7 @@ public void Can_call_with_mix_of_everything_and_storage_from_another_account_wro private CallResultWithProof TestCallWithCode(byte[] code, Address? from = null) { - StateProvider stateProvider = CreateInitialState(code); + WorldState stateProvider = CreateInitialState(code); Keccak root = stateProvider.StateRoot; Block block = Build.A.Block.WithParent(_blockTree.Head!).WithStateRoot(root).WithBeneficiary(TestItem.AddressD).TestObject; @@ -796,17 +797,13 @@ private CallResultWithProof TestCallWithCode(byte[] code, Address? from = null) private void TestCallWithStorageAndCode(byte[] code, UInt256 gasPrice, Address? from = null) { - StateProvider stateProvider = CreateInitialState(code); - StorageProvider storageProvider = new(new TrieStore(_dbProvider.StateDb, LimboLogs.Instance), stateProvider, LimboLogs.Instance); + WorldState stateProvider = CreateInitialState(code); for (int i = 0; i < 10000; i++) { - storageProvider.Set(new StorageCell(TestItem.AddressB, (UInt256)i), i.ToBigEndianByteArray()); + stateProvider.Set(new StorageCell(TestItem.AddressB, (UInt256)i), i.ToBigEndianByteArray()); } - storageProvider.Commit(); - storageProvider.CommitTrees(0); - stateProvider.Commit(MainnetSpecProvider.Instance.GenesisSpec, NullStateTracer.Instance); stateProvider.CommitTree(0); @@ -871,9 +868,9 @@ private void TestCallWithStorageAndCode(byte[] code, UInt256 gasPrice, Address? Assert.True(response.Contains("\"result\"")); } - private StateProvider CreateInitialState(byte[] code) + private WorldState CreateInitialState(byte[] code) { - StateProvider stateProvider = new(new TrieStore(_dbProvider.StateDb, LimboLogs.Instance), _dbProvider.CodeDb, LimboLogs.Instance); + WorldState stateProvider = new(new TrieStore(_dbProvider.StateDb, LimboLogs.Instance), _dbProvider.CodeDb, LimboLogs.Instance); AddAccount(stateProvider, TestItem.AddressA, 1.Ether()); AddAccount(stateProvider, TestItem.AddressB, 1.Ether()); @@ -892,17 +889,15 @@ private StateProvider CreateInitialState(byte[] code) return stateProvider; } - private void AddAccount(StateProvider stateProvider, Address account, UInt256 initialBalance) + private void AddAccount(WorldState stateProvider, Address account, UInt256 initialBalance) { stateProvider.CreateAccount(account, initialBalance); stateProvider.Commit(MuirGlacier.Instance, NullStateTracer.Instance); } - private void AddCode(StateProvider stateProvider, Address account, byte[] code) + private void AddCode(WorldState stateProvider, Address account, byte[] code) { - Keccak codeHash = stateProvider.UpdateCode(code); - stateProvider.UpdateCodeHash(account, codeHash, MuirGlacier.Instance); - + stateProvider.InsertCode(account, code, MuirGlacier.Instance); stateProvider.Commit(MainnetSpecProvider.Instance.GenesisSpec, NullStateTracer.Instance); } } diff --git a/src/Nethermind/Nethermind.JsonRpc.Test/Modules/Trace/ParityStyleTracerTests.cs b/src/Nethermind/Nethermind.JsonRpc.Test/Modules/Trace/ParityStyleTracerTests.cs index a689fdf3cc0..9d7d196d877 100644 --- a/src/Nethermind/Nethermind.JsonRpc.Test/Modules/Trace/ParityStyleTracerTests.cs +++ b/src/Nethermind/Nethermind.JsonRpc.Test/Modules/Trace/ParityStyleTracerTests.cs @@ -59,13 +59,12 @@ public void Setup() MemDb stateDb = new(); MemDb codeDb = new(); ITrieStore trieStore = new TrieStore(stateDb, LimboLogs.Instance).AsReadOnly(); - StateProvider stateProvider = new(trieStore, codeDb, LimboLogs.Instance); - StorageProvider storageProvider = new(trieStore, stateProvider, LimboLogs.Instance); + WorldState stateProvider = new(trieStore, codeDb, LimboLogs.Instance); StateReader stateReader = new StateReader(trieStore, codeDb, LimboLogs.Instance); BlockhashProvider blockhashProvider = new(_blockTree, LimboLogs.Instance); VirtualMachine virtualMachine = new(blockhashProvider, specProvider, LimboLogs.Instance); - TransactionProcessor transactionProcessor = new(specProvider, stateProvider, storageProvider, virtualMachine, LimboLogs.Instance); + TransactionProcessor transactionProcessor = new(specProvider, stateProvider, virtualMachine, LimboLogs.Instance); _poSSwitcher = Substitute.For(); BlockProcessor blockProcessor = new( @@ -74,7 +73,6 @@ public void Setup() new MergeRpcRewardCalculator(NoBlockRewards.Instance, _poSSwitcher), new BlockProcessor.BlockValidationTransactionsExecutor(transactionProcessor, stateProvider), stateProvider, - storageProvider, NullReceiptStorage.Instance, NullWitnessCollector.Instance, LimboLogs.Instance); diff --git a/src/Nethermind/Nethermind.JsonRpc/Modules/RpcBlockTransactionsExecutor.cs b/src/Nethermind/Nethermind.JsonRpc/Modules/RpcBlockTransactionsExecutor.cs index 53c4c47cd0d..63dbf44dc05 100644 --- a/src/Nethermind/Nethermind.JsonRpc/Modules/RpcBlockTransactionsExecutor.cs +++ b/src/Nethermind/Nethermind.JsonRpc/Modules/RpcBlockTransactionsExecutor.cs @@ -9,7 +9,7 @@ namespace Nethermind.JsonRpc.Modules { public class RpcBlockTransactionsExecutor : BlockProcessor.BlockValidationTransactionsExecutor { - public RpcBlockTransactionsExecutor(ITransactionProcessor transactionProcessor, IStateProvider stateProvider) + public RpcBlockTransactionsExecutor(ITransactionProcessor transactionProcessor, IWorldState stateProvider) : base(new TraceTransactionProcessorAdapter(transactionProcessor), stateProvider) { } diff --git a/src/Nethermind/Nethermind.Merge.AuRa/AuRaMergeBlockProcessor.cs b/src/Nethermind/Nethermind.Merge.AuRa/AuRaMergeBlockProcessor.cs index 31376c30368..9e675bab24c 100644 --- a/src/Nethermind/Nethermind.Merge.AuRa/AuRaMergeBlockProcessor.cs +++ b/src/Nethermind/Nethermind.Merge.AuRa/AuRaMergeBlockProcessor.cs @@ -25,8 +25,7 @@ public AuRaMergeBlockProcessor( IBlockValidator blockValidator, IRewardCalculator rewardCalculator, IBlockProcessor.IBlockTransactionsExecutor blockTransactionsExecutor, - IStateProvider stateProvider, - IStorageProvider storageProvider, + IWorldState stateProvider, IReceiptStorage receiptStorage, ILogManager logManager, IBlockTree blockTree, @@ -40,7 +39,6 @@ public AuRaMergeBlockProcessor( rewardCalculator, blockTransactionsExecutor, stateProvider, - storageProvider, receiptStorage, logManager, blockTree, diff --git a/src/Nethermind/Nethermind.Merge.AuRa/AuRaMergeBlockProducerEnvFactory.cs b/src/Nethermind/Nethermind.Merge.AuRa/AuRaMergeBlockProducerEnvFactory.cs index ec0fe81ac6c..a16c283a4ec 100644 --- a/src/Nethermind/Nethermind.Merge.AuRa/AuRaMergeBlockProducerEnvFactory.cs +++ b/src/Nethermind/Nethermind.Merge.AuRa/AuRaMergeBlockProducerEnvFactory.cs @@ -79,7 +79,6 @@ protected override BlockProcessor CreateBlockProcessor( rewardCalculatorSource.Get(readOnlyTxProcessingEnv.TransactionProcessor), TransactionsExecutorFactory.Create(readOnlyTxProcessingEnv), readOnlyTxProcessingEnv.StateProvider, - readOnlyTxProcessingEnv.StorageProvider, receiptStorage, logManager, _blockTree, diff --git a/src/Nethermind/Nethermind.Merge.AuRa/InitializationSteps/InitializeBlockchainAuRaMerge.cs b/src/Nethermind/Nethermind.Merge.AuRa/InitializationSteps/InitializeBlockchainAuRaMerge.cs index 1a98e36f319..d599ae32a96 100644 --- a/src/Nethermind/Nethermind.Merge.AuRa/InitializationSteps/InitializeBlockchainAuRaMerge.cs +++ b/src/Nethermind/Nethermind.Merge.AuRa/InitializationSteps/InitializeBlockchainAuRaMerge.cs @@ -32,9 +32,8 @@ protected override BlockProcessor NewBlockProcessor(AuRaNethermindApi api, ITxFi _api.SpecProvider!, _api.BlockValidator!, _api.RewardCalculatorSource!.Get(_api.TransactionProcessor!), - new BlockProcessor.BlockValidationTransactionsExecutor(_api.TransactionProcessor!, _api.StateProvider!), - _api.StateProvider!, - _api.StorageProvider!, + new BlockProcessor.BlockValidationTransactionsExecutor(_api.TransactionProcessor!, _api.WorldState!), + _api.WorldState!, _api.ReceiptStorage!, _api.LogManager, _api.BlockTree!, diff --git a/src/Nethermind/Nethermind.Merge.Plugin.Test/EngineModuleTests.Setup.cs b/src/Nethermind/Nethermind.Merge.Plugin.Test/EngineModuleTests.Setup.cs index 84b46854baa..83f1c4ed436 100644 --- a/src/Nethermind/Nethermind.Merge.Plugin.Test/EngineModuleTests.Setup.cs +++ b/src/Nethermind/Nethermind.Merge.Plugin.Test/EngineModuleTests.Setup.cs @@ -220,7 +220,6 @@ protected override IBlockProcessor CreateBlockProcessor() NoBlockRewards.Instance, new BlockProcessor.BlockValidationTransactionsExecutor(TxProcessor, State), State, - Storage, ReceiptStorage, NullWitnessCollector.Instance, LogManager); diff --git a/src/Nethermind/Nethermind.Merge.Plugin/BlockProduction/PostMergeBlockProducer.cs b/src/Nethermind/Nethermind.Merge.Plugin/BlockProduction/PostMergeBlockProducer.cs index 0e5533dd5df..eebd64ff0c3 100644 --- a/src/Nethermind/Nethermind.Merge.Plugin/BlockProduction/PostMergeBlockProducer.cs +++ b/src/Nethermind/Nethermind.Merge.Plugin/BlockProduction/PostMergeBlockProducer.cs @@ -26,7 +26,7 @@ public PostMergeBlockProducer( IBlockchainProcessor processor, IBlockTree blockTree, IBlockProductionTrigger blockProductionTrigger, - IStateProvider stateProvider, + IWorldState stateProvider, IGasLimitCalculator gasLimitCalculator, ISealEngine sealEngine, ITimestamper timestamper, diff --git a/src/Nethermind/Nethermind.Merge.Plugin/MergePlugin.cs b/src/Nethermind/Nethermind.Merge.Plugin/MergePlugin.cs index 74abfcf4664..8651a689396 100644 --- a/src/Nethermind/Nethermind.Merge.Plugin/MergePlugin.cs +++ b/src/Nethermind/Nethermind.Merge.Plugin/MergePlugin.cs @@ -258,7 +258,7 @@ public Task InitRpcModules() if (_api.RpcModuleProvider is null) throw new ArgumentNullException(nameof(_api.RpcModuleProvider)); if (_api.BlockTree is null) throw new ArgumentNullException(nameof(_api.BlockTree)); if (_api.BlockchainProcessor is null) throw new ArgumentNullException(nameof(_api.BlockchainProcessor)); - if (_api.StateProvider is null) throw new ArgumentNullException(nameof(_api.StateProvider)); + if (_api.WorldState is null) throw new ArgumentNullException(nameof(_api.WorldState)); if (_api.HeaderValidator is null) throw new ArgumentNullException(nameof(_api.HeaderValidator)); if (_api.EthSyncingInfo is null) throw new ArgumentNullException(nameof(_api.EthSyncingInfo)); if (_api.Sealer is null) throw new ArgumentNullException(nameof(_api.Sealer)); diff --git a/src/Nethermind/Nethermind.Mev.Test/MevRpcModuleTests.TestMevRpcBlockchain.cs b/src/Nethermind/Nethermind.Mev.Test/MevRpcModuleTests.TestMevRpcBlockchain.cs index 0f6bf40e3e8..3e6e6b235e0 100644 --- a/src/Nethermind/Nethermind.Mev.Test/MevRpcModuleTests.TestMevRpcBlockchain.cs +++ b/src/Nethermind/Nethermind.Mev.Test/MevRpcModuleTests.TestMevRpcBlockchain.cs @@ -204,7 +204,6 @@ protected override BlockProcessor CreateBlockProcessor() NoBlockRewards.Instance, new BlockProcessor.BlockValidationTransactionsExecutor(TxProcessor, State), State, - Storage, ReceiptStorage, NullWitnessCollector.Instance, LogManager); diff --git a/src/Nethermind/Nethermind.Mev/MevBlockProductionTransactionsExecutor.cs b/src/Nethermind/Nethermind.Mev/MevBlockProductionTransactionsExecutor.cs index a43a78af10f..f0582000f77 100644 --- a/src/Nethermind/Nethermind.Mev/MevBlockProductionTransactionsExecutor.cs +++ b/src/Nethermind/Nethermind.Mev/MevBlockProductionTransactionsExecutor.cs @@ -23,9 +23,7 @@ namespace Nethermind.Mev // this looks super complex, hmm, is it needed? public class MevBlockProductionTransactionsExecutor : BlockProcessor.BlockProductionTransactionsExecutor { - private readonly IStateProvider _stateProvider; - private readonly IStorageProvider _storageProvider; - private readonly IWorldState _worldState; + private readonly IWorldState _stateProvider; public MevBlockProductionTransactionsExecutor( ReadOnlyTxProcessingEnv readOnlyTxProcessingEnv, @@ -34,7 +32,6 @@ public MevBlockProductionTransactionsExecutor( this( readOnlyTxProcessingEnv.TransactionProcessor, readOnlyTxProcessingEnv.StateProvider, - readOnlyTxProcessingEnv.StorageProvider, specProvider, logManager) { @@ -42,15 +39,12 @@ public MevBlockProductionTransactionsExecutor( private MevBlockProductionTransactionsExecutor( ITransactionProcessor transactionProcessor, - IStateProvider stateProvider, - IStorageProvider storageProvider, + IWorldState stateProvider, ISpecProvider specProvider, ILogManager logManager) - : base(transactionProcessor, stateProvider, storageProvider, specProvider, logManager) + : base(transactionProcessor, stateProvider, specProvider, logManager) { _stateProvider = stateProvider; - _storageProvider = storageProvider; - _worldState = new WorldState(stateProvider, storageProvider); } public override TxReceipt[] ProcessTransactions(Block block, ProcessingOptions processingOptions, BlockReceiptsTracer receiptsTracer, IReleaseSpec spec) @@ -74,7 +68,7 @@ public override TxReceipt[] ProcessTransactions(Block block, ProcessingOptions p } else { - // otherwise process transaction as usual + // otherwise process transaction as usual TxAction action = ProcessTransaction(block, currentTx, transactionsInBlock.Count, receiptsTracer, processingOptions, transactionsInBlock); if (action == TxAction.Stop) break; } @@ -124,7 +118,6 @@ public override TxReceipt[] ProcessTransactions(Block block, ProcessingOptions p } _stateProvider.Commit(spec, receiptsTracer); - _storageProvider.Commit(receiptsTracer); SetTransactions(block, transactionsInBlock); return receiptsTracer.TxReceipts.ToArray(); @@ -137,7 +130,7 @@ private TxAction ProcessBundle(Block block, ProcessingOptions processingOptions) { - Snapshot snapshot = _worldState.TakeSnapshot(); + Snapshot snapshot = _stateProvider.TakeSnapshot(); int receiptSnapshot = receiptsTracer.TakeSnapshot(); UInt256 initialBalance = _stateProvider.GetBalance(block.Header.GasBeneficiary!); @@ -178,7 +171,7 @@ bool CheckFeeNotManipulated() } else { - _worldState.Restore(snapshot); + _stateProvider.Restore(snapshot); receiptsTracer.Restore(receiptSnapshot); for (int index = 0; index < bundleTransactions.Count; index++) { diff --git a/src/Nethermind/Nethermind.Network.Benchmark/Eth62ProtocolHandlerBenchmarks.cs b/src/Nethermind/Nethermind.Network.Benchmark/Eth62ProtocolHandlerBenchmarks.cs index 3c749db7def..9eb1afc1e71 100644 --- a/src/Nethermind/Nethermind.Network.Benchmark/Eth62ProtocolHandlerBenchmarks.cs +++ b/src/Nethermind/Nethermind.Network.Benchmark/Eth62ProtocolHandlerBenchmarks.cs @@ -53,7 +53,7 @@ public void SetUp() NodeStatsManager stats = new NodeStatsManager(TimerFactory.Default, LimboLogs.Instance); var ecdsa = new EthereumEcdsa(TestBlockchainIds.ChainId, LimboLogs.Instance); var tree = Build.A.BlockTree().TestObject; - var stateProvider = new StateProvider(new TrieStore(new MemDb(), LimboLogs.Instance), new MemDb(), LimboLogs.Instance); + var stateProvider = new WorldState(new TrieStore(new MemDb(), LimboLogs.Instance), new MemDb(), LimboLogs.Instance); var specProvider = MainnetSpecProvider.Instance; TxPool.TxPool txPool = new TxPool.TxPool( ecdsa, diff --git a/src/Nethermind/Nethermind.PerfTest/Program.cs b/src/Nethermind/Nethermind.PerfTest/Program.cs index 9a5048443fd..7902f163b19 100644 --- a/src/Nethermind/Nethermind.PerfTest/Program.cs +++ b/src/Nethermind/Nethermind.PerfTest/Program.cs @@ -331,8 +331,7 @@ private static async Task RunBenchmarkBlocks() stateProvider.CreateAccount(address, allocation.Balance); if (allocation.Code != null) { - Keccak codeHash = stateProvider.UpdateCode(allocation.Code); - stateProvider.UpdateCodeHash(address, codeHash, specProvider.GenesisSpec); + stateProvider.InsertCode(address, allocation.Code, specProvider.GenesisSpec); } if (allocation.Constructor != null) diff --git a/src/Nethermind/Nethermind.Runner.Test/Ethereum/ContextWithMocks.cs b/src/Nethermind/Nethermind.Runner.Test/Ethereum/ContextWithMocks.cs index 65721ff5bcb..0874c1ff690 100644 --- a/src/Nethermind/Nethermind.Runner.Test/Ethereum/ContextWithMocks.cs +++ b/src/Nethermind/Nethermind.Runner.Test/Ethereum/ContextWithMocks.cs @@ -93,9 +93,8 @@ public static NethermindApi ContextWithMocks() => SealValidator = Substitute.For(), SessionMonitor = Substitute.For(), SnapProvider = Substitute.For(), - StateProvider = Substitute.For(), + WorldState = Substitute.For(), StateReader = Substitute.For(), - StorageProvider = Substitute.For(), TransactionProcessor = Substitute.For(), TxSender = Substitute.For(), BlockProcessingQueue = Substitute.For(), diff --git a/src/Nethermind/Nethermind.State.Test.Runner/StateTestTxTracer.cs b/src/Nethermind/Nethermind.State.Test.Runner/StateTestTxTracer.cs index 57f4e8409d5..6f57b618ea9 100644 --- a/src/Nethermind/Nethermind.State.Test.Runner/StateTestTxTracer.cs +++ b/src/Nethermind/Nethermind.State.Test.Runner/StateTestTxTracer.cs @@ -10,6 +10,7 @@ using Nethermind.Int256; using Nethermind.Evm; using Nethermind.Evm.Tracing; +using Nethermind.State.Tracing; namespace Nethermind.State.Test.Runner { diff --git a/src/Nethermind/Nethermind.State.Test/StateProviderTests.cs b/src/Nethermind/Nethermind.State.Test/StateProviderTests.cs index 82d23756946..e8718dec1c6 100644 --- a/src/Nethermind/Nethermind.State.Test/StateProviderTests.cs +++ b/src/Nethermind/Nethermind.State.Test/StateProviderTests.cs @@ -40,12 +40,12 @@ public void Setup() public void Eip_158_zero_value_transfer_deletes() { var trieStore = new TrieStore(new MemDb(), Logger); - StateProvider frontierProvider = new(trieStore, _codeDb, Logger); + WorldState frontierProvider = new(trieStore, _codeDb, Logger); frontierProvider.CreateAccount(_address1, 0); frontierProvider.Commit(Frontier.Instance); frontierProvider.CommitTree(0); - StateProvider provider = new(trieStore, _codeDb, Logger); + WorldState provider = new(trieStore, _codeDb, Logger); provider.StateRoot = frontierProvider.StateRoot; provider.AddToBalance(_address1, 0, SpuriousDragon.Instance); @@ -59,14 +59,14 @@ public void Eip_158_zero_value_transfer_deletes() public void Eip_158_touch_zero_value_system_account_is_not_deleted() { TrieStore trieStore = new(new MemDb(), Logger); - StateProvider provider = new(trieStore, _codeDb, Logger); + WorldState provider = new(trieStore, _codeDb, Logger); var systemUser = Address.SystemUser; provider.CreateAccount(systemUser, 0); provider.Commit(Homestead.Instance); var releaseSpec = new ReleaseSpec() { IsEip158Enabled = true }; - provider.UpdateCodeHash(systemUser, Keccak.OfAnEmptyString, releaseSpec); + provider.InsertCode(systemUser, System.Text.Encoding.UTF8.GetBytes(""), releaseSpec); provider.Commit(releaseSpec); provider.GetAccount(systemUser).Should().NotBeNull(); @@ -75,7 +75,7 @@ public void Eip_158_touch_zero_value_system_account_is_not_deleted() [Test] public void Can_dump_state() { - StateProvider provider = new(new TrieStore(new MemDb(), Logger), _codeDb, Logger); + WorldState provider = new(new TrieStore(new MemDb(), Logger), _codeDb, Logger); provider.CreateAccount(TestItem.AddressA, 1.Ether()); provider.Commit(MuirGlacier.Instance); provider.CommitTree(0); @@ -87,7 +87,7 @@ public void Can_dump_state() [Test] public void Can_collect_stats() { - StateProvider provider = new(new TrieStore(new MemDb(), Logger), _codeDb, Logger); + WorldState provider = new(new TrieStore(new MemDb(), Logger), _codeDb, Logger); provider.CreateAccount(TestItem.AddressA, 1.Ether()); provider.Commit(MuirGlacier.Instance); provider.CommitTree(0); @@ -99,7 +99,7 @@ public void Can_collect_stats() [Test] public void Can_accepts_visitors() { - StateProvider provider = new(new TrieStore(new MemDb(), Logger), Substitute.For(), Logger); + WorldState provider = new(new TrieStore(new MemDb(), Logger), Substitute.For(), Logger); provider.CreateAccount(TestItem.AddressA, 1.Ether()); provider.Commit(MuirGlacier.Instance); provider.CommitTree(0); @@ -111,22 +111,22 @@ public void Can_accepts_visitors() [Test] public void Empty_commit_restore() { - StateProvider provider = new(new TrieStore(new MemDb(), Logger), _codeDb, Logger); + WorldState provider = new(new TrieStore(new MemDb(), Logger), _codeDb, Logger); provider.Commit(Frontier.Instance); - provider.Restore(-1); + provider.Restore(Snapshot.Empty); } [Test] public void Update_balance_on_non_existing_account_throws() { - StateProvider provider = new(new TrieStore(new MemDb(), Logger), _codeDb, Logger); + WorldState provider = new(new TrieStore(new MemDb(), Logger), _codeDb, Logger); Assert.Throws(() => provider.AddToBalance(TestItem.AddressA, 1.Ether(), Olympic.Instance)); } [Test] public void Is_empty_account() { - StateProvider provider = new(new TrieStore(new MemDb(), Logger), _codeDb, Logger); + WorldState provider = new(new TrieStore(new MemDb(), Logger), _codeDb, Logger); provider.CreateAccount(_address1, 0); provider.Commit(Frontier.Instance); Assert.True(provider.IsEmptyAccount(_address1)); @@ -135,7 +135,7 @@ public void Is_empty_account() [Test] public void Returns_empty_byte_code_for_non_existing_accounts() { - StateProvider provider = new(new TrieStore(new MemDb(), Logger), _codeDb, Logger); + WorldState provider = new(new TrieStore(new MemDb(), Logger), _codeDb, Logger); byte[] code = provider.GetCode(TestItem.AddressA); code.Should().BeEmpty(); } @@ -143,7 +143,7 @@ public void Returns_empty_byte_code_for_non_existing_accounts() [Test] public void Restore_update_restore() { - StateProvider provider = new(new TrieStore(new MemDb(), Logger), _codeDb, Logger); + WorldState provider = new(new TrieStore(new MemDb(), Logger), _codeDb, Logger); provider.CreateAccount(_address1, 0); provider.AddToBalance(_address1, 1, Frontier.Instance); provider.AddToBalance(_address1, 1, Frontier.Instance); @@ -153,7 +153,7 @@ public void Restore_update_restore() provider.AddToBalance(_address1, 1, Frontier.Instance); provider.AddToBalance(_address1, 1, Frontier.Instance); provider.AddToBalance(_address1, 1, Frontier.Instance); - provider.Restore(4); + provider.Restore(new Snapshot(4, Snapshot.Storage.Empty)); provider.AddToBalance(_address1, 1, Frontier.Instance); provider.AddToBalance(_address1, 1, Frontier.Instance); provider.AddToBalance(_address1, 1, Frontier.Instance); @@ -162,23 +162,23 @@ public void Restore_update_restore() provider.AddToBalance(_address1, 1, Frontier.Instance); provider.AddToBalance(_address1, 1, Frontier.Instance); provider.AddToBalance(_address1, 1, Frontier.Instance); - provider.Restore(4); + provider.Restore(new Snapshot(4, Snapshot.Storage.Empty)); Assert.That(provider.GetBalance(_address1), Is.EqualTo((UInt256)4)); } [Test] public void Keep_in_cache() { - StateProvider provider = new(new TrieStore(new MemDb(), Logger), _codeDb, Logger); + WorldState provider = new(new TrieStore(new MemDb(), Logger), _codeDb, Logger); provider.CreateAccount(_address1, 0); provider.Commit(Frontier.Instance); provider.GetBalance(_address1); provider.AddToBalance(_address1, 1, Frontier.Instance); - provider.Restore(-1); + provider.Restore(Snapshot.Empty); provider.AddToBalance(_address1, 1, Frontier.Instance); - provider.Restore(-1); + provider.Restore(Snapshot.Empty); provider.AddToBalance(_address1, 1, Frontier.Instance); - provider.Restore(-1); + provider.Restore(Snapshot.Empty); Assert.That(provider.GetBalance(_address1), Is.EqualTo(UInt256.Zero)); } @@ -187,38 +187,37 @@ public void Restore_in_the_middle() { byte[] code = new byte[] { 1 }; - StateProvider provider = new(new TrieStore(new MemDb(), Logger), _codeDb, Logger); + WorldState provider = new(new TrieStore(new MemDb(), Logger), _codeDb, Logger); provider.CreateAccount(_address1, 1); provider.AddToBalance(_address1, 1, Frontier.Instance); provider.IncrementNonce(_address1); - Keccak codeHash = provider.UpdateCode(new byte[] { 1 }); - provider.UpdateCodeHash(_address1, codeHash, Frontier.Instance); + provider.InsertCode(_address1, new byte[] { 1 }, Frontier.Instance); provider.UpdateStorageRoot(_address1, Hash2); Assert.That(provider.GetNonce(_address1), Is.EqualTo(UInt256.One)); Assert.That(provider.GetBalance(_address1), Is.EqualTo(UInt256.One + 1)); Assert.That(provider.GetCode(_address1), Is.EqualTo(code)); - provider.Restore(4); + provider.Restore(new Snapshot(4, Snapshot.Storage.Empty)); Assert.That(provider.GetNonce(_address1), Is.EqualTo(UInt256.One)); Assert.That(provider.GetBalance(_address1), Is.EqualTo(UInt256.One + 1)); Assert.That(provider.GetCode(_address1), Is.EqualTo(code)); - provider.Restore(3); + provider.Restore(new Snapshot(3, Snapshot.Storage.Empty)); Assert.That(provider.GetNonce(_address1), Is.EqualTo(UInt256.One)); Assert.That(provider.GetBalance(_address1), Is.EqualTo(UInt256.One + 1)); Assert.That(provider.GetCode(_address1), Is.EqualTo(code)); - provider.Restore(2); + provider.Restore(new Snapshot(2, Snapshot.Storage.Empty)); Assert.That(provider.GetNonce(_address1), Is.EqualTo(UInt256.One)); Assert.That(provider.GetBalance(_address1), Is.EqualTo(UInt256.One + 1)); Assert.That(provider.GetCode(_address1), Is.EqualTo(new byte[0])); - provider.Restore(1); + provider.Restore(new Snapshot(1, Snapshot.Storage.Empty)); Assert.That(provider.GetNonce(_address1), Is.EqualTo(UInt256.Zero)); Assert.That(provider.GetBalance(_address1), Is.EqualTo(UInt256.One + 1)); Assert.That(provider.GetCode(_address1), Is.EqualTo(new byte[0])); - provider.Restore(0); + provider.Restore(new Snapshot(0, Snapshot.Storage.Empty)); Assert.That(provider.GetNonce(_address1), Is.EqualTo(UInt256.Zero)); Assert.That(provider.GetBalance(_address1), Is.EqualTo(UInt256.One)); Assert.That(provider.GetCode(_address1), Is.EqualTo(new byte[0])); - provider.Restore(-1); + provider.Restore(new Snapshot(-1, Snapshot.Storage.Empty)); Assert.That(provider.AccountExists(_address1), Is.EqualTo(false)); } @@ -227,7 +226,7 @@ public void Touch_empty_trace_does_not_throw() { ParityLikeTxTracer tracer = new(Build.A.Block.TestObject, null, ParityTraceTypes.StateDiff); - StateProvider provider = new(new TrieStore(new MemDb(), Logger), _codeDb, Logger); + WorldState provider = new(new TrieStore(new MemDb(), Logger), _codeDb, Logger); provider.CreateAccount(_address1, 0); Account account = provider.GetAccount(_address1); Assert.True(account.IsEmpty); @@ -244,7 +243,7 @@ public void Touch_empty_trace_does_not_throw() [Test] public void Does_not_require_recalculation_after_reset() { - StateProvider provider = new(new TrieStore(new MemDb(), Logger), _codeDb, Logger); + WorldState provider = new(new TrieStore(new MemDb(), Logger), _codeDb, Logger); provider.CreateAccount(TestItem.AddressA, 5); Action action = () => { _ = provider.StateRoot; }; diff --git a/src/Nethermind/Nethermind.State.Test/StateReaderTests.cs b/src/Nethermind/Nethermind.State.Test/StateReaderTests.cs index 51b9692c82f..079f03fecdd 100644 --- a/src/Nethermind/Nethermind.State.Test/StateReaderTests.cs +++ b/src/Nethermind/Nethermind.State.Test/StateReaderTests.cs @@ -32,7 +32,7 @@ public async Task Can_ask_about_balance_in_parallel() { IReleaseSpec spec = MainnetSpecProvider.Instance.GetSpec((ForkActivation)MainnetSpecProvider.ConstantinopleFixBlockNumber); MemDb stateDb = new(); - StateProvider provider = + WorldState provider = new(new TrieStore(stateDb, Logger), Substitute.For(), Logger); provider.CreateAccount(_address1, 0); provider.AddToBalance(_address1, 1, spec); @@ -75,12 +75,11 @@ public async Task Can_ask_about_storage_in_parallel() IReleaseSpec spec = MuirGlacier.Instance; MemDb stateDb = new(); TrieStore trieStore = new(stateDb, Logger); - StateProvider provider = new(trieStore, new MemDb(), Logger); - StorageProvider storageProvider = new(trieStore, provider, Logger); + WorldState provider = new(trieStore, new MemDb(), Logger); void UpdateStorageValue(byte[] newValue) { - storageProvider.Set(storageCell, newValue); + provider.Set(storageCell, newValue); } void AddOneToBalance() @@ -90,8 +89,6 @@ void AddOneToBalance() void CommitEverything() { - storageProvider.Commit(); - storageProvider.CommitTrees(0); provider.Commit(spec); provider.CommitTree(0); } @@ -138,19 +135,16 @@ public void Non_existing() MemDb stateDb = new(); TrieStore trieStore = new(stateDb, Logger); - StateProvider provider = new(trieStore, new MemDb(), Logger); - StorageProvider storageProvider = new(trieStore, provider, Logger); + WorldState provider = new(trieStore, new MemDb(), Logger); void CommitEverything() { - storageProvider.Commit(); - storageProvider.CommitTrees(0); provider.Commit(spec); provider.CommitTree(0); } provider.CreateAccount(_address1, 1); - storageProvider.Set(storageCell, new byte[] { 1 }); + provider.Set(storageCell, new byte[] { 1 }); CommitEverything(); Keccak stateRoot0 = provider.StateRoot; @@ -197,8 +191,7 @@ public async Task Get_storage() StorageCell storageCell = new(_address1, UInt256.One); TrieStore trieStore = new(dbProvider.StateDb, Logger); - StateProvider state = new(trieStore, dbProvider.CodeDb, Logger); - StorageProvider storage = new(trieStore, state, Logger); + WorldState state = new(trieStore, dbProvider.CodeDb, Logger); /* to start with we need to create an account that we will be setting storage at */ state.CreateAccount(storageCell.Address, UInt256.One); @@ -208,9 +201,7 @@ public async Task Get_storage() /* at this stage we have an account with empty storage at the address that we want to test */ byte[] initialValue = new byte[] { 1, 2, 3 }; - storage.Set(storageCell, initialValue); - storage.Commit(); - storage.CommitTrees(2); + state.Set(storageCell, initialValue); state.Commit(MuirGlacier.Instance); state.CommitTree(2); @@ -229,16 +220,11 @@ It is a different stack of objects than the one that is used by the blockchain b byte[] newValue = new byte[] { 1, 2, 3, 4, 5 }; - StateProvider processorStateProvider = + WorldState processorStateProvider = new(trieStore, new MemDb(), LimboLogs.Instance); processorStateProvider.StateRoot = state.StateRoot; - StorageProvider processorStorageProvider = - new(trieStore, processorStateProvider, LimboLogs.Instance); - - processorStorageProvider.Set(storageCell, newValue); - processorStorageProvider.Commit(); - processorStorageProvider.CommitTrees(3); + processorStateProvider.Set(storageCell, newValue); processorStateProvider.Commit(MuirGlacier.Instance); processorStateProvider.CommitTree(3); diff --git a/src/Nethermind/Nethermind.State.Test/StatsCollectorTests.cs b/src/Nethermind/Nethermind.State.Test/StatsCollectorTests.cs index d1c278b9192..1808b511ab4 100644 --- a/src/Nethermind/Nethermind.State.Test/StatsCollectorTests.cs +++ b/src/Nethermind/Nethermind.State.Test/StatsCollectorTests.cs @@ -26,32 +26,26 @@ public void Can_collect_stats([Values(false, true)] bool parallel) MemDb memDb = new(); IDb stateDb = memDb; TrieStore trieStore = new(stateDb, new MemoryLimit(0.MB()), Persist.EveryBlock, LimboLogs.Instance); - StateProvider stateProvider = new(trieStore, stateDb, LimboLogs.Instance); - StorageProvider storageProvider = new(trieStore, stateProvider, LimboLogs.Instance); + WorldState stateProvider = new(trieStore, stateDb, LimboLogs.Instance); stateProvider.CreateAccount(TestItem.AddressA, 1); - Keccak codeHash = stateProvider.UpdateCode(new byte[] { 1, 2, 3 }); - stateProvider.UpdateCodeHash(TestItem.AddressA, codeHash, Istanbul.Instance); + stateProvider.InsertCode(TestItem.AddressA, new byte[] { 1, 2, 3 }, Istanbul.Instance); stateProvider.CreateAccount(TestItem.AddressB, 1); - Keccak codeHash2 = stateProvider.UpdateCode(new byte[] { 1, 2, 3, 4 }); - stateProvider.UpdateCodeHash(TestItem.AddressB, codeHash2, Istanbul.Instance); + stateProvider.InsertCode(TestItem.AddressB, new byte[] { 1, 2, 3, 4 }, Istanbul.Instance); for (int i = 0; i < 1000; i++) { StorageCell storageCell = new(TestItem.AddressA, (UInt256)i); - storageProvider.Set(storageCell, new byte[] { (byte)i }); + stateProvider.Set(storageCell, new byte[] { (byte)i }); } - storageProvider.Commit(); stateProvider.Commit(Istanbul.Instance); - storageProvider.CommitTrees(0); stateProvider.CommitTree(0); - storageProvider.CommitTrees(1); stateProvider.CommitTree(1); - memDb.Delete(codeHash2); // missing code + memDb.Delete(Keccak.Compute(new byte[] { 1, 2, 3, 4 })); // missing code Keccak storageKey = new("0x345e54154080bfa9e8f20c99d7a0139773926479bc59e5b4f830ad94b6425332"); memDb.Delete(storageKey); // deletes some storage trieStore.ClearCache(); diff --git a/src/Nethermind/Nethermind.State.Test/StorageProviderTests.cs b/src/Nethermind/Nethermind.State.Test/StorageProviderTests.cs index 67b514e1757..259de727843 100644 --- a/src/Nethermind/Nethermind.State.Test/StorageProviderTests.cs +++ b/src/Nethermind/Nethermind.State.Test/StorageProviderTests.cs @@ -43,15 +43,14 @@ public class StorageProviderTests public void Empty_commit_restore() { Context ctx = new(); - StorageProvider provider = BuildStorageProvider(ctx); - provider.Commit(); - provider.Restore(Snapshot.Storage.Empty); + WorldState provider = BuildStorageProvider(ctx); + provider.Commit(Frontier.Instance); + provider.Restore(Snapshot.Empty); } - private StorageProvider BuildStorageProvider(Context ctx) + private WorldState BuildStorageProvider(Context ctx) { - StorageProvider provider = new(new TrieStore(new MemDb(), LogManager), ctx.StateProvider, LogManager); - return provider; + return ctx.StateProvider; } [TestCase(-1)] @@ -61,11 +60,11 @@ private StorageProvider BuildStorageProvider(Context ctx) public void Same_address_same_index_different_values_restore(int snapshot) { Context ctx = new(); - StorageProvider provider = BuildStorageProvider(ctx); + WorldState provider = BuildStorageProvider(ctx); provider.Set(new StorageCell(ctx.Address1, 1), _values[1]); provider.Set(new StorageCell(ctx.Address1, 1), _values[2]); provider.Set(new StorageCell(ctx.Address1, 1), _values[3]); - provider.Restore(snapshot); + provider.Restore(Snapshot.EmptyPosition, snapshot, Snapshot.EmptyPosition); Assert.That(provider.Get(new StorageCell(ctx.Address1, 1)), Is.EqualTo(_values[snapshot + 1])); } @@ -74,16 +73,16 @@ public void Same_address_same_index_different_values_restore(int snapshot) public void Keep_in_cache() { Context ctx = new(); - StorageProvider provider = BuildStorageProvider(ctx); + WorldState provider = BuildStorageProvider(ctx); provider.Set(new StorageCell(ctx.Address1, 1), _values[1]); - provider.Commit(); + provider.Commit(Frontier.Instance); provider.Get(new StorageCell(ctx.Address1, 1)); provider.Set(new StorageCell(ctx.Address1, 1), _values[2]); - provider.Restore(-1); + provider.Restore(Snapshot.EmptyPosition, -1, Snapshot.EmptyPosition); provider.Set(new StorageCell(ctx.Address1, 1), _values[2]); - provider.Restore(-1); + provider.Restore(Snapshot.EmptyPosition, -1, Snapshot.EmptyPosition); provider.Set(new StorageCell(ctx.Address1, 1), _values[2]); - provider.Restore(-1); + provider.Restore(Snapshot.EmptyPosition, -1, Snapshot.EmptyPosition); Assert.That(provider.Get(new StorageCell(ctx.Address1, 1)), Is.EqualTo(_values[1])); } @@ -94,11 +93,11 @@ public void Keep_in_cache() public void Same_address_different_index(int snapshot) { Context ctx = new(); - StorageProvider provider = BuildStorageProvider(ctx); + WorldState provider = BuildStorageProvider(ctx); provider.Set(new StorageCell(ctx.Address1, 1), _values[1]); provider.Set(new StorageCell(ctx.Address1, 2), _values[2]); provider.Set(new StorageCell(ctx.Address1, 3), _values[3]); - provider.Restore(snapshot); + provider.Restore(Snapshot.EmptyPosition, snapshot, Snapshot.EmptyPosition); Assert.That(provider.Get(new StorageCell(ctx.Address1, 1)), Is.EqualTo(_values[Math.Min(snapshot + 1, 1)])); } @@ -107,24 +106,24 @@ public void Same_address_different_index(int snapshot) public void Commit_restore() { Context ctx = new(); - StorageProvider provider = BuildStorageProvider(ctx); + WorldState provider = BuildStorageProvider(ctx); provider.Set(new StorageCell(ctx.Address1, 1), _values[1]); provider.Set(new StorageCell(ctx.Address1, 2), _values[2]); provider.Set(new StorageCell(ctx.Address1, 3), _values[3]); - provider.Commit(); + provider.Commit(Frontier.Instance); provider.Set(new StorageCell(ctx.Address2, 1), _values[4]); provider.Set(new StorageCell(ctx.Address2, 2), _values[5]); provider.Set(new StorageCell(ctx.Address2, 3), _values[6]); - provider.Commit(); + provider.Commit(Frontier.Instance); provider.Set(new StorageCell(ctx.Address1, 1), _values[7]); provider.Set(new StorageCell(ctx.Address1, 2), _values[8]); provider.Set(new StorageCell(ctx.Address1, 3), _values[9]); - provider.Commit(); + provider.Commit(Frontier.Instance); provider.Set(new StorageCell(ctx.Address2, 1), _values[10]); provider.Set(new StorageCell(ctx.Address2, 2), _values[11]); provider.Set(new StorageCell(ctx.Address2, 3), _values[12]); - provider.Commit(); - provider.Restore(-1); + provider.Commit(Frontier.Instance); + provider.Restore(Snapshot.Empty); Assert.That(provider.Get(new StorageCell(ctx.Address1, 1)), Is.EqualTo(_values[7])); Assert.That(provider.Get(new StorageCell(ctx.Address1, 2)), Is.EqualTo(_values[8])); @@ -138,12 +137,12 @@ public void Commit_restore() public void Commit_no_changes() { Context ctx = new(); - StorageProvider provider = BuildStorageProvider(ctx); + WorldState provider = BuildStorageProvider(ctx); provider.Set(new StorageCell(ctx.Address1, 1), _values[1]); provider.Set(new StorageCell(ctx.Address1, 2), _values[2]); provider.Set(new StorageCell(ctx.Address1, 3), _values[3]); - provider.Restore(-1); - provider.Commit(); + provider.Restore(Snapshot.Empty); + provider.Commit(Frontier.Instance); Assert.IsTrue(provider.Get(new StorageCell(ctx.Address1, 1)).IsZero()); } @@ -152,27 +151,27 @@ public void Commit_no_changes() public void Commit_no_changes_2() { Context ctx = new(); - StorageProvider provider = BuildStorageProvider(ctx); + WorldState provider = BuildStorageProvider(ctx); provider.Get(new StorageCell(ctx.Address1, 1)); provider.Get(new StorageCell(ctx.Address1, 1)); provider.Get(new StorageCell(ctx.Address1, 1)); provider.Set(new StorageCell(ctx.Address1, 1), _values[1]); provider.Set(new StorageCell(ctx.Address1, 1), _values[2]); provider.Set(new StorageCell(ctx.Address1, 1), _values[3]); - provider.Restore(2); - provider.Restore(1); - provider.Restore(0); + provider.Restore(Snapshot.EmptyPosition, 2, Snapshot.EmptyPosition); + provider.Restore(Snapshot.EmptyPosition, 1, Snapshot.EmptyPosition); + provider.Restore(Snapshot.EmptyPosition, 0, Snapshot.EmptyPosition); provider.Get(new StorageCell(ctx.Address1, 1)); provider.Get(new StorageCell(ctx.Address1, 1)); provider.Get(new StorageCell(ctx.Address1, 1)); provider.Set(new StorageCell(ctx.Address1, 1), _values[1]); provider.Set(new StorageCell(ctx.Address1, 1), _values[2]); provider.Set(new StorageCell(ctx.Address1, 1), _values[3]); - provider.Restore(-1); + provider.Restore(Snapshot.EmptyPosition, -1, Snapshot.EmptyPosition); provider.Get(new StorageCell(ctx.Address1, 1)); provider.Get(new StorageCell(ctx.Address1, 1)); provider.Get(new StorageCell(ctx.Address1, 1)); - provider.Commit(); + provider.Commit(Frontier.Instance); Assert.True(provider.Get(new StorageCell(ctx.Address1, 1)).IsZero()); } @@ -182,18 +181,17 @@ public void Commit_trees_clear_caches_get_previous_root() { Context ctx = new(); // block 1 - StorageProvider storageProvider = BuildStorageProvider(ctx); + WorldState storageProvider = BuildStorageProvider(ctx); storageProvider.Set(new StorageCell(ctx.Address1, 1), _values[1]); - storageProvider.Commit(); + storageProvider.Commit(Frontier.Instance); ctx.StateProvider.Commit(Frontier.Instance); - storageProvider.CommitTrees(0); ctx.StateProvider.CommitTree(0); // block 2 Keccak stateRoot = ctx.StateProvider.StateRoot; storageProvider.Set(new StorageCell(ctx.Address1, 1), _values[2]); - storageProvider.Commit(); + storageProvider.Commit(Frontier.Instance); ctx.StateProvider.Commit(Frontier.Instance); // revert @@ -211,13 +209,13 @@ public void Can_commit_when_exactly_at_capacity_regression() { Context ctx = new(); // block 1 - StorageProvider storageProvider = BuildStorageProvider(ctx); + WorldState storageProvider = BuildStorageProvider(ctx); for (int i = 0; i < Resettable.StartCapacity; i++) { storageProvider.Set(new StorageCell(ctx.Address1, 1), _values[i % 2]); } - storageProvider.Commit(); + storageProvider.Commit(Frontier.Instance); ctx.StateProvider.Commit(Frontier.Instance); byte[] valueAfter = storageProvider.Get(new StorageCell(ctx.Address1, 1)); @@ -231,7 +229,7 @@ public void Can_commit_when_exactly_at_capacity_regression() public void Can_tload_uninitialized_locations() { Context ctx = new(); - StorageProvider provider = BuildStorageProvider(ctx); + WorldState provider = BuildStorageProvider(ctx); // Should be 0 if not set Assert.True(provider.GetTransientState(new StorageCell(ctx.Address1, 1)).IsZero()); @@ -249,8 +247,8 @@ public void Can_tload_uninitialized_locations() [Test] public void Can_tload_after_tstore() { - Context ctx = new(); - StorageProvider provider = BuildStorageProvider(ctx); + Context ctx = new Context(); + WorldState provider = BuildStorageProvider(ctx); provider.SetTransientState(new StorageCell(ctx.Address1, 2), _values[1]); Assert.That(provider.GetTransientState(new StorageCell(ctx.Address1, 2)), Is.EqualTo(_values[1])); @@ -267,19 +265,20 @@ public void Can_tload_after_tstore() public void Tload_same_address_same_index_different_values_restore(int snapshot) { Context ctx = new(); - StorageProvider provider = BuildStorageProvider(ctx); - Snapshot.Storage[] snapshots = new Snapshot.Storage[4]; - snapshots[0] = ((IStorageProvider)provider).TakeSnapshot(); + WorldState provider = BuildStorageProvider(ctx); + Snapshot[] snapshots = new Snapshot[4]; + snapshots[0] = provider.TakeSnapshot(); provider.SetTransientState(new StorageCell(ctx.Address1, 1), _values[1]); - snapshots[1] = ((IStorageProvider)provider).TakeSnapshot(); + snapshots[1] = provider.TakeSnapshot(); provider.SetTransientState(new StorageCell(ctx.Address1, 1), _values[2]); - snapshots[2] = ((IStorageProvider)provider).TakeSnapshot(); + snapshots[2] = provider.TakeSnapshot(); provider.SetTransientState(new StorageCell(ctx.Address1, 1), _values[3]); - snapshots[3] = ((IStorageProvider)provider).TakeSnapshot(); + snapshots[3] = provider.TakeSnapshot(); - Assert.That(snapshot, Is.EqualTo(snapshots[snapshot + 1].TransientStorageSnapshot)); + Assert.That(snapshot, Is.EqualTo(snapshots[snapshot + 1].StorageSnapshot.TransientStorageSnapshot)); // Persistent storage is unimpacted by transient storage - Assert.That(snapshots[snapshot + 1].PersistentStorageSnapshot, Is.EqualTo(-1)); + Assert.That(snapshots[snapshot + 1].StorageSnapshot.PersistentStorageSnapshot, Is.EqualTo(-1)); + provider.Restore(snapshots[snapshot + 1]); Assert.That(provider.GetTransientState(new StorageCell(ctx.Address1, 1)), Is.EqualTo(_values[snapshot + 1])); @@ -292,12 +291,12 @@ public void Tload_same_address_same_index_different_values_restore(int snapshot) public void Commit_resets_transient_state() { Context ctx = new(); - StorageProvider provider = BuildStorageProvider(ctx); + WorldState provider = BuildStorageProvider(ctx); provider.SetTransientState(new StorageCell(ctx.Address1, 2), _values[1]); Assert.That(provider.GetTransientState(new StorageCell(ctx.Address1, 2)), Is.EqualTo(_values[1])); - provider.Commit(); + provider.Commit(Frontier.Instance); Assert.True(provider.GetTransientState(new StorageCell(ctx.Address1, 2)).IsZero()); } @@ -308,7 +307,7 @@ public void Commit_resets_transient_state() public void Reset_resets_transient_state() { Context ctx = new(); - StorageProvider provider = BuildStorageProvider(ctx); + WorldState provider = BuildStorageProvider(ctx); provider.SetTransientState(new StorageCell(ctx.Address1, 2), _values[1]); Assert.That(provider.GetTransientState(new StorageCell(ctx.Address1, 2)), Is.EqualTo(_values[1])); @@ -328,24 +327,24 @@ public void Reset_resets_transient_state() public void Transient_state_restores_independent_of_persistent_state(int snapshot) { Context ctx = new(); - StorageProvider provider = BuildStorageProvider(ctx); - Snapshot.Storage[] snapshots = new Snapshot.Storage[4]; + WorldState provider = BuildStorageProvider(ctx); + Snapshot[] snapshots = new Snapshot[4]; // No updates - snapshots[0] = ((IStorageProvider)provider).TakeSnapshot(); + snapshots[0] = provider.TakeSnapshot(); // Only update transient provider.SetTransientState(new StorageCell(ctx.Address1, 1), _values[1]); - snapshots[1] = ((IStorageProvider)provider).TakeSnapshot(); + snapshots[1] = provider.TakeSnapshot(); // Update both provider.SetTransientState(new StorageCell(ctx.Address1, 1), _values[2]); provider.Set(new StorageCell(ctx.Address1, 1), _values[9]); - snapshots[2] = ((IStorageProvider)provider).TakeSnapshot(); + snapshots[2] = provider.TakeSnapshot(); // Only update persistent provider.Set(new StorageCell(ctx.Address1, 1), _values[8]); - snapshots[3] = ((IStorageProvider)provider).TakeSnapshot(); + snapshots[3] = provider.TakeSnapshot(); provider.Restore(snapshots[snapshot + 1]); @@ -354,12 +353,10 @@ public void Transient_state_restores_independent_of_persistent_state(int snapsho { snapshot--; } - - snapshots.Should().Equal( - Snapshot.Storage.Empty, - new Snapshot.Storage(Snapshot.EmptyPosition, 0), - new Snapshot.Storage(0, 1), - new Snapshot.Storage(1, 1)); + snapshots[0].StorageSnapshot.Should().BeEquivalentTo(Snapshot.Storage.Empty); + snapshots[1].StorageSnapshot.Should().BeEquivalentTo(new Snapshot.Storage(Snapshot.EmptyPosition, 0)); + snapshots[2].StorageSnapshot.Should().BeEquivalentTo(new Snapshot.Storage(0, 1)); + snapshots[3].StorageSnapshot.Should().BeEquivalentTo(new Snapshot.Storage(1, 1)); _values[snapshot + 1].Should().BeEquivalentTo(provider.GetTransientState(new StorageCell(ctx.Address1, 1))); } @@ -375,24 +372,24 @@ public void Transient_state_restores_independent_of_persistent_state(int snapsho public void Persistent_state_restores_independent_of_transient_state(int snapshot) { Context ctx = new(); - StorageProvider provider = BuildStorageProvider(ctx); - Snapshot.Storage[] snapshots = new Snapshot.Storage[4]; + WorldState provider = BuildStorageProvider(ctx); + Snapshot[] snapshots = new Snapshot[4]; // No updates - snapshots[0] = ((IStorageProvider)provider).TakeSnapshot(); + snapshots[0] = (provider).TakeSnapshot(); // Only update persistent provider.Set(new StorageCell(ctx.Address1, 1), _values[1]); - snapshots[1] = ((IStorageProvider)provider).TakeSnapshot(); + snapshots[1] = (provider).TakeSnapshot(); // Update both provider.Set(new StorageCell(ctx.Address1, 1), _values[2]); provider.SetTransientState(new StorageCell(ctx.Address1, 1), _values[9]); - snapshots[2] = ((IStorageProvider)provider).TakeSnapshot(); + snapshots[2] = (provider).TakeSnapshot(); // Only update transient provider.SetTransientState(new StorageCell(ctx.Address1, 1), _values[8]); - snapshots[3] = ((IStorageProvider)provider).TakeSnapshot(); + snapshots[3] = (provider).TakeSnapshot(); provider.Restore(snapshots[snapshot + 1]); @@ -403,24 +400,25 @@ public void Persistent_state_restores_independent_of_transient_state(int snapsho } snapshots.Should().Equal( - Snapshot.Storage.Empty, - new Snapshot.Storage(0, Snapshot.EmptyPosition), - new Snapshot.Storage(1, 0), - new Snapshot.Storage(1, 1)); + Snapshot.Empty, + new Snapshot(Snapshot.EmptyPosition, new Snapshot.Storage(0, Snapshot.EmptyPosition)), + new Snapshot(Snapshot.EmptyPosition, new Snapshot.Storage(1, 0)), + new Snapshot(Snapshot.EmptyPosition, new Snapshot.Storage(1, 1)) + ); _values[snapshot + 1].Should().BeEquivalentTo(provider.Get(new StorageCell(ctx.Address1, 1))); } private class Context { - public IStateProvider StateProvider { get; } + public WorldState StateProvider { get; } public readonly Address Address1 = new(Keccak.Compute("1")); public readonly Address Address2 = new(Keccak.Compute("2")); public Context() { - StateProvider = new StateProvider(new TrieStore(new MemDb(), LimboLogs.Instance), Substitute.For(), LogManager); + StateProvider = new WorldState(new TrieStore(new MemDb(), LimboLogs.Instance), Substitute.For(), LogManager); StateProvider.CreateAccount(Address1, 0); StateProvider.CreateAccount(Address2, 0); StateProvider.Commit(Frontier.Instance); diff --git a/src/Nethermind/Nethermind.State.Test/WorldStateTests.cs b/src/Nethermind/Nethermind.State.Test/WorldStateTests.cs deleted file mode 100644 index 216082e3733..00000000000 --- a/src/Nethermind/Nethermind.State.Test/WorldStateTests.cs +++ /dev/null @@ -1,80 +0,0 @@ -// SPDX-FileCopyrightText: 2022 Demerzel Solutions Limited -// SPDX-License-Identifier: LGPL-3.0-only - -using FluentAssertions; -using Nethermind.State; -using NSubstitute; -using NUnit.Framework; - -namespace Nethermind.Store.Test -{ - [TestFixture] - public class WorldStateTests - { - [Test] - public void When_taking_a_snapshot_invokes_take_snapshot_on_both_providers() - { - IStateProvider stateProvider = Substitute.For(); - IStorageProvider storageProvider = Substitute.For(); - - WorldState worldState = new(stateProvider, storageProvider); - worldState.TakeSnapshot(); - - stateProvider.Received().TakeSnapshot(); - storageProvider.Received().TakeSnapshot(); - } - - [Test] - public void When_taking_a_snapshot_return_the_same_value_as_both() - { - IStateProvider stateProvider = Substitute.For(); - IStorageProvider storageProvider = Substitute.For(); - - WorldState worldState = new(stateProvider, storageProvider); - Snapshot snapshot = worldState.TakeSnapshot(); - - snapshot.StateSnapshot.Should().Be(0); - snapshot.StorageSnapshot.PersistentStorageSnapshot.Should().Be(0); - } - - [Test] - public void When_taking_a_snapshot_can_return_non_zero_snapshot_value() - { - IStateProvider stateProvider = Substitute.For(); - IStorageProvider storageProvider = Substitute.For(); - - WorldState worldState = new(stateProvider, storageProvider); - - stateProvider.TakeSnapshot().Returns(1); - storageProvider.TakeSnapshot().Returns(new Snapshot.Storage(2, 3)); - - Snapshot snapshot = worldState.TakeSnapshot(); - snapshot.StateSnapshot.Should().Be(1); - snapshot.StorageSnapshot.PersistentStorageSnapshot.Should().Be(2); - snapshot.StorageSnapshot.TransientStorageSnapshot.Should().Be(3); - } - - [Test] - public void When_taking_a_snapshot_can_specify_transaction_boundary() - { - IStateProvider stateProvider = Substitute.For(); - IStorageProvider storageProvider = Substitute.For(); - - WorldState worldState = new(stateProvider, storageProvider); - _ = worldState.TakeSnapshot(true); - storageProvider.Received().TakeSnapshot(true); - } - - [Test] - public void Can_restore_snapshot() - { - IStateProvider stateProvider = Substitute.For(); - IStorageProvider storageProvider = Substitute.For(); - - WorldState worldState = new(stateProvider, storageProvider); - worldState.Restore(new Snapshot(1, new Snapshot.Storage(2, 1))); - stateProvider.Received().Restore(1); - storageProvider.Received().Restore(new Snapshot.Storage(2, 1)); - } - } -} diff --git a/src/Nethermind/Nethermind.State/IStateProvider.cs b/src/Nethermind/Nethermind.State/IStateProvider.cs deleted file mode 100644 index 277bae6a572..00000000000 --- a/src/Nethermind/Nethermind.State/IStateProvider.cs +++ /dev/null @@ -1,55 +0,0 @@ -// SPDX-FileCopyrightText: 2022 Demerzel Solutions Limited -// SPDX-License-Identifier: LGPL-3.0-only - -using System; -using Nethermind.Core; -using Nethermind.Core.Crypto; -using Nethermind.Core.Specs; -using Nethermind.Int256; -using Nethermind.Trie; - -namespace Nethermind.State -{ - public interface IStateProvider : IReadOnlyStateProvider, IJournal - { - void RecalculateStateRoot(); - - new Keccak StateRoot { get; set; } - - void DeleteAccount(Address address); - - void CreateAccount(Address address, in UInt256 balance); - - void CreateAccount(Address address, in UInt256 balance, in UInt256 nonce); - - void UpdateCodeHash(Address address, Keccak codeHash, IReleaseSpec spec, bool isGenesis = false); - - void AddToBalance(Address address, in UInt256 balanceChange, IReleaseSpec spec); - - void SubtractFromBalance(Address address, in UInt256 balanceChange, IReleaseSpec spec); - - void UpdateStorageRoot(Address address, Keccak storageRoot); - - void IncrementNonce(Address address); - - void DecrementNonce(Address address); - - Keccak UpdateCode(ReadOnlyMemory code); - - /* snapshots */ - - void Commit(IReleaseSpec releaseSpec, bool isGenesis = false); - - void Commit(IReleaseSpec releaseSpec, IStateTracer? stateTracer, bool isGenesis = false); - - void Reset(); - - void CommitTree(long blockNumber); - - /// - /// For witness - /// - /// - void TouchCode(Keccak codeHash); - } -} diff --git a/src/Nethermind/Nethermind.State/IStorageProvider.cs b/src/Nethermind/Nethermind.State/IStorageProvider.cs deleted file mode 100644 index ab4e325fab2..00000000000 --- a/src/Nethermind/Nethermind.State/IStorageProvider.cs +++ /dev/null @@ -1,90 +0,0 @@ -// SPDX-FileCopyrightText: 2022 Demerzel Solutions Limited -// SPDX-License-Identifier: LGPL-3.0-only - -using Nethermind.Core; - -namespace Nethermind.State -{ - /// - /// Interface for the StorageProvider - /// Includes both persistent and transient storage - /// - public interface IStorageProvider : IJournal - { - /// - /// Return the original persistent storage value from the storage cell - /// - /// - /// - byte[] GetOriginal(in StorageCell storageCell); - - /// - /// Get the persistent storage value at the specified storage cell - /// - /// Storage location - /// Value at cell - byte[] Get(in StorageCell storageCell); - - /// - /// Set the provided value to persistent storage at the specified storage cell - /// - /// Storage location - /// Value to store - void Set(in StorageCell storageCell, byte[] newValue); - - /// - /// Get the transient storage value at the specified storage cell - /// - /// Storage location - /// Value at cell - byte[] GetTransientState(in StorageCell storageCell); - - /// - /// Set the provided value to transient storage at the specified storage cell - /// - /// Storage location - /// Value to store - void SetTransientState(in StorageCell storageCell, byte[] newValue); - - /// - /// Reset all storage - /// - void Reset(); - - /// - /// Commit persisent storage trees - /// - /// Current block number - void CommitTrees(long blockNumber); - - /// - /// Commit persistent storage - /// - void Commit(); - - /// - /// Commit persistent storage - /// - /// State tracer - void Commit(IStorageTracer stateTracer); - - /// - /// Creates a restartable snapshot. - /// - /// Indicates new transaction will start here. - /// Snapshot index - /// - /// If is true and there are already changes in then next call to - /// will use changes before this snapshot as original values for this new transaction. - /// - Snapshot.Storage TakeSnapshot(bool newTransactionStart = false); - - Snapshot.Storage IJournal.TakeSnapshot() => TakeSnapshot(); - - /// - /// Clear all storage at specified address - /// - /// Contract address - void ClearStorage(Address address); - } -} diff --git a/src/Nethermind/Nethermind.State/IWorldState.cs b/src/Nethermind/Nethermind.State/IWorldState.cs index 68c68265539..cea4e411e11 100644 --- a/src/Nethermind/Nethermind.State/IWorldState.cs +++ b/src/Nethermind/Nethermind.State/IWorldState.cs @@ -1,22 +1,112 @@ // SPDX-FileCopyrightText: 2022 Demerzel Solutions Limited // SPDX-License-Identifier: LGPL-3.0-only +using System; using Nethermind.Core; +using Nethermind.Core.Crypto; +using Nethermind.Core.Specs; +using Nethermind.Int256; +using Nethermind.State.Tracing; -namespace Nethermind.State +namespace Nethermind.State; +/// +/// Represents state that can be anchored at specific state root, snapshot, committed, reverted. +/// Current format is an intermittent form on the way to a better state management. +/// +public interface IWorldState : IJournal, IReadOnlyStateProvider { /// - /// Represents state that can be anchored at specific state root, snapshot, committed, reverted. - /// Current format is an intermittent form on the way to a better state management. + /// Return the original persistent storage value from the storage cell /// - public interface IWorldState : IJournal - { - IStorageProvider StorageProvider { get; } + /// + /// + byte[] GetOriginal(in StorageCell storageCell); - IStateProvider StateProvider { get; } + /// + /// Get the persistent storage value at the specified storage cell + /// + /// Storage location + /// Value at cell + byte[] Get(in StorageCell storageCell); + + /// + /// Set the provided value to persistent storage at the specified storage cell + /// + /// Storage location + /// Value to store + void Set(in StorageCell storageCell, byte[] newValue); - Snapshot TakeSnapshot(bool newTransactionStart = false); + /// + /// Get the transient storage value at the specified storage cell + /// + /// Storage location + /// Value at cell + byte[] GetTransientState(in StorageCell storageCell); + + /// + /// Set the provided value to transient storage at the specified storage cell + /// + /// Storage location + /// Value to store + void SetTransientState(in StorageCell storageCell, byte[] newValue); - Snapshot IJournal.TakeSnapshot() => TakeSnapshot(); - } + /// + /// Reset all storage + /// + void Reset(); + + /// + /// Creates a restartable snapshot. + /// + /// Indicates new transaction will start here. + /// Snapshot index + /// + /// If is true and there are already changes in then next call to + /// will use changes before this snapshot as original values for this new transaction. + /// + Snapshot TakeSnapshot(bool newTransactionStart = false); + + Snapshot IJournal.TakeSnapshot() => TakeSnapshot(); + + /// + /// Clear all storage at specified address + /// + /// Contract address + void ClearStorage(Address address); + + void RecalculateStateRoot(); + + new Keccak StateRoot { get; set; } + + void DeleteAccount(Address address); + + void CreateAccount(Address address, in UInt256 balance); + + void CreateAccount(Address address, in UInt256 balance, in UInt256 nonce); + + void InsertCode(Address address, ReadOnlyMemory code, IReleaseSpec spec, bool isGenesis = false); + + void AddToBalance(Address address, in UInt256 balanceChange, IReleaseSpec spec); + + void SubtractFromBalance(Address address, in UInt256 balanceChange, IReleaseSpec spec); + + void UpdateStorageRoot(Address address, Keccak storageRoot); + + void IncrementNonce(Address address); + + void DecrementNonce(Address address); + + /* snapshots */ + + void Commit(IReleaseSpec releaseSpec, bool isGenesis = false); + + void Commit(IReleaseSpec releaseSpec, IWorldStateTracer? traver, bool isGenesis = false); + + void CommitTree(long blockNumber); + + /// + /// For witness + /// + /// + void TouchCode(Keccak codeHash); } diff --git a/src/Nethermind/Nethermind.State/IStateProviderExtensions.cs b/src/Nethermind/Nethermind.State/IWorldStateExtensions.cs similarity index 74% rename from src/Nethermind/Nethermind.State/IStateProviderExtensions.cs rename to src/Nethermind/Nethermind.State/IWorldStateExtensions.cs index 1cc633fb269..b9692d42c35 100644 --- a/src/Nethermind/Nethermind.State/IStateProviderExtensions.cs +++ b/src/Nethermind/Nethermind.State/IWorldStateExtensions.cs @@ -10,21 +10,21 @@ namespace Nethermind.State { - public static class StateProviderExtensions + public static class WorldStateExtensions { - public static byte[] GetCode(this IStateProvider stateProvider, Address address) + public static byte[] GetCode(this IWorldState stateProvider, Address address) { return stateProvider.GetCode(stateProvider.GetCodeHash(address)); } - public static string DumpState(this IStateProvider stateProvider) + public static string DumpState(this IWorldState stateProvider) { TreeDumper dumper = new(); stateProvider.Accept(dumper, stateProvider.StateRoot); return dumper.ToString(); } - public static TrieStats CollectStats(this IStateProvider stateProvider, IKeyValueStore codeStorage, ILogManager logManager) + public static TrieStats CollectStats(this IWorldState stateProvider, IKeyValueStore codeStorage, ILogManager logManager) { TrieStatsCollector collector = new(codeStorage, logManager); stateProvider.Accept(collector, stateProvider.StateRoot, new VisitingOptions diff --git a/src/Nethermind/Nethermind.State/NullStateTracer.cs b/src/Nethermind/Nethermind.State/NullStateTracer.cs deleted file mode 100644 index 6e95da80641..00000000000 --- a/src/Nethermind/Nethermind.State/NullStateTracer.cs +++ /dev/null @@ -1,31 +0,0 @@ -// SPDX-FileCopyrightText: 2022 Demerzel Solutions Limited -// SPDX-License-Identifier: LGPL-3.0-only - -using System; -using Nethermind.Core; -using Nethermind.Int256; - -namespace Nethermind.State -{ - public class NullStateTracer : IStateTracer - { - private NullStateTracer() { } - - public static IStateTracer Instance { get; } = new NullStateTracer(); - private const string ErrorMessage = "Null tracer should never receive any calls."; - - public bool IsTracingState => false; - - public void ReportBalanceChange(Address address, UInt256? before, UInt256? after) - => throw new InvalidOperationException(ErrorMessage); - - public void ReportCodeChange(Address address, byte[]? before, byte[]? after) - => throw new InvalidOperationException(ErrorMessage); - - public void ReportNonceChange(Address address, UInt256? before, UInt256? after) - => throw new InvalidOperationException(ErrorMessage); - - public void ReportAccountRead(Address address) - => throw new InvalidOperationException(ErrorMessage); - } -} diff --git a/src/Nethermind/Nethermind.State/NullStorageTracer.cs b/src/Nethermind/Nethermind.State/NullStorageTracer.cs deleted file mode 100644 index 9a04149c85d..00000000000 --- a/src/Nethermind/Nethermind.State/NullStorageTracer.cs +++ /dev/null @@ -1,27 +0,0 @@ -// SPDX-FileCopyrightText: 2022 Demerzel Solutions Limited -// SPDX-License-Identifier: LGPL-3.0-only - -using System; -using Nethermind.Core; - -namespace Nethermind.State -{ - public class NullStorageTracer : IStorageTracer - { - private NullStorageTracer() { } - - public static IStorageTracer Instance { get; } = new NullStorageTracer(); - - private const string ErrorMessage = "Null tracer should never receive any calls."; - - public bool IsTracingStorage => false; - public void ReportStorageChange(in ReadOnlySpan key, in ReadOnlySpan value) - => throw new InvalidOperationException(ErrorMessage); - - public void ReportStorageChange(in StorageCell storageCell, byte[] before, byte[] after) - => throw new InvalidOperationException(ErrorMessage); - - public void ReportStorageRead(in StorageCell storageCell) - => throw new InvalidOperationException(ErrorMessage); - } -} diff --git a/src/Nethermind/Nethermind.State/PartialStorageProviderBase.cs b/src/Nethermind/Nethermind.State/PartialStorageProviderBase.cs index e6427a33756..b47e0d36c96 100644 --- a/src/Nethermind/Nethermind.State/PartialStorageProviderBase.cs +++ b/src/Nethermind/Nethermind.State/PartialStorageProviderBase.cs @@ -7,13 +7,14 @@ using Nethermind.Core.Collections; using Nethermind.Core.Resettables; using Nethermind.Logging; +using Nethermind.State.Tracing; namespace Nethermind.State { /// /// Contains common code for both Persistent and Transient storage providers /// - public abstract class PartialStorageProviderBase + internal abstract class PartialStorageProviderBase { protected readonly ResettableDictionary> _intraBlockCache = new(); @@ -145,7 +146,7 @@ public void Restore(int snapshot) /// public void Commit() { - Commit(NullStorageTracer.Instance); + Commit(NullStateTracer.Instance); } protected readonly struct ChangeTrace diff --git a/src/Nethermind/Nethermind.State/PersistentStorageProvider.cs b/src/Nethermind/Nethermind.State/PersistentStorageProvider.cs index 9aa9323858e..0f496cf0a13 100644 --- a/src/Nethermind/Nethermind.State/PersistentStorageProvider.cs +++ b/src/Nethermind/Nethermind.State/PersistentStorageProvider.cs @@ -9,6 +9,7 @@ using Nethermind.Core.Extensions; using Nethermind.Core.Resettables; using Nethermind.Logging; +using Nethermind.State.Tracing; using Nethermind.Trie.Pruning; namespace Nethermind.State @@ -17,10 +18,10 @@ namespace Nethermind.State /// Manages persistent storage allowing for snapshotting and restoring /// Persists data to ITrieStore /// - public class PersistentStorageProvider : PartialStorageProviderBase + internal class PersistentStorageProvider : PartialStorageProviderBase { private readonly ITrieStore _trieStore; - private readonly IStateProvider _stateProvider; + private readonly StateProvider _stateProvider; private readonly ILogManager? _logManager; private readonly ResettableDictionary _storages = new(); /// @@ -29,7 +30,7 @@ public class PersistentStorageProvider : PartialStorageProviderBase private readonly ResettableDictionary _originalValues = new(); private readonly ResettableHashSet _committedThisRound = new(); - public PersistentStorageProvider(ITrieStore? trieStore, IStateProvider? stateProvider, ILogManager? logManager) + public PersistentStorageProvider(ITrieStore? trieStore, StateProvider? stateProvider, ILogManager? logManager) : base(logManager) { _trieStore = trieStore ?? throw new ArgumentNullException(nameof(trieStore)); diff --git a/src/Nethermind/Nethermind.State/StateProvider.cs b/src/Nethermind/Nethermind.State/StateProvider.cs index d807436cc0f..e79434ffd30 100644 --- a/src/Nethermind/Nethermind.State/StateProvider.cs +++ b/src/Nethermind/Nethermind.State/StateProvider.cs @@ -10,21 +10,15 @@ using Nethermind.Core.Specs; using Nethermind.Int256; using Nethermind.Logging; +using Nethermind.State.Tracing; using Nethermind.State.Witnesses; using Nethermind.Trie; using Nethermind.Trie.Pruning; using Metrics = Nethermind.Db.Metrics; -[assembly: InternalsVisibleTo("Ethereum.Test.Base")] -[assembly: InternalsVisibleTo("Ethereum.Blockchain.Test")] -[assembly: InternalsVisibleTo("Nethermind.State.Test")] -[assembly: InternalsVisibleTo("Nethermind.Benchmark")] -[assembly: InternalsVisibleTo("Nethermind.Blockchain.Test")] -[assembly: InternalsVisibleTo("Nethermind.Synchronization.Test")] - namespace Nethermind.State { - public class StateProvider : IStateProvider + internal class StateProvider { private const int StartCapacity = Resettable.StartCapacity; private readonly ResettableDictionary> _intraBlockCache = new(); @@ -132,9 +126,12 @@ public UInt256 GetBalance(Address address) return account?.Balance ?? UInt256.Zero; } - public void UpdateCodeHash(Address address, Keccak codeHash, IReleaseSpec releaseSpec, bool isGenesis = false) + public void InsertCode(Address address, ReadOnlyMemory code, IReleaseSpec spec, bool isGenesis = false) { _needsStateRootUpdate = true; + Keccak codeHash = code.Length == 0 ? Keccak.OfAnEmptyString : Keccak.Compute(code.Span); + _codeDb[codeHash.Bytes] = code.ToArray(); + Account? account = GetThroughCache(address); if (account is null) { @@ -147,12 +144,12 @@ public void UpdateCodeHash(Address address, Keccak codeHash, IReleaseSpec releas Account changedAccount = account.WithChangedCodeHash(codeHash); PushUpdate(address, changedAccount); } - else if (releaseSpec.IsEip158Enabled && !isGenesis) + else if (spec.IsEip158Enabled && !isGenesis) { if (_logger.IsTrace) _logger.Trace($" Touch {address} (code hash)"); if (account.IsEmpty) { - PushTouch(address, account, releaseSpec, account.Balance.IsZero); + PushTouch(address, account, spec, account.Balance.IsZero); } } } @@ -274,21 +271,6 @@ public void TouchCode(Keccak codeHash) } } - public Keccak UpdateCode(ReadOnlyMemory code) - { - _needsStateRootUpdate = true; - if (code.Length == 0) - { - return Keccak.OfAnEmptyString; - } - - Keccak codeHash = Keccak.Compute(code.Span); - - _codeDb[codeHash.Bytes] = code.ToArray(); - - return codeHash; - } - public Keccak GetCodeHash(Address address) { Account account = GetThroughCache(address); @@ -323,7 +305,7 @@ public void DeleteAccount(Address address) PushDelete(address); } - int IJournal.TakeSnapshot() + public int TakeSnapshot() { if (_logger.IsTrace) _logger.Trace($"State snapshot {_currentPosition}"); return _currentPosition; @@ -425,7 +407,7 @@ public ChangeTrace(Account? after) public Account? After { get; } } - public void Commit(IReleaseSpec releaseSpec, IStateTracer stateTracer, bool isGenesis = false) + public void Commit(IReleaseSpec releaseSpec, IWorldStateTracer stateTracer, bool isGenesis = false) { if (_currentPosition == -1) { diff --git a/src/Nethermind/Nethermind.State/StateReaderExtensions.cs b/src/Nethermind/Nethermind.State/StateReaderExtensions.cs index 7edcd31d6a4..d146bfbedea 100644 --- a/src/Nethermind/Nethermind.State/StateReaderExtensions.cs +++ b/src/Nethermind/Nethermind.State/StateReaderExtensions.cs @@ -42,7 +42,5 @@ public static bool HasStateForBlock(this IStateReader stateReader, BlockHeader h stateReader.RunTreeVisitor(rootCheckVisitor, header.StateRoot); return rootCheckVisitor.HasRoot; } - - } } diff --git a/src/Nethermind/Nethermind.State/StorageProvider.cs b/src/Nethermind/Nethermind.State/StorageProvider.cs deleted file mode 100644 index e8edd1a9372..00000000000 --- a/src/Nethermind/Nethermind.State/StorageProvider.cs +++ /dev/null @@ -1,98 +0,0 @@ -// SPDX-FileCopyrightText: 2022 Demerzel Solutions Limited -// SPDX-License-Identifier: LGPL-3.0-only - -using Nethermind.Core; -using Nethermind.Logging; -using Nethermind.Trie.Pruning; - -namespace Nethermind.State -{ - public class StorageProvider : IStorageProvider - { - PersistentStorageProvider _persistentStorageProvider; - TransientStorageProvider _transientStorageProvider; - - public StorageProvider(ITrieStore? trieStore, IStateProvider? stateProvider, ILogManager? logManager) - { - _persistentStorageProvider = new PersistentStorageProvider(trieStore, stateProvider, logManager); - _transientStorageProvider = new TransientStorageProvider(logManager); - } - - public void ClearStorage(Address address) - { - _persistentStorageProvider.ClearStorage(address); - _transientStorageProvider.ClearStorage(address); - } - - public void Commit() - { - _persistentStorageProvider.Commit(); - _transientStorageProvider.Commit(); - } - - public void Commit(IStorageTracer stateTracer) - { - _persistentStorageProvider.Commit(stateTracer); - _transientStorageProvider.Commit(stateTracer); - } - - public void CommitTrees(long blockNumber) - { - _persistentStorageProvider.CommitTrees(blockNumber); - } - - public byte[] Get(in StorageCell storageCell) - { - return _persistentStorageProvider.Get(storageCell); - } - - public byte[] GetOriginal(in StorageCell storageCell) - { - return _persistentStorageProvider.GetOriginal(storageCell); - } - - public byte[] GetTransientState(in StorageCell storageCell) - { - return _transientStorageProvider.Get(storageCell); - } - - public void Reset() - { - _persistentStorageProvider.Reset(); - _transientStorageProvider.Reset(); - } - - /// - /// Convenience for test cases - /// - /// - internal void Restore(int snapshot) - { - Restore(new Snapshot.Storage(snapshot, Snapshot.EmptyPosition)); - } - - public void Restore(Snapshot.Storage snapshot) - { - _persistentStorageProvider.Restore(snapshot.PersistentStorageSnapshot); - _transientStorageProvider.Restore(snapshot.TransientStorageSnapshot); - } - - public void Set(in StorageCell storageCell, byte[] newValue) - { - _persistentStorageProvider.Set(storageCell, newValue); - } - - public void SetTransientState(in StorageCell storageCell, byte[] newValue) - { - _transientStorageProvider.Set(storageCell, newValue); - } - - Snapshot.Storage IStorageProvider.TakeSnapshot(bool newTransactionStart) - { - int persistentSnapshot = _persistentStorageProvider.TakeSnapshot(newTransactionStart); - int transientSnapshot = _transientStorageProvider.TakeSnapshot(newTransactionStart); - - return new Snapshot.Storage(persistentSnapshot, transientSnapshot); - } - } -} diff --git a/src/Nethermind/Nethermind.State/IStateTracer.cs b/src/Nethermind/Nethermind.State/Tracing/IStateTracer.cs similarity index 98% rename from src/Nethermind/Nethermind.State/IStateTracer.cs rename to src/Nethermind/Nethermind.State/Tracing/IStateTracer.cs index 1d62d72ab72..db53accd4c9 100644 --- a/src/Nethermind/Nethermind.State/IStateTracer.cs +++ b/src/Nethermind/Nethermind.State/Tracing/IStateTracer.cs @@ -4,7 +4,7 @@ using Nethermind.Core; using Nethermind.Int256; -namespace Nethermind.State +namespace Nethermind.State.Tracing { public interface IStateTracer { diff --git a/src/Nethermind/Nethermind.State/IStorageTracer.cs b/src/Nethermind/Nethermind.State/Tracing/IStorageTracer.cs similarity index 97% rename from src/Nethermind/Nethermind.State/IStorageTracer.cs rename to src/Nethermind/Nethermind.State/Tracing/IStorageTracer.cs index d041cbccc1c..66d157dcdeb 100644 --- a/src/Nethermind/Nethermind.State/IStorageTracer.cs +++ b/src/Nethermind/Nethermind.State/Tracing/IStorageTracer.cs @@ -4,7 +4,7 @@ using System; using Nethermind.Core; -namespace Nethermind.State +namespace Nethermind.State.Tracing { public interface IStorageTracer { diff --git a/src/Nethermind/Nethermind.State/Tracing/IWorldStateTracer.cs b/src/Nethermind/Nethermind.State/Tracing/IWorldStateTracer.cs new file mode 100644 index 00000000000..f8f87c9429d --- /dev/null +++ b/src/Nethermind/Nethermind.State/Tracing/IWorldStateTracer.cs @@ -0,0 +1,9 @@ +// SPDX-FileCopyrightText: 2023 Demerzel Solutions Limited +// SPDX-License-Identifier: LGPL-3.0-only + +namespace Nethermind.State.Tracing; + +public interface IWorldStateTracer : IStateTracer, IStorageTracer +{ + +} diff --git a/src/Nethermind/Nethermind.State/Tracing/NullStateTracer.cs b/src/Nethermind/Nethermind.State/Tracing/NullStateTracer.cs new file mode 100644 index 00000000000..945d7a8a958 --- /dev/null +++ b/src/Nethermind/Nethermind.State/Tracing/NullStateTracer.cs @@ -0,0 +1,40 @@ +// SPDX-FileCopyrightText: 2023 Demerzel Solutions Limited +// SPDX-License-Identifier: LGPL-3.0-only + +using System; +using Nethermind.Core; +using Nethermind.Int256; + +namespace Nethermind.State.Tracing; + +public class NullStateTracer : IWorldStateTracer +{ + private NullStateTracer() { } + + public static IWorldStateTracer Instance { get; } = new NullStateTracer(); + private const string ErrorMessage = "Null tracer should never receive any calls."; + + public bool IsTracingState => false; + public bool IsTracingStorage => false; + + public void ReportBalanceChange(Address address, UInt256? before, UInt256? after) + => throw new InvalidOperationException(ErrorMessage); + + public void ReportCodeChange(Address address, byte[]? before, byte[]? after) + => throw new InvalidOperationException(ErrorMessage); + + public void ReportNonceChange(Address address, UInt256? before, UInt256? after) + => throw new InvalidOperationException(ErrorMessage); + + public void ReportAccountRead(Address address) + => throw new InvalidOperationException(ErrorMessage); + + public void ReportStorageChange(in ReadOnlySpan key, in ReadOnlySpan value) + => throw new InvalidOperationException(ErrorMessage); + + public void ReportStorageChange(in StorageCell storageCell, byte[] before, byte[] after) + => throw new InvalidOperationException(ErrorMessage); + + public void ReportStorageRead(in StorageCell storageCell) + => throw new InvalidOperationException(ErrorMessage); +} diff --git a/src/Nethermind/Nethermind.State/TransientStorageProvider.cs b/src/Nethermind/Nethermind.State/TransientStorageProvider.cs index 27702485f7e..9c1c9d8fde9 100644 --- a/src/Nethermind/Nethermind.State/TransientStorageProvider.cs +++ b/src/Nethermind/Nethermind.State/TransientStorageProvider.cs @@ -10,7 +10,7 @@ namespace Nethermind.State /// EIP-1153 provides a transient store for contracts that doesn't persist /// storage across calls. Reverts will rollback any transient state changes. /// - public class TransientStorageProvider : PartialStorageProviderBase + internal class TransientStorageProvider : PartialStorageProviderBase { public TransientStorageProvider(ILogManager? logManager) : base(logManager) { } diff --git a/src/Nethermind/Nethermind.State/WorldState.cs b/src/Nethermind/Nethermind.State/WorldState.cs index cad22bb3947..e73f3081a5d 100644 --- a/src/Nethermind/Nethermind.State/WorldState.cs +++ b/src/Nethermind/Nethermind.State/WorldState.cs @@ -2,31 +2,209 @@ // SPDX-License-Identifier: LGPL-3.0-only using System; +using System.Runtime.CompilerServices; +using Nethermind.Core; +using Nethermind.Core.Crypto; +using Nethermind.Core.Specs; +using Nethermind.Int256; +using Nethermind.Logging; +using Nethermind.State.Tracing; +using Nethermind.Trie; +using Nethermind.Trie.Pruning; + +[assembly: InternalsVisibleTo("Ethereum.Test.Base")] +[assembly: InternalsVisibleTo("Ethereum.Blockchain.Test")] +[assembly: InternalsVisibleTo("Nethermind.State.Test")] +[assembly: InternalsVisibleTo("Nethermind.Benchmark")] +[assembly: InternalsVisibleTo("Nethermind.Blockchain.Test")] +[assembly: InternalsVisibleTo("Nethermind.Synchronization.Test")] namespace Nethermind.State { public class WorldState : IWorldState { - public IStateProvider StateProvider { get; } + private readonly StateProvider _stateProvider; + private readonly PersistentStorageProvider _persistentStorageProvider; + private readonly TransientStorageProvider _transientStorageProvider; + + public Keccak StateRoot + { + get => _stateProvider.StateRoot; + set => _stateProvider.StateRoot = value; + } + + public WorldState(ITrieStore? trieStore, IKeyValueStore? codeDb, ILogManager? logManager) + { + _stateProvider = new StateProvider(trieStore, codeDb, logManager); + _persistentStorageProvider = new PersistentStorageProvider(trieStore, _stateProvider, logManager); + _transientStorageProvider = new TransientStorageProvider(logManager); + } + public Account GetAccount(Address address) + { + return _stateProvider.GetAccount(address); + } + public byte[] GetOriginal(in StorageCell storageCell) + { + return _persistentStorageProvider.GetOriginal(storageCell); + } + public byte[] Get(in StorageCell storageCell) + { + return _persistentStorageProvider.Get(storageCell); + } + public void Set(in StorageCell storageCell, byte[] newValue) + { + _persistentStorageProvider.Set(storageCell, newValue); + } + public byte[] GetTransientState(in StorageCell storageCell) + { + return _transientStorageProvider.Get(storageCell); + } + public void SetTransientState(in StorageCell storageCell, byte[] newValue) + { + _transientStorageProvider.Set(storageCell, newValue); + } + public void Reset() + { + _stateProvider.Reset(); + _persistentStorageProvider.Reset(); + _transientStorageProvider.Reset(); + } + + public void ClearStorage(Address address) + { + _persistentStorageProvider.ClearStorage(address); + _transientStorageProvider.ClearStorage(address); + } + public void RecalculateStateRoot() + { + _stateProvider.RecalculateStateRoot(); + } + public void DeleteAccount(Address address) + { + _stateProvider.DeleteAccount(address); + } + public void CreateAccount(Address address, in UInt256 balance) + { + _stateProvider.CreateAccount(address, balance); + } + public void CreateAccount(Address address, in UInt256 balance, in UInt256 nonce) + { + _stateProvider.CreateAccount(address, balance, nonce); + } + public void InsertCode(Address address, ReadOnlyMemory code, IReleaseSpec spec, bool isGenesis = false) + { + _stateProvider.InsertCode(address, code, spec, isGenesis); + } + public void AddToBalance(Address address, in UInt256 balanceChange, IReleaseSpec spec) + { + _stateProvider.AddToBalance(address, balanceChange, spec); + } + public void SubtractFromBalance(Address address, in UInt256 balanceChange, IReleaseSpec spec) + { + _stateProvider.SubtractFromBalance(address, balanceChange, spec); + } + public void UpdateStorageRoot(Address address, Keccak storageRoot) + { + _stateProvider.UpdateStorageRoot(address, storageRoot); + } + public void IncrementNonce(Address address) + { + _stateProvider.IncrementNonce(address); + } + public void DecrementNonce(Address address) + { + _stateProvider.DecrementNonce(address); + } + + public void CommitTree(long blockNumber) + { + _persistentStorageProvider.CommitTrees(blockNumber); + _stateProvider.CommitTree(blockNumber); + } + + public void TouchCode(Keccak codeHash) + { + _stateProvider.TouchCode(codeHash); + } + + public UInt256 GetNonce(Address address) + { + return _stateProvider.GetNonce(address); + } + public UInt256 GetBalance(Address address) + { + return _stateProvider.GetBalance(address); + } + public Keccak GetStorageRoot(Address address) + { + return _stateProvider.GetStorageRoot(address); + } + public byte[] GetCode(Address address) + { + return _stateProvider.GetCode(address); + } + public byte[] GetCode(Keccak codeHash) + { + return _stateProvider.GetCode(codeHash); + } + public Keccak GetCodeHash(Address address) + { + return _stateProvider.GetCodeHash(address); + } + public void Accept(ITreeVisitor visitor, Keccak stateRoot, VisitingOptions? visitingOptions = null) + { + _stateProvider.Accept(visitor, stateRoot, visitingOptions); + } + public bool AccountExists(Address address) + { + return _stateProvider.AccountExists(address); + } + public bool IsDeadAccount(Address address) + { + return _stateProvider.IsDeadAccount(address); + } + public bool IsEmptyAccount(Address address) + { + return _stateProvider.IsEmptyAccount(address); + } + + public void Commit(IReleaseSpec releaseSpec, bool isGenesis = false) + { + _persistentStorageProvider.Commit(); + _transientStorageProvider.Commit(); + _stateProvider.Commit(releaseSpec, isGenesis); + } + public void Commit(IReleaseSpec releaseSpec, IWorldStateTracer tracer, bool isGenesis = false) + { + _persistentStorageProvider.Commit(tracer); + _transientStorageProvider.Commit(tracer); + _stateProvider.Commit(releaseSpec, tracer, isGenesis); + } public Snapshot TakeSnapshot(bool newTransactionStart = false) { - Snapshot.Storage storageSnapshot = StorageProvider.TakeSnapshot(newTransactionStart); - return new(StateProvider.TakeSnapshot(), storageSnapshot); + int persistentSnapshot = _persistentStorageProvider.TakeSnapshot(newTransactionStart); + int transientSnapshot = _transientStorageProvider.TakeSnapshot(newTransactionStart); + Snapshot.Storage storageSnapshot = new Snapshot.Storage(persistentSnapshot, transientSnapshot); + int stateSnapshot = _stateProvider.TakeSnapshot(); + return new Snapshot(stateSnapshot, storageSnapshot); } public void Restore(Snapshot snapshot) { - StateProvider.Restore(snapshot.StateSnapshot); - StorageProvider.Restore(snapshot.StorageSnapshot); + _persistentStorageProvider.Restore(snapshot.StorageSnapshot.PersistentStorageSnapshot); + _transientStorageProvider.Restore(snapshot.StorageSnapshot.TransientStorageSnapshot); + _stateProvider.Restore(snapshot.StateSnapshot); } - public IStorageProvider StorageProvider { get; } + internal void Restore(int state, int persistantStorage, int transientStorage) + { + Restore(new Snapshot(state, new Snapshot.Storage(persistantStorage, transientStorage))); + } - public WorldState(IStateProvider stateProvider, IStorageProvider storageProvider) + internal void SetNonce(Address address, in UInt256 nonce) { - StateProvider = stateProvider ?? throw new ArgumentNullException(nameof(stateProvider)); - StorageProvider = storageProvider ?? throw new ArgumentNullException(nameof(storageProvider)); + _stateProvider.SetNonce(address, nonce); } } } diff --git a/src/Nethermind/Nethermind.Synchronization.Test/SyncThreadTests.cs b/src/Nethermind/Nethermind.Synchronization.Test/SyncThreadTests.cs index fa08dca0892..02949474290 100644 --- a/src/Nethermind/Nethermind.Synchronization.Test/SyncThreadTests.cs +++ b/src/Nethermind/Nethermind.Synchronization.Test/SyncThreadTests.cs @@ -225,7 +225,7 @@ private class SyncTestContext public IBlockchainProcessor? BlockchainProcessor { get; set; } public ISynchronizer? Synchronizer { get; set; } public IBlockTree Tree { get; set; } = null!; - public IStateProvider StateProvider { get; set; } = null!; + public IWorldState StateProvider { get; set; } = null!; public DevBlockProducer? BlockProducer { get; set; } public ConsoleAsyncLogger? Logger { get; set; } @@ -257,13 +257,12 @@ private SyncTestContext CreateSyncManager(int index) TrieStore trieStore = new(stateDb, LimboLogs.Instance); StateReader stateReader = new(trieStore, codeDb, logManager); - StateProvider stateProvider = new(trieStore, codeDb, logManager); + WorldState stateProvider = new(trieStore, codeDb, logManager); stateProvider.CreateAccount(TestItem.AddressA, 10000.Ether()); stateProvider.Commit(specProvider.GenesisSpec); stateProvider.CommitTree(0); stateProvider.RecalculateStateRoot(); - StorageProvider storageProvider = new(trieStore, stateProvider, logManager); InMemoryReceiptStorage receiptStorage = new(); EthereumEcdsa ecdsa = new(specProvider.ChainId, logManager); @@ -290,7 +289,7 @@ private SyncTestContext CreateSyncManager(int index) RewardCalculator rewardCalculator = new(specProvider); TransactionProcessor txProcessor = - new(specProvider, stateProvider, storageProvider, virtualMachine, logManager); + new(specProvider, stateProvider, virtualMachine, logManager); BlockProcessor blockProcessor = new( specProvider, @@ -298,7 +297,6 @@ private SyncTestContext CreateSyncManager(int index) rewardCalculator, new BlockProcessor.BlockValidationTransactionsExecutor(txProcessor, stateProvider), stateProvider, - storageProvider, receiptStorage, NullWitnessCollector.Instance, logManager); @@ -311,18 +309,16 @@ private SyncTestContext CreateSyncManager(int index) NodeStatsManager nodeStatsManager = new(timerFactory, logManager); SyncPeerPool syncPeerPool = new(tree, nodeStatsManager, new TotalDifficultyBetterPeerStrategy(LimboLogs.Instance), logManager, 25); - StateProvider devState = new(trieStore, codeDb, logManager); - StorageProvider devStorage = new(trieStore, devState, logManager); + WorldState devState = new(trieStore, codeDb, logManager); VirtualMachine devEvm = new(blockhashProvider, specProvider, logManager); - TransactionProcessor devTxProcessor = new(specProvider, devState, devStorage, devEvm, logManager); + TransactionProcessor devTxProcessor = new(specProvider, devState, devEvm, logManager); BlockProcessor devBlockProcessor = new( specProvider, blockValidator, rewardCalculator, - new BlockProcessor.BlockProductionTransactionsExecutor(devTxProcessor, devState, devStorage, specProvider, logManager), + new BlockProcessor.BlockProductionTransactionsExecutor(devTxProcessor, devState, specProvider, logManager), devState, - devStorage, receiptStorage, NullWitnessCollector.Instance, logManager); diff --git a/src/Nethermind/Nethermind.Trie.Test/PruningScenariosTests.cs b/src/Nethermind/Nethermind.Trie.Test/PruningScenariosTests.cs index dd271862843..7f9f63a6e56 100644 --- a/src/Nethermind/Nethermind.Trie.Test/PruningScenariosTests.cs +++ b/src/Nethermind/Nethermind.Trie.Test/PruningScenariosTests.cs @@ -37,9 +37,8 @@ public class PruningContext private long _blockNumber = 1; private Dictionary _branchingPoints = new(); private IDbProvider _dbProvider; - private IStateProvider _stateProvider; + private IWorldState _stateProvider; private IStateReader _stateReader; - private IStorageProvider _storageProvider; private ILogManager _logManager; private ILogger _logger; private TrieStore _trieStore; @@ -56,8 +55,7 @@ private PruningContext(TestPruningStrategy pruningStrategy, IPersistenceStrategy _persistenceStrategy = persistenceStrategy; _pruningStrategy = pruningStrategy; _trieStore = new TrieStore(_dbProvider.StateDb, _pruningStrategy, _persistenceStrategy, _logManager); - _stateProvider = new StateProvider(_trieStore, _dbProvider.CodeDb, _logManager); - _storageProvider = new StorageProvider(_trieStore, _stateProvider, _logManager); + _stateProvider = new WorldState(_trieStore, _dbProvider.CodeDb, _logManager); _stateReader = new StateReader(_trieStore, _dbProvider.CodeDb, _logManager); } @@ -133,7 +131,7 @@ public PruningContext SetPruningMemoryLimit(int? memoryLimit) public PruningContext SetStorage(int accountIndex, int storageKey, int storageValue = 1) { - _storageProvider.Set( + _stateProvider.Set( new StorageCell(Address.FromNumber((UInt256)accountIndex), (UInt256)storageKey), ((UInt256)storageValue).ToBigEndian()); return this; @@ -151,7 +149,7 @@ public PruningContext ReadStorage(int accountIndex, int storageKey) _logger.Info($"READ STORAGE {accountIndex}.{storageKey}"); StorageCell storageCell = new(Address.FromNumber((UInt256)accountIndex), (UInt256)storageKey); - _storageProvider.Get(storageCell); + _stateProvider.Get(storageCell); return this; } @@ -178,8 +176,6 @@ public PruningContext CommitWithRandomChange() public PruningContext Commit() { - _storageProvider.Commit(); - _storageProvider.CommitTrees(_blockNumber); _stateProvider.Commit(MuirGlacier.Instance); _stateProvider.CommitTree(_blockNumber); _blockNumber++; @@ -196,8 +192,7 @@ public PruningContext DisposeAndRecreate() { _trieStore.Dispose(); _trieStore = new TrieStore(_dbProvider.StateDb, _pruningStrategy, _persistenceStrategy, _logManager); - _stateProvider = new StateProvider(_trieStore, _dbProvider.CodeDb, _logManager); - _storageProvider = new StorageProvider(_trieStore, _stateProvider, _logManager); + _stateProvider = new WorldState(_trieStore, _dbProvider.CodeDb, _logManager); _stateReader = new StateReader(_trieStore, _dbProvider.CodeDb, _logManager); return this; } @@ -223,7 +218,7 @@ public PruningContext VerifyAccountBalance(int account, int balance) public PruningContext VerifyStorageValue(int account, UInt256 index, int value) { - _storageProvider.Get(new StorageCell(Address.FromNumber((UInt256)account), index)) + _stateProvider.Get(new StorageCell(Address.FromNumber((UInt256)account), index)) .Should().BeEquivalentTo(((UInt256)value).ToBigEndian()); return this; } @@ -255,7 +250,6 @@ public PruningContext RestoreBranchingPoint(string name) (long blockNumber, Keccak rootHash) branchPoint = _branchingPoints[name]; _blockNumber = branchPoint.blockNumber; Keccak rootHash = branchPoint.rootHash; - _storageProvider.Reset(); _stateProvider.Reset(); _stateProvider.StateRoot = rootHash; return this; diff --git a/src/Nethermind/Nethermind.Trie.Test/TrieTests.cs b/src/Nethermind/Nethermind.Trie.Test/TrieTests.cs index 403d86af778..03c3639bfb6 100644 --- a/src/Nethermind/Nethermind.Trie.Test/TrieTests.cs +++ b/src/Nethermind/Nethermind.Trie.Test/TrieTests.cs @@ -978,8 +978,7 @@ public void Fuzz_accounts_with_storage( MemDb memDb = new(); using TrieStore trieStore = new(memDb, Prune.WhenCacheReaches(1.MB()), Persist.IfBlockOlderThan(lookupLimit), _logManager); - StateProvider stateProvider = new(trieStore, new MemDb(), _logManager); - StorageProvider storageProvider = new(trieStore, stateProvider, _logManager); + WorldState stateProvider = new(trieStore, new MemDb(), _logManager); Account[] accounts = new Account[accountsCount]; Address[] addresses = new Address[accountsCount]; @@ -1033,7 +1032,7 @@ public void Fuzz_accounts_with_storage( byte[] storage = new byte[1]; _random.NextBytes(storage); - storageProvider.Set(new StorageCell(address, 1), storage); + stateProvider.Set(new StorageCell(address, 1), storage); } else if (!account.IsTotallyEmpty) { @@ -1041,7 +1040,7 @@ public void Fuzz_accounts_with_storage( byte[] storage = new byte[1]; _random.NextBytes(storage); - storageProvider.Set(new StorageCell(address, 1), storage); + stateProvider.Set(new StorageCell(address, 1), storage); } } } @@ -1049,10 +1048,8 @@ public void Fuzz_accounts_with_storage( streamWriter.WriteLine( $"Commit block {blockNumber} | empty: {isEmptyBlock}"); - storageProvider.Commit(); stateProvider.Commit(MuirGlacier.Instance); - storageProvider.CommitTrees(blockNumber); stateProvider.CommitTree(blockNumber); rootQueue.Enqueue(stateProvider.StateRoot); } @@ -1076,7 +1073,7 @@ public void Fuzz_accounts_with_storage( { for (int j = 0; j < 256; j++) { - storageProvider.Get(new StorageCell(addresses[i], (UInt256)j)); + stateProvider.Get(new StorageCell(addresses[i], (UInt256)j)); } } } diff --git a/src/Nethermind/Nethermind.TxPool.Test/NonceManagerTests.cs b/src/Nethermind/Nethermind.TxPool.Test/NonceManagerTests.cs index 9d38cb756b3..4d52ea18552 100644 --- a/src/Nethermind/Nethermind.TxPool.Test/NonceManagerTests.cs +++ b/src/Nethermind/Nethermind.TxPool.Test/NonceManagerTests.cs @@ -24,7 +24,7 @@ namespace Nethermind.TxPool.Test; public class NonceManagerTests { private ISpecProvider _specProvider; - private IStateProvider _stateProvider; + private IWorldState _stateProvider; private IBlockTree _blockTree; private ChainHeadInfoProvider _headInfo; private INonceManager _nonceManager; @@ -36,7 +36,7 @@ public void Setup() _specProvider = RopstenSpecProvider.Instance; var trieStore = new TrieStore(new MemDb(), logManager); var codeDb = new MemDb(); - _stateProvider = new StateProvider(trieStore, codeDb, logManager); + _stateProvider = new WorldState(trieStore, codeDb, logManager); _blockTree = Substitute.For(); Block block = Build.A.Block.WithNumber(0).TestObject; _blockTree.Head.Returns(block); diff --git a/src/Nethermind/Nethermind.TxPool.Test/TxPoolTests.cs b/src/Nethermind/Nethermind.TxPool.Test/TxPoolTests.cs index 5fe4eb05c89..10e1d9af72e 100644 --- a/src/Nethermind/Nethermind.TxPool.Test/TxPoolTests.cs +++ b/src/Nethermind/Nethermind.TxPool.Test/TxPoolTests.cs @@ -42,7 +42,7 @@ public class TxPoolTests private IEthereumEcdsa _ethereumEcdsa; private ISpecProvider _specProvider; private TxPool _txPool; - private IStateProvider _stateProvider; + private IWorldState _stateProvider; private IBlockTree _blockTree; private int _txGasLimit = 1_000_000; @@ -55,7 +55,7 @@ public void Setup() _ethereumEcdsa = new EthereumEcdsa(_specProvider.ChainId, _logManager); var trieStore = new TrieStore(new MemDb(), _logManager); var codeDb = new MemDb(); - _stateProvider = new StateProvider(trieStore, codeDb, _logManager); + _stateProvider = new WorldState(trieStore, codeDb, _logManager); _blockTree = Substitute.For(); Block block = Build.A.Block.WithNumber(0).TestObject; _blockTree.Head.Returns(block); @@ -169,7 +169,7 @@ public void should_reject_transactions_from_contract_address() .WithGasLimit(_txGasLimit) .SignedAndResolved(_ethereumEcdsa, TestItem.PrivateKeyA).TestObject; EnsureSenderBalance(tx); - _stateProvider.UpdateCodeHash(TestItem.AddressA, TestItem.KeccakA, _specProvider.GetSpec((ForkActivation)1)); + _stateProvider.InsertCode(TestItem.AddressA, "A"u8.ToArray(), _specProvider.GetSpec((ForkActivation)1)); AcceptTxResult result = _txPool.SubmitTx(tx, TxHandlingOptions.PersistentBroadcast); result.Should().Be(AcceptTxResult.SenderIsContract); } @@ -237,7 +237,7 @@ public string should_reject_transactions_with_deployed_code_when_eip3607_enabled Transaction tx = Build.A.Transaction.SignedAndResolved(_ethereumEcdsa, TestItem.PrivateKeyA).TestObject; EnsureSenderBalance(tx); - _stateProvider.UpdateCodeHash(TestItem.AddressA, hasCode ? TestItem.KeccakH : Keccak.OfAnEmptyString, London.Instance); + _stateProvider.InsertCode(TestItem.AddressA, hasCode ? "H"u8.ToArray() : System.Text.Encoding.UTF8.GetBytes(""), London.Instance); return txPool.SubmitTx(tx, TxHandlingOptions.PersistentBroadcast).ToString(); }