From d81ce27f528da7553bf7c98e464988e267f3b9c9 Mon Sep 17 00:00:00 2001 From: Tanishq Jasoria Date: Thu, 15 Aug 2024 19:30:09 +0200 Subject: [PATCH] pass in world state where there in no context which worldState to use --- .../Nethermind.Analytics/AnalyticsPlugin.cs | 2 +- .../AnalyticsRpcModule.cs | 6 +- .../Nethermind.Analytics/RewardsVerifier.cs | 7 +- .../Contract/TestContractBlockchain.cs | 2 +- .../Contract/ValidatorContractTests.cs | 3 +- .../Reward/AuRaRewardCalculatorTests.cs | 16 ++- .../Reward/StaticRewardCalculatorTests.cs | 12 +- .../Validators/ContractBasedValidatorTests.cs | 14 +- .../Validators/MultiValidatorTests.cs | 9 +- .../GenesisLoaderTests.cs | 2 +- .../Producers/DevBlockproducerTests.cs | 1 - .../Nethermind.Blockchain.Test/ReorgTests.cs | 1 - .../Rewards/NoBlockRewardsTests.cs | 4 +- .../Rewards/RewardCalculatorTests.cs | 12 +- .../TransactionsExecutorTests.cs | 2 +- .../Contracts/CallableContract.cs | 31 +++-- .../Contracts/Contract.ConstantContract.cs | 5 +- .../Contracts/Contract.cs | 9 +- .../Nethermind.Blockchain/GenesisLoader.cs | 22 ++-- .../CliqueBlockProducerTests.cs | 4 +- .../AuRaBlockProcessor.cs | 15 ++- .../Contracts/RewardContract.cs | 31 +++-- .../Contracts/ValidatorContract.cs | 4 +- .../Rewards/AuRaRewardCalculator.cs | 12 +- .../Rewards/StaticRewardCalculator.cs | 3 +- .../Validators/AuRaValidatorBase.cs | 4 +- .../Validators/ContractBasedValidator.cs | 12 +- .../Validators/IAuRaValidator.cs | 4 +- .../Validators/MultiValidator.cs | 6 +- .../ReportingContractBasedValidator.cs | 5 +- .../Withdrawals/NullWithdrawalProcessor.cs | 3 +- .../Processing/BlockCachePreWarmer.cs | 2 +- .../Processing/BlockProcessor.cs | 18 +-- .../Processing/ReadOnlyTxProcessingEnv.cs | 2 +- .../TransactionProcessorAdapterExtensions.cs | 2 +- .../Rewards/IRewardCalculator.cs | 3 +- .../Rewards/NoBlockRewards.cs | 3 +- .../Rewards/RewardCalculator.cs | 3 +- .../Rewards/ZeroWeiRewards.cs | 3 +- .../BlockProductionWithdrawalProcessor.cs | 5 +- .../Withdrawals/IWithdrawalProcessor.cs | 3 +- .../Withdrawals/WithdrawalProcessor.cs | 2 +- .../Blockchain/TestBlockchain.cs | 2 +- .../Nethermind.Evm.Test/Eip2935Tests.cs | 2 +- .../Eip3198BaseFeeTests.cs | 4 +- .../Eip3529RefundsTests.cs | 12 +- .../Nethermind.Evm.Test/Eip3541Tests.cs | 4 +- .../Nethermind.Evm.Test/Eip3860Tests.cs | 2 +- .../Nethermind.Evm.Test/Eip6780Tests.cs | 14 +- .../Eip7516BlobBaseFeeTests.cs | 4 +- .../EvmPooledMemoryTests.cs | 2 +- .../GasPriceExtractorTests.cs | 6 +- .../StorageAndSelfDestructTests.cs | 40 +++--- .../Tracing/AccessTxTracerTests.cs | 2 +- .../Tracing/GasEstimationTests.cs | 40 +++--- .../Tracing/GethLike4byteTracerTests.cs | 2 +- .../Tracing/ParityLikeTxTracerTests.cs | 8 +- .../Tracing/ProofTxTracerTests.cs | 2 +- .../TransactionProcessorEip4844Tests.cs | 6 +- .../TransactionProcessorFeeTests.cs | 8 +- .../TransactionProcessorTests.cs | 84 ++++++------ .../TransactionProcessorTraceTest.cs | 2 +- .../VirtualMachineTestsBase.cs | 18 +-- .../Nethermind.Evm/Tracing/GasEstimator.cs | 23 ++-- .../BuildUpTransactionProcessorAdapter.cs | 5 +- ...llAndRestoreTransactionProcessorAdapter.cs | 5 +- .../ChangeableTransactionProcessorAdapter.cs | 5 +- .../ExecuteTransactionProcessorAdapter.cs | 5 +- .../ITransactionProcessor.cs | 9 +- .../ITransactionProcessorAdapter.cs | 3 +- .../TraceTransactionProcessorAdapter.cs | 5 +- .../TransactionProcessor.cs | 122 +++++++++--------- .../BlockchainBridgeTests.cs | 4 + .../Nethermind.Facade/BlockchainBridge.cs | 6 +- .../SimulateReadOnlyBlocksProcessingEnv.cs | 2 +- .../Simulate/SimulateTransactionProcessor.cs | 7 +- .../Steps/InitializeBlockchain.cs | 1 - .../Nethermind.Init/Steps/LoadGenesisBlock.cs | 2 +- .../Modules/Trace/ParityStyleTracerTests.cs | 2 +- .../Modules/Eth/SimulateTxExecutor.cs | 1 + .../Modules/Trace/MergeRpcRewardCalculator.cs | 5 +- .../AuraWithdrawalProcessorTests.cs | 15 +-- .../AuRaMergeBlockProcessor.cs | 7 +- .../Contracts/IWithdrawalContract.cs | 4 +- .../Contracts/WithdrawalContract.cs | 6 +- .../Withdrawals/AuraWithdrawalProcessor.cs | 5 +- .../EngineModuleTests.HelperFunctions.cs | 4 +- .../MergeRewardCalculatorTests.cs | 25 ++-- .../MergeRewardCalculator.cs | 7 +- .../InitializeBlockchainOptimism.cs | 1 - .../OptimismBlockProcessor.cs | 5 +- .../OptimismReadOnlyTxProcessingEnv.cs | 2 +- .../OptimismTransactionProcessor.cs | 49 ++++--- .../SyncThreadTests.cs | 4 +- 94 files changed, 489 insertions(+), 430 deletions(-) diff --git a/src/Nethermind/Nethermind.Analytics/AnalyticsPlugin.cs b/src/Nethermind/Nethermind.Analytics/AnalyticsPlugin.cs index 503ce7ffc4c..a60c16db8b1 100644 --- a/src/Nethermind/Nethermind.Analytics/AnalyticsPlugin.cs +++ b/src/Nethermind/Nethermind.Analytics/AnalyticsPlugin.cs @@ -91,7 +91,7 @@ public Task InitRpcModules() { var (getFromAPi, _) = _api.ForRpc; AnalyticsRpcModule analyticsRpcModule = new( - getFromAPi.BlockTree, getFromAPi.StateReader, getFromAPi.LogManager); + getFromAPi.BlockTree, getFromAPi.WorldState, getFromAPi.StateReader, getFromAPi.LogManager); getFromAPi.RpcModuleProvider.Register(new SingletonModulePool(analyticsRpcModule)); return Task.CompletedTask; } diff --git a/src/Nethermind/Nethermind.Analytics/AnalyticsRpcModule.cs b/src/Nethermind/Nethermind.Analytics/AnalyticsRpcModule.cs index 7a4755d3124..746c62ecdbe 100644 --- a/src/Nethermind/Nethermind.Analytics/AnalyticsRpcModule.cs +++ b/src/Nethermind/Nethermind.Analytics/AnalyticsRpcModule.cs @@ -15,13 +15,15 @@ public class AnalyticsRpcModule : IAnalyticsRpcModule { private readonly IBlockTree _blockTree; private readonly IStateReader _stateReader; + private readonly IWorldState _worldState; private readonly ILogManager _logManager; - public AnalyticsRpcModule(IBlockTree blockTree, IStateReader stateReader, ILogManager logManager) + public AnalyticsRpcModule(IBlockTree blockTree, IWorldState worldState, IStateReader stateReader, ILogManager logManager) { _blockTree = blockTree ?? throw new ArgumentNullException(nameof(blockTree)); _stateReader = stateReader ?? throw new ArgumentNullException(nameof(stateReader)); _logManager = logManager ?? throw new ArgumentNullException(nameof(logManager)); + _worldState = worldState; } public ResultWrapper analytics_verifySupply() @@ -33,7 +35,7 @@ public ResultWrapper analytics_verifySupply() public ResultWrapper analytics_verifyRewards() { - RewardsVerifier rewardsVerifier = new RewardsVerifier(_logManager, (_blockTree.Head?.Number ?? 0) + 1); + RewardsVerifier rewardsVerifier = new RewardsVerifier(_worldState, _logManager, (_blockTree.Head?.Number ?? 0) + 1); _blockTree.Accept(rewardsVerifier, CancellationToken.None); return ResultWrapper.Success(rewardsVerifier.BlockRewards); } diff --git a/src/Nethermind/Nethermind.Analytics/RewardsVerifier.cs b/src/Nethermind/Nethermind.Analytics/RewardsVerifier.cs index ac876d041d0..b22174a4ddc 100644 --- a/src/Nethermind/Nethermind.Analytics/RewardsVerifier.cs +++ b/src/Nethermind/Nethermind.Analytics/RewardsVerifier.cs @@ -10,6 +10,7 @@ using Nethermind.Int256; using Nethermind.Logging; using Nethermind.Specs; +using Nethermind.State; namespace Nethermind.Analytics { @@ -19,24 +20,26 @@ public class RewardsVerifier : IBlockTreeVisitor public bool PreventsAcceptingNewBlocks => true; public long StartLevelInclusive => 0; public long EndLevelExclusive { get; } + public IWorldState WorldState { get; } private readonly UInt256 _genesisAllocations = UInt256.Parse("72009990499480000000000000"); private UInt256 _uncles; public UInt256 BlockRewards { get; private set; } - public RewardsVerifier(ILogManager logManager, long endLevelExclusive) + public RewardsVerifier(IWorldState worldState, ILogManager logManager, long endLevelExclusive) { _logger = logManager.GetClassLogger(); EndLevelExclusive = endLevelExclusive; BlockRewards = _genesisAllocations; + WorldState = worldState; } private readonly RewardCalculator _rewardCalculator = new(MainnetSpecProvider.Instance); public Task VisitBlock(Block block, CancellationToken cancellationToken) { - BlockReward[] rewards = _rewardCalculator.CalculateRewards(block); + BlockReward[] rewards = _rewardCalculator.CalculateRewards(block, WorldState); for (int i = 0; i < rewards.Length; i++) { if (rewards[i].RewardType == BlockRewardType.Uncle) diff --git a/src/Nethermind/Nethermind.AuRa.Test/Contract/TestContractBlockchain.cs b/src/Nethermind/Nethermind.AuRa.Test/Contract/TestContractBlockchain.cs index bde491cbd4f..b9f8f98e5c6 100644 --- a/src/Nethermind/Nethermind.AuRa.Test/Contract/TestContractBlockchain.cs +++ b/src/Nethermind/Nethermind.AuRa.Test/Contract/TestContractBlockchain.cs @@ -44,6 +44,6 @@ protected override Block GetGenesisBlock() => SpecProvider, State, TxProcessor) - .Load(); + .Load(State); } } diff --git a/src/Nethermind/Nethermind.AuRa.Test/Contract/ValidatorContractTests.cs b/src/Nethermind/Nethermind.AuRa.Test/Contract/ValidatorContractTests.cs index ae1a5040a4f..b6f0544a823 100644 --- a/src/Nethermind/Nethermind.AuRa.Test/Contract/ValidatorContractTests.cs +++ b/src/Nethermind/Nethermind.AuRa.Test/Contract/ValidatorContractTests.cs @@ -80,9 +80,10 @@ public void finalize_change_should_call_correct_transaction() _readOnlyTxProcessorSource, new Signer(0, TestItem.PrivateKeyD, LimboLogs.Instance)); - contract.FinalizeChange(_block.Header); + contract.FinalizeChange(_block.Header, _stateProvider); _transactionProcessor.Received().Execute( + Arg.Any(), Arg.Is(t => IsEquivalentTo(expectation, t)), Arg.Is(blkCtx => blkCtx.Header.Equals(_block.Header)), Arg.Any()); } diff --git a/src/Nethermind/Nethermind.AuRa.Test/Reward/AuRaRewardCalculatorTests.cs b/src/Nethermind/Nethermind.AuRa.Test/Reward/AuRaRewardCalculatorTests.cs index 417955c1ffe..d8b943a2ce2 100644 --- a/src/Nethermind/Nethermind.AuRa.Test/Reward/AuRaRewardCalculatorTests.cs +++ b/src/Nethermind/Nethermind.AuRa.Test/Reward/AuRaRewardCalculatorTests.cs @@ -20,6 +20,7 @@ using NSubstitute; using NUnit.Framework; using Nethermind.Evm; +using Nethermind.State; namespace Nethermind.AuRa.Test.Reward { @@ -28,6 +29,7 @@ public class AuRaRewardCalculatorTests private AuRaParameters _auraParameters; private IAbiEncoder _abiEncoder; private ITransactionProcessor _transactionProcessor; + private IWorldState _worldState; private Block _block; private readonly byte[] _rewardData = { 3, 4, 5 }; private Address _address10; @@ -49,6 +51,7 @@ public void SetUp() _abiEncoder = Substitute.For(); _transactionProcessor = Substitute.For(); + _worldState = Substitute.For(); _block = new Block(Build.A.BlockHeader.TestObject, new BlockBody()); @@ -97,7 +100,7 @@ public void calculates_rewards_correctly_before_contract_transition(long blockNu { _block.Header.Number = blockNumber; AuRaRewardCalculator calculator = new(_auraParameters, _abiEncoder, _transactionProcessor); - BlockReward[] result = calculator.CalculateRewards(_block); + BlockReward[] result = calculator.CalculateRewards(_block, _worldState); result.Should().BeEquivalentTo(new BlockReward(_block.Beneficiary, expectedReward)); } @@ -106,7 +109,7 @@ public void calculates_rewards_correctly_for_genesis() { _block.Header.Number = 0; AuRaRewardCalculator calculator = new(_auraParameters, _abiEncoder, _transactionProcessor); - BlockReward[] result = calculator.CalculateRewards(_block); + BlockReward[] result = calculator.CalculateRewards(_block, _worldState); result.Should().BeEmpty(); } @@ -118,7 +121,7 @@ public void calculates_rewards_correctly_after_contract_transition(long blockNum BlockReward expected = new(_block.Beneficiary, expectedReward, BlockRewardType.External); SetupBlockRewards(new Dictionary() { { _address10, new[] { expected } } }); AuRaRewardCalculator calculator = new(_auraParameters, _abiEncoder, _transactionProcessor); - BlockReward[] result = calculator.CalculateRewards(_block); + BlockReward[] result = calculator.CalculateRewards(_block, _worldState); result.Should().BeEquivalentTo(expected); } @@ -144,7 +147,7 @@ public void calculates_rewards_correctly_after_subsequent_contract_transitions(l BlockReward expected = new(_block.Beneficiary, expectedReward, BlockRewardType.External); SetupBlockRewards(new Dictionary() { { address, new[] { expected } } }); AuRaRewardCalculator calculator = new(_auraParameters, _abiEncoder, _transactionProcessor); - BlockReward[] result = calculator.CalculateRewards(_block); + BlockReward[] result = calculator.CalculateRewards(_block, _worldState); result.Should().BeEquivalentTo(expected); } @@ -167,7 +170,7 @@ public void calculates_rewards_correctly_for_uncles(long blockNumber, ulong expe SetupBlockRewards(new Dictionary() { { _address10, expected } }); AuRaRewardCalculator calculator = new(_auraParameters, _abiEncoder, _transactionProcessor); - BlockReward[] result = calculator.CalculateRewards(_block); + BlockReward[] result = calculator.CalculateRewards(_block, _worldState); result.Should().BeEquivalentTo(expected); } @@ -190,13 +193,14 @@ public void calculates_rewards_correctly_for_external_addresses() SetupBlockRewards(new Dictionary() { { _address10, expected } }); AuRaRewardCalculator calculator = new(_auraParameters, _abiEncoder, _transactionProcessor); - BlockReward[] result = calculator.CalculateRewards(_block); + BlockReward[] result = calculator.CalculateRewards(_block, _worldState); result.Should().BeEquivalentTo(expected); } private void SetupBlockRewards(IDictionary rewards) { _transactionProcessor.When(x => x.Execute( + Arg.Any(), Arg.Is(t => CheckTransaction(t, rewards.Keys, _rewardData)), Arg.Is(blkCtx => blkCtx.Header.Equals(_block.Header)), Arg.Is(t => t is CallOutputTracer))) diff --git a/src/Nethermind/Nethermind.AuRa.Test/Reward/StaticRewardCalculatorTests.cs b/src/Nethermind/Nethermind.AuRa.Test/Reward/StaticRewardCalculatorTests.cs index 291feb3dd17..4c646771e86 100644 --- a/src/Nethermind/Nethermind.AuRa.Test/Reward/StaticRewardCalculatorTests.cs +++ b/src/Nethermind/Nethermind.AuRa.Test/Reward/StaticRewardCalculatorTests.cs @@ -9,6 +9,8 @@ using Nethermind.Core.Test; using Nethermind.Core.Test.Builders; using Nethermind.Int256; +using Nethermind.State; +using NSubstitute; using NUnit.Framework; namespace Nethermind.AuRa.Test.Reward @@ -27,7 +29,7 @@ public void calculates_rewards_correctly_for_thresholds(long blockNumber, ulong Dictionary blockReward = new() { { 0, 200 }, { 5, 150 }, { 10, 100 }, { 11, 50 } }; _block.Header.Number = blockNumber; StaticRewardCalculator calculator = new(blockReward); - BlockReward[] result = calculator.CalculateRewards(_block); + BlockReward[] result = calculator.CalculateRewards(_block, Substitute.For()); result.Should().BeEquivalentTo(new BlockReward(_block.Beneficiary, expectedReward)); } @@ -38,7 +40,7 @@ public void calculates_rewards_correctly_for_single_value(long blockNumber, ulon Dictionary blockReward = new() { { 0, 200 } }; _block.Header.Number = blockNumber; StaticRewardCalculator calculator = new(blockReward); - BlockReward[] result = calculator.CalculateRewards(_block); + BlockReward[] result = calculator.CalculateRewards(_block, Substitute.For()); result.Should().BeEquivalentTo(new BlockReward(_block.Beneficiary, expectedReward)); } @@ -48,7 +50,7 @@ public void calculates_rewards_correctly_for_null_argument(long blockNumber, ulo { _block.Header.Number = blockNumber; StaticRewardCalculator calculator = new(null); - BlockReward[] result = calculator.CalculateRewards(_block); + BlockReward[] result = calculator.CalculateRewards(_block, Substitute.For()); result.Should().BeEquivalentTo(new BlockReward(_block.Beneficiary, expectedReward)); } @@ -59,7 +61,7 @@ public void calculates_rewards_correctly_for_not_supported_value(long blockNumbe Dictionary blockReward = new() { { 10, 200 } }; _block.Header.Number = blockNumber; StaticRewardCalculator calculator = new(blockReward); - BlockReward[] result = calculator.CalculateRewards(_block); + BlockReward[] result = calculator.CalculateRewards(_block, Substitute.For()); result.Should().BeEquivalentTo(new BlockReward(_block.Beneficiary, expectedReward)); } @@ -69,7 +71,7 @@ public void calculates_rewards_correctly_for_empty_dictionary(long blockNumber, Dictionary blockReward = new() { }; _block.Header.Number = blockNumber; StaticRewardCalculator calculator = new(blockReward); - BlockReward[] result = calculator.CalculateRewards(_block); + BlockReward[] result = calculator.CalculateRewards(_block, Substitute.For()); result.Should().BeEquivalentTo(new BlockReward(_block.Beneficiary, expectedReward)); } } diff --git a/src/Nethermind/Nethermind.AuRa.Test/Validators/ContractBasedValidatorTests.cs b/src/Nethermind/Nethermind.AuRa.Test/Validators/ContractBasedValidatorTests.cs index 3902182d6e8..d4ef41867e4 100644 --- a/src/Nethermind/Nethermind.AuRa.Test/Validators/ContractBasedValidatorTests.cs +++ b/src/Nethermind/Nethermind.AuRa.Test/Validators/ContractBasedValidatorTests.cs @@ -136,7 +136,7 @@ public void creates_system_account_on_start_block() _block.Header.Beneficiary = initialValidator; ContractBasedValidator validator = new(_validatorContract, _blockTree, _receiptsStorage, _validatorStore, _validSealerStrategy, _blockFinalizationManager, default, _logManager, 1); - validator.OnBlockProcessingStart(_block); + validator.OnBlockProcessingStart(_block, _stateProvider); _stateProvider.Received(1).CreateAccount(Address.SystemUser, UInt256.Zero); _stateProvider.Received(1).Commit(Homestead.Instance); @@ -180,18 +180,19 @@ public void loads_initial_validators_from_contract(long blockNumber) validator.Validators = new[] { TestItem.AddressD }; } - validator.OnBlockProcessingStart(block); + validator.OnBlockProcessingStart(block, _stateProvider); // getValidators should have been called _transactionProcessor.Received() .CallAndRestore( + Arg.Any(), Arg.Is(t => CheckTransaction(t, _getValidatorsData)), Arg.Is(blkCtx => blkCtx.Header.Equals(_parentHeader)), Arg.Is(t => t is CallOutputTracer)); // finalizeChange should be called _transactionProcessor.Received(finalizeChangeCalled ? 1 : 0) - .Execute(Arg.Is(t => CheckTransaction(t, _finalizeChangeData)), + .Execute(Arg.Any(),Arg.Is(t => CheckTransaction(t, _finalizeChangeData)), Arg.Is(blkCtx => blkCtx.Header.Equals(block.Header)), Arg.Is(t => t is CallOutputTracer)); @@ -521,7 +522,7 @@ public void consecutive_initiate_change_gets_finalized_and_switch_validators(Con _blockTree.FindBlock(_block.Header.Hash, Arg.Any()).Returns(new Block(_block.Header.Clone())); - Action preProcess = () => validator.OnBlockProcessingStart(_block); + Action preProcess = () => validator.OnBlockProcessingStart(_block, _stateProvider); preProcess.Should().NotThrow(test.TestName); validator.OnBlockProcessingEnd(_block, txReceipts); int finalizedNumber = blockNumber - validator.Validators.MinSealersForFinalization() + 1; @@ -587,7 +588,7 @@ IEnumerable GetAllBlocks(BlockTree bt) _blockFinalizationManager.GetLastLevelFinalizedBy(blockTree.Head.ParentHash).Returns(lastLevelFinalized); - validator.OnBlockProcessingStart(blockTree.FindBlock(blockTree.Head.Hash, BlockTreeLookupOptions.None)); + validator.OnBlockProcessingStart(blockTree.FindBlock(blockTree.Head.Hash, BlockTreeLookupOptions.None), _stateProvider); PendingValidators pendingValidators = null; if (expectedBlockValidators.HasValue) @@ -604,7 +605,7 @@ private void ValidateFinalizationForChain(ConsecutiveInitiateChangeTestParameter { // finalizeChange should be called or not based on test spec _transactionProcessor.Received(chain.ExpectedFinalizationCount) - .Execute(Arg.Is(t => CheckTransaction(t, _finalizeChangeData)), + .Execute(Arg.Any(), Arg.Is(t => CheckTransaction(t, _finalizeChangeData)), Arg.Is(blkCtx => blkCtx.Header.Equals(_block.Header)), Arg.Is(t => t is CallOutputTracer)); @@ -635,6 +636,7 @@ private void SetupInitialValidators(BlockHeader header, BlockHeader parentHeader } _transactionProcessor.When(x => x.CallAndRestore( + Arg.Any(), Arg.Is(t => CheckTransaction(t, _getValidatorsData)), Arg.Any(), Arg.Is(t => t is CallOutputTracer))) diff --git a/src/Nethermind/Nethermind.AuRa.Test/Validators/MultiValidatorTests.cs b/src/Nethermind/Nethermind.AuRa.Test/Validators/MultiValidatorTests.cs index a06c0245c51..229f87d5ec5 100644 --- a/src/Nethermind/Nethermind.AuRa.Test/Validators/MultiValidatorTests.cs +++ b/src/Nethermind/Nethermind.AuRa.Test/Validators/MultiValidatorTests.cs @@ -14,6 +14,7 @@ using Nethermind.Core.Test.Builders; using Nethermind.Specs.ChainSpecStyle; using Nethermind.Logging; +using Nethermind.State; using NSubstitute; using NUnit.Framework; @@ -160,7 +161,7 @@ public long initializes_validator_when_producing_block(long blockNumber) { IAuRaValidator validator = new MultiValidator(_validator, _factory, _blockTree, _validatorStore, _finalizationManager, default, _logManager); _block.Header.Number = blockNumber; - validator.OnBlockProcessingStart(_block, ProcessingOptions.ProducingBlock); + validator.OnBlockProcessingStart(_block, Substitute.For(), ProcessingOptions.ProducingBlock); _innerValidators.Count.Should().Be(2); return _innerValidators.Keys.Last(); } @@ -178,7 +179,7 @@ public long initializes_validator_when_on_nonconsecutive_block(long blockNumber, _validator.Validators.ToList().TryGetSearchedItem(in blockNumber, (l, pair) => l.CompareTo(pair.Key), out KeyValuePair validatorInfo); _finalizationManager.GetFinalizationLevel(validatorInfo.Key).Returns(finalizedLastValidatorBlockLevel ? blockNumber - 2 : (long?)null); _block.Header.Number = blockNumber; - validator.OnBlockProcessingStart(_block); + validator.OnBlockProcessingStart(_block, Substitute.For()); return _innerValidators.Keys.Last(); } @@ -187,7 +188,7 @@ private void ProcessBlocks(long count, IAuRaValidator validator, int blocksToFin for (int i = 1; i < count; i++) { _block.Header.Number = i; - validator.OnBlockProcessingStart(_block); + validator.OnBlockProcessingStart(_block, Substitute.For()); validator.OnBlockProcessingEnd(_block, Array.Empty()); int finalizedBlock = i - blocksToFinalization; @@ -206,7 +207,7 @@ private void EnsureInnerValidatorsCalled(Func()); + innerValidator.Received(calls).OnBlockProcessingStart(Arg.Any(), Arg.Any()); innerValidator.Received(calls).OnBlockProcessingEnd(Arg.Any(), Array.Empty()); } diff --git a/src/Nethermind/Nethermind.Blockchain.Test/GenesisLoaderTests.cs b/src/Nethermind/Nethermind.Blockchain.Test/GenesisLoaderTests.cs index 539e2505405..f7e7c788e4c 100644 --- a/src/Nethermind/Nethermind.Blockchain.Test/GenesisLoaderTests.cs +++ b/src/Nethermind/Nethermind.Blockchain.Test/GenesisLoaderTests.cs @@ -65,7 +65,7 @@ private Block GetGenesisBlock(string chainspecPath) specProvider.GetSpec(Arg.Any()).Returns(Berlin.Instance); ITransactionProcessor transactionProcessor = Substitute.For(); GenesisLoader genesisLoader = new(chainSpec, specProvider, stateProvider, transactionProcessor); - return genesisLoader.Load(); + return genesisLoader.Load(stateProvider); } diff --git a/src/Nethermind/Nethermind.Blockchain.Test/Producers/DevBlockproducerTests.cs b/src/Nethermind/Nethermind.Blockchain.Test/Producers/DevBlockproducerTests.cs index 3afe77c9aa6..3b30d752979 100644 --- a/src/Nethermind/Nethermind.Blockchain.Test/Producers/DevBlockproducerTests.cs +++ b/src/Nethermind/Nethermind.Blockchain.Test/Producers/DevBlockproducerTests.cs @@ -66,7 +66,6 @@ public void Test() LimboLogs.Instance); TransactionProcessor txProcessor = new( specProvider, - stateProvider, virtualMachine, codeInfoRepository, LimboLogs.Instance); diff --git a/src/Nethermind/Nethermind.Blockchain.Test/ReorgTests.cs b/src/Nethermind/Nethermind.Blockchain.Test/ReorgTests.cs index f48be888945..14a83096a3f 100644 --- a/src/Nethermind/Nethermind.Blockchain.Test/ReorgTests.cs +++ b/src/Nethermind/Nethermind.Blockchain.Test/ReorgTests.cs @@ -65,7 +65,6 @@ public void Setup() LimboLogs.Instance); TransactionProcessor transactionProcessor = new( specProvider, - stateProvider, virtualMachine, codeInfoRepository, LimboLogs.Instance); diff --git a/src/Nethermind/Nethermind.Blockchain.Test/Rewards/NoBlockRewardsTests.cs b/src/Nethermind/Nethermind.Blockchain.Test/Rewards/NoBlockRewardsTests.cs index ce38a2ce14a..f06fc3182bb 100644 --- a/src/Nethermind/Nethermind.Blockchain.Test/Rewards/NoBlockRewardsTests.cs +++ b/src/Nethermind/Nethermind.Blockchain.Test/Rewards/NoBlockRewardsTests.cs @@ -4,6 +4,8 @@ using Nethermind.Consensus.Rewards; using Nethermind.Core; using Nethermind.Core.Test.Builders; +using Nethermind.State; +using NSubstitute; using NUnit.Framework; namespace Nethermind.Blockchain.Test.Rewards @@ -15,7 +17,7 @@ public void No_rewards() { Block block = Build.A.Block.WithNumber(10).WithUncles(Build.A.Block.WithNumber(9).TestObject).TestObject; NoBlockRewards calculator = NoBlockRewards.Instance; - var rewards = calculator.CalculateRewards(block); + var rewards = calculator.CalculateRewards(block, Substitute.For()); Assert.IsEmpty(rewards); } } diff --git a/src/Nethermind/Nethermind.Blockchain.Test/Rewards/RewardCalculatorTests.cs b/src/Nethermind/Nethermind.Blockchain.Test/Rewards/RewardCalculatorTests.cs index 041676676af..b271c9e704d 100644 --- a/src/Nethermind/Nethermind.Blockchain.Test/Rewards/RewardCalculatorTests.cs +++ b/src/Nethermind/Nethermind.Blockchain.Test/Rewards/RewardCalculatorTests.cs @@ -5,6 +5,8 @@ using Nethermind.Core; using Nethermind.Core.Test.Builders; using Nethermind.Specs; +using Nethermind.State; +using NSubstitute; using NUnit.Framework; namespace Nethermind.Blockchain.Test.Rewards @@ -19,7 +21,7 @@ public void Two_uncles_from_the_same_coinbase() Block block = Build.A.Block.WithNumber(3).WithUncles(uncle, uncle2).TestObject; RewardCalculator calculator = new(MainnetSpecProvider.Instance); - BlockReward[] rewards = calculator.CalculateRewards(block); + BlockReward[] rewards = calculator.CalculateRewards(block, Substitute.For()); Assert.That(rewards.Length, Is.EqualTo(3)); Assert.That((long)rewards[0].Value, Is.EqualTo(5312500000000000000), "miner"); @@ -34,7 +36,7 @@ public void One_uncle() Block block = Build.A.Block.WithNumber(3).WithUncles(uncle).TestObject; RewardCalculator calculator = new(MainnetSpecProvider.Instance); - BlockReward[] rewards = calculator.CalculateRewards(block); + BlockReward[] rewards = calculator.CalculateRewards(block, Substitute.For()); Assert.That(rewards.Length, Is.EqualTo(2)); Assert.That((long)rewards[0].Value, Is.EqualTo(5156250000000000000), "miner"); @@ -47,7 +49,7 @@ public void No_uncles() Block block = Build.A.Block.WithNumber(3).TestObject; RewardCalculator calculator = new(MainnetSpecProvider.Instance); - BlockReward[] rewards = calculator.CalculateRewards(block); + BlockReward[] rewards = calculator.CalculateRewards(block, Substitute.For()); Assert.That(rewards.Length, Is.EqualTo(1)); Assert.That((long)rewards[0].Value, Is.EqualTo(5000000000000000000), "miner"); @@ -62,7 +64,7 @@ public void Byzantium_reward_two_uncles() Block block = Build.A.Block.WithNumber(blockNumber).WithUncles(uncle, uncle2).TestObject; RewardCalculator calculator = new(MainnetSpecProvider.Instance); - BlockReward[] rewards = calculator.CalculateRewards(block); + BlockReward[] rewards = calculator.CalculateRewards(block, Substitute.For()); Assert.That(rewards.Length, Is.EqualTo(3)); Assert.That((long)rewards[0].Value, Is.EqualTo(3187500000000000000), "miner"); @@ -79,7 +81,7 @@ public void Constantinople_reward_two_uncles() Block block = Build.A.Block.WithNumber(blockNumber).WithUncles(uncle, uncle2).TestObject; RewardCalculator calculator = new(MainnetSpecProvider.Instance); - BlockReward[] rewards = calculator.CalculateRewards(block); + BlockReward[] rewards = calculator.CalculateRewards(block, Substitute.For()); Assert.That(rewards.Length, Is.EqualTo(3)); Assert.That((long)rewards[0].Value, Is.EqualTo(2125000000000000000), "miner"); diff --git a/src/Nethermind/Nethermind.Blockchain.Test/TransactionsExecutorTests.cs b/src/Nethermind/Nethermind.Blockchain.Test/TransactionsExecutorTests.cs index 8799490191a..039e69a9184 100644 --- a/src/Nethermind/Nethermind.Blockchain.Test/TransactionsExecutorTests.cs +++ b/src/Nethermind/Nethermind.Blockchain.Test/TransactionsExecutorTests.cs @@ -271,7 +271,7 @@ public void Proper_transactions_selected(TransactionSelectorTests.ProperTransact specProvider.GetSpec(Arg.Any()).Returns(spec); ITransactionProcessor transactionProcessor = Substitute.For(); - transactionProcessor.When(t => t.BuildUp(Arg.Any(), Arg.Any(), Arg.Any())) + transactionProcessor.When(t => t.BuildUp(Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any())) .Do(info => { Transaction tx = info.Arg(); diff --git a/src/Nethermind/Nethermind.Blockchain/Contracts/CallableContract.cs b/src/Nethermind/Nethermind.Blockchain/Contracts/CallableContract.cs index 54ddaf92945..3d8ce2cdd2c 100644 --- a/src/Nethermind/Nethermind.Blockchain/Contracts/CallableContract.cs +++ b/src/Nethermind/Nethermind.Blockchain/Contracts/CallableContract.cs @@ -29,7 +29,7 @@ protected CallableContract(ITransactionProcessor transactionProcessor, IAbiEncod _transactionProcessor = transactionProcessor ?? throw new ArgumentNullException(nameof(transactionProcessor)); } - private byte[] Call(BlockHeader header, string functionName, Transaction transaction) => CallCore(_transactionProcessor, header, functionName, transaction); + private byte[] Call(BlockHeader header, string functionName, Transaction transaction, IWorldState worldState) => CallCore(_transactionProcessor, header, functionName, transaction, worldState); /// /// Calls the function in contract, state modification is allowed. @@ -37,10 +37,12 @@ protected CallableContract(ITransactionProcessor transactionProcessor, IAbiEncod /// Header in which context the call is done. /// /// Sender of the transaction - caller of the function. + /// /// Arguments to the function. /// Deserialized return value of the based on its definition. - protected object[] Call(BlockHeader header, string functionName, Address sender, params object[] arguments) => - Call(header, functionName, sender, DefaultContractGasLimit, arguments); + protected object[] Call(BlockHeader header, string functionName, Address sender, IWorldState worldState, + params object[] arguments) => + Call(header, functionName, sender, (long)DefaultContractGasLimit, worldState, arguments); /// /// Calls the function in contract, state modification is allowed. @@ -49,24 +51,26 @@ protected object[] Call(BlockHeader header, string functionName, Address sender, /// /// Sender of the transaction - caller of the function. /// Gas limit for generated transaction. + /// /// Arguments to the function. /// Deserialized return value of the based on its definition. - protected object[] Call(BlockHeader header, string functionName, Address sender, long gasLimit, params object[] arguments) + protected object[] Call(BlockHeader header, string functionName, Address sender, long gasLimit, + IWorldState worldState, params object[] arguments) { var function = AbiDefinition.GetFunction(functionName); var transaction = GenerateTransaction(functionName, sender, gasLimit, header, arguments); - var result = Call(header, functionName, transaction); + var result = Call(header, functionName, transaction, worldState); var objects = DecodeData(function.GetReturnInfo(), result); return objects; } - private bool TryCall(BlockHeader header, Transaction transaction, out byte[] result) + private bool TryCall(BlockHeader header, Transaction transaction, out byte[] result, IWorldState worldState) { CallOutputTracer tracer = new(); try { - _transactionProcessor.Execute(transaction, new BlockExecutionContext(header), tracer); + _transactionProcessor.Execute(worldState, transaction, new BlockExecutionContext(header), tracer); result = tracer.ReturnValue; return tracer.StatusCode == StatusCode.Success; } @@ -84,10 +88,12 @@ private bool TryCall(BlockHeader header, Transaction transaction, out byte[] res /// /// Sender of the transaction - caller of the function. /// Deserialized return value of the based on its definition. + /// /// Arguments to the function. /// true if function was otherwise false. - protected bool TryCall(BlockHeader header, string functionName, Address sender, out object[] result, params object[] arguments) => - TryCall(header, functionName, sender, DefaultContractGasLimit, out result, arguments); + protected bool TryCall(BlockHeader header, string functionName, Address sender, out object[] result, + IWorldState worldState, params object[] arguments) => + TryCall(header, functionName, sender, DefaultContractGasLimit, worldState, out result, arguments); /// /// Same as but returns false instead of throwing . @@ -96,14 +102,17 @@ protected bool TryCall(BlockHeader header, string functionName, Address sender, /// /// Sender of the transaction - caller of the function. /// Gas limit for generated transaction. + /// /// Deserialized return value of the based on its definition. /// Arguments to the function. /// true if function was otherwise false. - protected bool TryCall(BlockHeader header, string functionName, Address sender, long gasLimit, out object[] result, params object[] arguments) + protected bool TryCall(BlockHeader header, string functionName, Address sender, long gasLimit, + IWorldState worldState, + out object[] result, params object[] arguments) { var function = AbiDefinition.GetFunction(functionName); var transaction = GenerateTransaction(functionName, sender, gasLimit, header, arguments); - if (TryCall(header, transaction, out var bytes)) + if (TryCall(header, transaction, out var bytes, worldState)) { result = DecodeData(function.GetReturnInfo(), bytes); return true; diff --git a/src/Nethermind/Nethermind.Blockchain/Contracts/Contract.ConstantContract.cs b/src/Nethermind/Nethermind.Blockchain/Contracts/Contract.ConstantContract.cs index d8b3f164d50..bccd654435a 100644 --- a/src/Nethermind/Nethermind.Blockchain/Contracts/Contract.ConstantContract.cs +++ b/src/Nethermind/Nethermind.Blockchain/Contracts/Contract.ConstantContract.cs @@ -58,9 +58,6 @@ protected ConstantContractBase(Contract contract) protected Transaction GenerateTransaction(CallInfo callInfo) => _contract.GenerateTransaction(callInfo.ContractAddress, callInfo.FunctionName, callInfo.Sender, DefaultConstantContractGasLimit, callInfo.ParentHeader, callInfo.Arguments); - protected byte[] CallCore(CallInfo callInfo, ITransactionProcessor readOnlyTransactionProcessor, Transaction transaction) => - _contract.CallCore(readOnlyTransactionProcessor, callInfo.ParentHeader, callInfo.FunctionName, transaction, true); - protected object[] DecodeReturnData(string functionName, byte[] data) => _contract.DecodeReturnData(functionName, data); public abstract object[] Call(CallInfo callInfo); @@ -95,7 +92,7 @@ protected virtual object[] CallRaw(CallInfo callInfo, IReadOnlyTxProcessingScope var transaction = GenerateTransaction(callInfo); if (_contract.ContractAddress is not null && scope.WorldState.IsContract(_contract.ContractAddress)) { - var result = CallCore(callInfo, scope.TransactionProcessor, transaction); + var result = _contract.CallCore(scope.TransactionProcessor, callInfo.ParentHeader, callInfo.FunctionName, transaction, scope.WorldState, true); return callInfo.Result = _contract.DecodeReturnData(callInfo.FunctionName, result); } else if (callInfo.MissingContractResult is not null) diff --git a/src/Nethermind/Nethermind.Blockchain/Contracts/Contract.cs b/src/Nethermind/Nethermind.Blockchain/Contracts/Contract.cs index cbb39fff9f0..bfe13d1bc4a 100644 --- a/src/Nethermind/Nethermind.Blockchain/Contracts/Contract.cs +++ b/src/Nethermind/Nethermind.Blockchain/Contracts/Contract.cs @@ -12,6 +12,7 @@ using Nethermind.Evm; using Nethermind.Evm.Tracing; using Nethermind.Evm.TransactionProcessing; +using Nethermind.State; namespace Nethermind.Blockchain.Contracts { @@ -165,10 +166,12 @@ protected virtual Transaction GenerateTransaction(Address? contractAddress, b /// Header in which context the call is done. /// Function name. /// Transaction to be executed. + /// /// Is it restore call. /// Bytes with result. /// Thrown when there is an exception during execution or is . - protected byte[] CallCore(ITransactionProcessor transactionProcessor, BlockHeader header, string functionName, Transaction transaction, bool callAndRestore = false) + protected byte[] CallCore(ITransactionProcessor transactionProcessor, BlockHeader header, string functionName, + Transaction transaction, IWorldState? worldState, bool callAndRestore = false) { bool failure; @@ -178,11 +181,11 @@ protected byte[] CallCore(ITransactionProcessor transactionProcessor, BlockHeade { if (callAndRestore) { - transactionProcessor.CallAndRestore(transaction, new BlockExecutionContext(header), tracer); + transactionProcessor.CallAndRestore(worldState!, transaction, new BlockExecutionContext(header), tracer); } else { - transactionProcessor.Execute(transaction, new BlockExecutionContext(header), tracer); + transactionProcessor.Execute(worldState!, transaction, new BlockExecutionContext(header), tracer); } failure = tracer.StatusCode != StatusCode.Success; diff --git a/src/Nethermind/Nethermind.Blockchain/GenesisLoader.cs b/src/Nethermind/Nethermind.Blockchain/GenesisLoader.cs index 28f4979bafe..4c035ff46b4 100644 --- a/src/Nethermind/Nethermind.Blockchain/GenesisLoader.cs +++ b/src/Nethermind/Nethermind.Blockchain/GenesisLoader.cs @@ -22,7 +22,6 @@ public class GenesisLoader { private readonly ChainSpec _chainSpec; private readonly ISpecProvider _specProvider; - private readonly IWorldState _stateProvider; private readonly ITransactionProcessor _transactionProcessor; private readonly BeaconBlockRootHandler _beaconBlockRootHandler; @@ -34,26 +33,25 @@ public GenesisLoader( { _chainSpec = chainSpec ?? throw new ArgumentNullException(nameof(chainSpec)); _specProvider = specProvider ?? throw new ArgumentNullException(nameof(specProvider)); - _stateProvider = stateProvider ?? throw new ArgumentNullException(nameof(stateProvider)); _transactionProcessor = transactionProcessor ?? throw new ArgumentNullException(nameof(transactionProcessor)); _beaconBlockRootHandler = new BeaconBlockRootHandler(); } - public Block Load() + public Block Load(IWorldState worldState) { Block genesis = _chainSpec.Genesis; - Preallocate(genesis); + Preallocate(genesis, worldState); // we no longer need the allocations - 0.5MB RAM, 9000 objects for mainnet _chainSpec.Allocations = null; if (!_chainSpec.GenesisStateUnavailable) { - _stateProvider.Commit(_specProvider.GenesisSpec, true); + worldState.Commit(_specProvider.GenesisSpec, true); - _stateProvider.CommitTree(0); + worldState.CommitTree(0); - genesis.Header.StateRoot = _stateProvider.StateRoot; + genesis.Header.StateRoot = worldState.StateRoot; } genesis.Header.Hash = genesis.Header.CalculateHash(); @@ -61,22 +59,22 @@ public Block Load() return genesis; } - private void Preallocate(Block genesis) + private void Preallocate(Block genesis, IWorldState worldState) { foreach ((Address address, ChainSpecAllocation allocation) in _chainSpec.Allocations.OrderBy(a => a.Key)) { - _stateProvider.CreateAccount(address, allocation.Balance, allocation.Nonce); + worldState.CreateAccount(address, allocation.Balance, allocation.Nonce); if (allocation.Code is not null) { - _stateProvider.InsertCode(address, allocation.Code, _specProvider.GenesisSpec, true); + worldState.InsertCode(address, allocation.Code, _specProvider.GenesisSpec, true); } if (allocation.Storage is not null) { foreach (KeyValuePair storage in allocation.Storage) { - _stateProvider.Set(new StorageCell(address, storage.Key), + worldState.Set(new StorageCell(address, storage.Key), storage.Value.WithoutLeadingZeros().ToArray()); } } @@ -91,7 +89,7 @@ private void Preallocate(Block genesis) }; CallOutputTracer outputTracer = new(); - _transactionProcessor.Execute(constructorTransaction, new BlockExecutionContext(genesis.Header), outputTracer); + _transactionProcessor.Execute(worldState, constructorTransaction, new BlockExecutionContext(genesis.Header), outputTracer); if (outputTracer.StatusCode != StatusCode.Success) { diff --git a/src/Nethermind/Nethermind.Clique.Test/CliqueBlockProducerTests.cs b/src/Nethermind/Nethermind.Clique.Test/CliqueBlockProducerTests.cs index 04c64ea3eaf..9e82746e5bf 100644 --- a/src/Nethermind/Nethermind.Clique.Test/CliqueBlockProducerTests.cs +++ b/src/Nethermind/Nethermind.Clique.Test/CliqueBlockProducerTests.cs @@ -129,7 +129,7 @@ public On CreateNode(PrivateKey privateKey, bool withGenesisAlreadyProcessed = f _genesis3Validators.Header.Hash = _genesis3Validators.Header.CalculateHash(); CodeInfoRepository codeInfoRepository = new(); - TransactionProcessor transactionProcessor = new(goerliSpecProvider, stateProvider, + TransactionProcessor transactionProcessor = new(goerliSpecProvider, new VirtualMachine(blockhashProvider, specProvider, codeInfoRepository, nodeLogManager), codeInfoRepository, nodeLogManager); @@ -150,7 +150,7 @@ public On CreateNode(PrivateKey privateKey, bool withGenesisAlreadyProcessed = f WorldState minerStateProvider = new(minerTrieStore, codeDb, nodeLogManager); VirtualMachine minerVirtualMachine = new(blockhashProvider, specProvider, codeInfoRepository, nodeLogManager); - TransactionProcessor minerTransactionProcessor = new(goerliSpecProvider, minerStateProvider, minerVirtualMachine, codeInfoRepository, nodeLogManager); + TransactionProcessor minerTransactionProcessor = new(goerliSpecProvider, minerVirtualMachine, codeInfoRepository, nodeLogManager); BlockProcessor minerBlockProcessor = new( goerliSpecProvider, diff --git a/src/Nethermind/Nethermind.Consensus.AuRa/AuRaBlockProcessor.cs b/src/Nethermind/Nethermind.Consensus.AuRa/AuRaBlockProcessor.cs index 51190c3dd7e..3df0258e61a 100644 --- a/src/Nethermind/Nethermind.Consensus.AuRa/AuRaBlockProcessor.cs +++ b/src/Nethermind/Nethermind.Consensus.AuRa/AuRaBlockProcessor.cs @@ -74,21 +74,23 @@ public AuRaBlockProcessor( public IAuRaValidator AuRaValidator { get; } - protected override TxReceipt[] ProcessBlock(Block block, IBlockTracer blockTracer, ProcessingOptions options) + protected override TxReceipt[] ProcessBlock(IWorldState worldState, Block block, IBlockTracer blockTracer, + ProcessingOptions options) { ValidateAuRa(block); _contractRewriter?.RewriteContracts(block.Number, _stateProvider, _specProvider.GetSpec(block.Header)); - AuRaValidator.OnBlockProcessingStart(block, options); - TxReceipt[] receipts = base.ProcessBlock(block, blockTracer, options); + AuRaValidator.OnBlockProcessingStart(block, worldState, options); + TxReceipt[] receipts = base.ProcessBlock(worldState, block, blockTracer, options); AuRaValidator.OnBlockProcessingEnd(block, receipts, options); Metrics.AuRaStep = block.Header?.AuRaStep ?? 0; return receipts; } // After PoS switch we need to revert to standard block processing, ignoring AuRa customizations - protected TxReceipt[] PostMergeProcessBlock(Block block, IBlockTracer blockTracer, ProcessingOptions options) + protected TxReceipt[] PostMergeProcessBlock(IWorldState worldState, Block block, IBlockTracer blockTracer, + ProcessingOptions options) { - return base.ProcessBlock(block, blockTracer, options); + return base.ProcessBlock(worldState, block, blockTracer, options); } // This validations cannot be run in AuraSealValidator because they are dependent on state. @@ -173,7 +175,8 @@ private AddingTxEventArgs CheckTxPosdaoRules(AddingTxEventArgs args) private class NullAuRaValidator : IAuRaValidator { public Address[] Validators => Array.Empty
(); - public void OnBlockProcessingStart(Block block, ProcessingOptions options = ProcessingOptions.None) { } + public void OnBlockProcessingStart(Block block, IWorldState worldState, + ProcessingOptions options = ProcessingOptions.None) { } public void OnBlockProcessingEnd(Block block, TxReceipt[] receipts, ProcessingOptions options = ProcessingOptions.None) { } } } diff --git a/src/Nethermind/Nethermind.Consensus.AuRa/Contracts/RewardContract.cs b/src/Nethermind/Nethermind.Consensus.AuRa/Contracts/RewardContract.cs index e78314f8d97..4902973ffe1 100644 --- a/src/Nethermind/Nethermind.Consensus.AuRa/Contracts/RewardContract.cs +++ b/src/Nethermind/Nethermind.Consensus.AuRa/Contracts/RewardContract.cs @@ -7,6 +7,7 @@ using Nethermind.Core; using Nethermind.Int256; using Nethermind.Evm.TransactionProcessing; +using Nethermind.State; namespace Nethermind.Consensus.AuRa.Contracts { @@ -21,13 +22,15 @@ public interface IRewardContract : IActivatedAtBlock /// /// benefactor addresses /// - /// Kind: - /// 0 - Author - Reward attributed to the block author - /// 2 - Empty step - Reward attributed to the author(s) of empty step(s) included in the block (AuthorityRound engine) - /// 3 - External - Reward attributed by an external protocol (e.g. block reward contract) - /// 101-106 - Uncle - Reward attributed to uncles, with distance 1 to 6 (Ethash engine) + /// Kind: + /// 0 - Author - Reward attributed to the block author + /// 2 - Empty step - Reward attributed to the author(s) of empty step(s) included in the block (AuthorityRound engine) + /// 3 - External - Reward attributed by an external protocol (e.g. block reward contract) + /// 101-106 - Uncle - Reward attributed to uncles, with distance 1 to 6 (Ethash engine) /// - (Address[] Addresses, UInt256[] Rewards) Reward(BlockHeader blockHeader, Address[] benefactors, ushort[] kind); + /// + (Address[] Addresses, UInt256[] Rewards) Reward(BlockHeader blockHeader, Address[] benefactors, ushort[] kind, + IWorldState worldState); } public sealed class RewardContract : CallableContract, IRewardContract @@ -49,15 +52,17 @@ public RewardContract(ITransactionProcessor transactionProcessor, IAbiEncoder ab /// /// benefactor addresses /// - /// Kind: - /// 0 - Author - Reward attributed to the block author - /// 2 - Empty step - Reward attributed to the author(s) of empty step(s) included in the block (AuthorityRound engine) - /// 3 - External - Reward attributed by an external protocol (e.g. block reward contract) - /// 101-106 - Uncle - Reward attributed to uncles, with distance 1 to 6 (Ethash engine) + /// Kind: + /// 0 - Author - Reward attributed to the block author + /// 2 - Empty step - Reward attributed to the author(s) of empty step(s) included in the block (AuthorityRound engine) + /// 3 - External - Reward attributed by an external protocol (e.g. block reward contract) + /// 101-106 - Uncle - Reward attributed to uncles, with distance 1 to 6 (Ethash engine) /// - public (Address[] Addresses, UInt256[] Rewards) Reward(BlockHeader blockHeader, Address[] benefactors, ushort[] kind) + /// + public (Address[] Addresses, UInt256[] Rewards) Reward(BlockHeader blockHeader, Address[] benefactors, + ushort[] kind, IWorldState worldState) { - var result = Call(blockHeader, nameof(Reward), Address.SystemUser, UnlimitedGas, benefactors, kind); + var result = Call(blockHeader, nameof(Reward), Address.SystemUser, UnlimitedGas, worldState, benefactors, kind); return ((Address[])result[0], (UInt256[])result[1]); } } diff --git a/src/Nethermind/Nethermind.Consensus.AuRa/Contracts/ValidatorContract.cs b/src/Nethermind/Nethermind.Consensus.AuRa/Contracts/ValidatorContract.cs index 7483dc283db..e273210bc6c 100644 --- a/src/Nethermind/Nethermind.Consensus.AuRa/Contracts/ValidatorContract.cs +++ b/src/Nethermind/Nethermind.Consensus.AuRa/Contracts/ValidatorContract.cs @@ -21,7 +21,7 @@ public partial interface IValidatorContract /// the "change" finalized is the activation of the initial set. /// function finalizeChange(); ///
- void FinalizeChange(BlockHeader blockHeader); + void FinalizeChange(BlockHeader blockHeader, IWorldState worldState); /// /// Get current validator set (last enacted or initial if no changes ever made) @@ -76,7 +76,7 @@ public ValidatorContract( /// the "change" finalized is the activation of the initial set. /// function finalizeChange(); /// - public void FinalizeChange(BlockHeader blockHeader) => TryCall(blockHeader, nameof(FinalizeChange), Address.SystemUser, UnlimitedGas, out _); + public void FinalizeChange(BlockHeader blockHeader, IWorldState worldState) => TryCall(blockHeader, nameof(FinalizeChange), Address.SystemUser, UnlimitedGas, worldState, out _); internal static readonly string GetValidatorsFunction = AbiDefinition.GetName(nameof(GetValidators)); diff --git a/src/Nethermind/Nethermind.Consensus.AuRa/Rewards/AuRaRewardCalculator.cs b/src/Nethermind/Nethermind.Consensus.AuRa/Rewards/AuRaRewardCalculator.cs index 280741ec67c..99234f504c8 100644 --- a/src/Nethermind/Nethermind.Consensus.AuRa/Rewards/AuRaRewardCalculator.cs +++ b/src/Nethermind/Nethermind.Consensus.AuRa/Rewards/AuRaRewardCalculator.cs @@ -10,6 +10,7 @@ using Nethermind.Core; using Nethermind.Evm.TransactionProcessing; using Nethermind.Specs.ChainSpecStyle; +using Nethermind.State; namespace Nethermind.Consensus.AuRa.Rewards { @@ -53,7 +54,7 @@ IList BuildTransitions() _blockRewardCalculator = new StaticRewardCalculator(auRaParameters.BlockReward); } - public BlockReward[] CalculateRewards(Block block) + public BlockReward[] CalculateRewards(Block block, IWorldState worldState) { if (block.IsGenesis) { @@ -61,12 +62,13 @@ public BlockReward[] CalculateRewards(Block block) } return _contracts.TryGetForBlock(block.Number, out var contract) - ? CalculateRewardsWithContract(block, contract) - : _blockRewardCalculator.CalculateRewards(block); + ? CalculateRewardsWithContract(block, contract, worldState) + : _blockRewardCalculator.CalculateRewards(block, worldState); } - private static BlockReward[] CalculateRewardsWithContract(Block block, IRewardContract contract) + private static BlockReward[] CalculateRewardsWithContract(Block block, IRewardContract contract, + IWorldState worldState) { (Address[] beneficieries, ushort[] kinds) GetBeneficiaries() { @@ -91,7 +93,7 @@ private static BlockReward[] CalculateRewardsWithContract(Block block, IRewardCo } var (beneficiaries, kinds) = GetBeneficiaries(); - var (addresses, rewards) = contract.Reward(block.Header, beneficiaries, kinds); + var (addresses, rewards) = contract.Reward(block.Header, beneficiaries, kinds, worldState); var blockRewards = new BlockReward[addresses.Length]; for (int index = 0; index < addresses.Length; index++) diff --git a/src/Nethermind/Nethermind.Consensus.AuRa/Rewards/StaticRewardCalculator.cs b/src/Nethermind/Nethermind.Consensus.AuRa/Rewards/StaticRewardCalculator.cs index 26f376b5ab6..a200cbec084 100644 --- a/src/Nethermind/Nethermind.Consensus.AuRa/Rewards/StaticRewardCalculator.cs +++ b/src/Nethermind/Nethermind.Consensus.AuRa/Rewards/StaticRewardCalculator.cs @@ -6,6 +6,7 @@ using Nethermind.Consensus.Rewards; using Nethermind.Core; using Nethermind.Int256; +using Nethermind.State; namespace Nethermind.Consensus.AuRa.Rewards { @@ -18,7 +19,7 @@ public StaticRewardCalculator(IDictionary? blockRewards) _blockRewards = CreateBlockRewards(blockRewards); } - public BlockReward[] CalculateRewards(Block block) + public BlockReward[] CalculateRewards(Block block, IWorldState worldState) { _blockRewards.TryGetForActivation(block.Number, out var blockReward); return new[] { new BlockReward(block.Beneficiary, blockReward.Reward) }; diff --git a/src/Nethermind/Nethermind.Consensus.AuRa/Validators/AuRaValidatorBase.cs b/src/Nethermind/Nethermind.Consensus.AuRa/Validators/AuRaValidatorBase.cs index b0fe7e7c540..a36880987db 100644 --- a/src/Nethermind/Nethermind.Consensus.AuRa/Validators/AuRaValidatorBase.cs +++ b/src/Nethermind/Nethermind.Consensus.AuRa/Validators/AuRaValidatorBase.cs @@ -6,6 +6,7 @@ using Nethermind.Consensus.Processing; using Nethermind.Core; using Nethermind.Logging; +using Nethermind.State; namespace Nethermind.Consensus.AuRa.Validators { @@ -44,7 +45,8 @@ protected void InitValidatorStore() } } - public virtual void OnBlockProcessingStart(Block block, ProcessingOptions options = ProcessingOptions.None) + public virtual void OnBlockProcessingStart(Block block, IWorldState worldState, + ProcessingOptions options = ProcessingOptions.None) { if (!options.ContainsFlag(ProcessingOptions.ProducingBlock) && !block.IsGenesis) { diff --git a/src/Nethermind/Nethermind.Consensus.AuRa/Validators/ContractBasedValidator.cs b/src/Nethermind/Nethermind.Consensus.AuRa/Validators/ContractBasedValidator.cs index c235d05a8ff..bc1292f1088 100644 --- a/src/Nethermind/Nethermind.Consensus.AuRa/Validators/ContractBasedValidator.cs +++ b/src/Nethermind/Nethermind.Consensus.AuRa/Validators/ContractBasedValidator.cs @@ -13,6 +13,7 @@ using Nethermind.Core; using Nethermind.Core.Crypto; using Nethermind.Logging; +using Nethermind.State; namespace Nethermind.Consensus.AuRa.Validators { @@ -72,7 +73,8 @@ public void Dispose() _blockFinalizationManager.BlocksFinalized -= OnBlocksFinalized; } - public override void OnBlockProcessingStart(Block block, ProcessingOptions options = ProcessingOptions.None) + public override void OnBlockProcessingStart(Block block, IWorldState worldState, + ProcessingOptions options = ProcessingOptions.None) { if (block.IsGenesis) { @@ -128,9 +130,9 @@ public override void OnBlockProcessingStart(Block block, ProcessingOptions optio } - base.OnBlockProcessingStart(block, options); + base.OnBlockProcessingStart(block, worldState, options); - FinalizePendingValidatorsIfNeeded(block.Header, isProducingBlock); + FinalizePendingValidatorsIfNeeded(block.Header, isProducingBlock, worldState); (_lastProcessedBlockNumber, _lastProcessedBlockHash) = (block.Number, block.Hash); } @@ -188,7 +190,7 @@ public override void OnBlockProcessingEnd(Block block, TxReceipt[] receipts, Pro } } - private void FinalizePendingValidatorsIfNeeded(BlockHeader block, bool isProducingBlock) + private void FinalizePendingValidatorsIfNeeded(BlockHeader block, bool isProducingBlock, IWorldState worldState) { var validatorsInfo = ValidatorStore.GetValidatorsInfo(block.Number); var isInitialValidatorSet = validatorsInfo.FinalizingBlockNumber == InitBlockNumber @@ -202,7 +204,7 @@ private void FinalizePendingValidatorsIfNeeded(BlockHeader block, bool isProduci if (block.Number == InitBlockNumber) ValidatorContract.EnsureSystemAccount(); - ValidatorContract.FinalizeChange(block); + ValidatorContract.FinalizeChange(block, worldState); } } diff --git a/src/Nethermind/Nethermind.Consensus.AuRa/Validators/IAuRaValidator.cs b/src/Nethermind/Nethermind.Consensus.AuRa/Validators/IAuRaValidator.cs index 2a5e66b85c4..e4db5cb2ce0 100644 --- a/src/Nethermind/Nethermind.Consensus.AuRa/Validators/IAuRaValidator.cs +++ b/src/Nethermind/Nethermind.Consensus.AuRa/Validators/IAuRaValidator.cs @@ -3,13 +3,15 @@ using Nethermind.Consensus.Processing; using Nethermind.Core; +using Nethermind.State; namespace Nethermind.Consensus.AuRa.Validators { public interface IAuRaValidator { Address[] Validators { get; } - void OnBlockProcessingStart(Block block, ProcessingOptions options = ProcessingOptions.None); + void OnBlockProcessingStart(Block block, IWorldState worldState, + ProcessingOptions options = ProcessingOptions.None); void OnBlockProcessingEnd(Block block, TxReceipt[] receipts, ProcessingOptions options = ProcessingOptions.None); } } diff --git a/src/Nethermind/Nethermind.Consensus.AuRa/Validators/MultiValidator.cs b/src/Nethermind/Nethermind.Consensus.AuRa/Validators/MultiValidator.cs index fc7f041d37c..f175879a592 100644 --- a/src/Nethermind/Nethermind.Consensus.AuRa/Validators/MultiValidator.cs +++ b/src/Nethermind/Nethermind.Consensus.AuRa/Validators/MultiValidator.cs @@ -12,6 +12,7 @@ using Nethermind.Core; using Nethermind.Logging; using Nethermind.Specs.ChainSpecStyle; +using Nethermind.State; namespace Nethermind.Consensus.AuRa.Validators { @@ -100,7 +101,8 @@ private void OnBlocksFinalized(object sender, FinalizeEventArgs e) } } - public void OnBlockProcessingStart(Block block, ProcessingOptions options = ProcessingOptions.None) + public void OnBlockProcessingStart(Block block, IWorldState worldState, + ProcessingOptions options = ProcessingOptions.None) { if (!block.IsGenesis) { @@ -139,7 +141,7 @@ public void OnBlockProcessingStart(Block block, ProcessingOptions options = Proc } } - _currentValidator?.OnBlockProcessingStart(block, options); + _currentValidator?.OnBlockProcessingStart(block, worldState, options); } private bool TryGetValidator(long blockNumber, out AuRaParameters.Validator validator) => _validators.TryGetValue(blockNumber, out validator); diff --git a/src/Nethermind/Nethermind.Consensus.AuRa/Validators/ReportingContractBasedValidator.cs b/src/Nethermind/Nethermind.Consensus.AuRa/Validators/ReportingContractBasedValidator.cs index 3d0ac523795..48646924940 100644 --- a/src/Nethermind/Nethermind.Consensus.AuRa/Validators/ReportingContractBasedValidator.cs +++ b/src/Nethermind/Nethermind.Consensus.AuRa/Validators/ReportingContractBasedValidator.cs @@ -207,9 +207,10 @@ public void TryReportSkipped(BlockHeader header, BlockHeader parent) public Address[] Validators => _contractValidator.Validators; - public void OnBlockProcessingStart(Block block, ProcessingOptions options = ProcessingOptions.None) + public void OnBlockProcessingStart(Block block, IWorldState worldState, + ProcessingOptions options = ProcessingOptions.None) { - _contractValidator.OnBlockProcessingStart(block, options); + _contractValidator.OnBlockProcessingStart(block, worldState, options); } public void OnBlockProcessingEnd(Block block, TxReceipt[] receipts, ProcessingOptions options = ProcessingOptions.None) diff --git a/src/Nethermind/Nethermind.Consensus.AuRa/Withdrawals/NullWithdrawalProcessor.cs b/src/Nethermind/Nethermind.Consensus.AuRa/Withdrawals/NullWithdrawalProcessor.cs index 24f84f52ba2..64ad8e2cb07 100644 --- a/src/Nethermind/Nethermind.Consensus.AuRa/Withdrawals/NullWithdrawalProcessor.cs +++ b/src/Nethermind/Nethermind.Consensus.AuRa/Withdrawals/NullWithdrawalProcessor.cs @@ -4,12 +4,13 @@ using Nethermind.Consensus.Withdrawals; using Nethermind.Core; using Nethermind.Core.Specs; +using Nethermind.State; namespace Nethermind.Consensus.AuRa.Withdrawals; public class NullWithdrawalProcessor : IWithdrawalProcessor { - public void ProcessWithdrawals(Block block, IReleaseSpec spec) { } + public void ProcessWithdrawals(Block block, IReleaseSpec spec, IWorldState worldState) { } public static IWithdrawalProcessor Instance { get; } = new NullWithdrawalProcessor(); } diff --git a/src/Nethermind/Nethermind.Consensus/Processing/BlockCachePreWarmer.cs b/src/Nethermind/Nethermind.Consensus/Processing/BlockCachePreWarmer.cs index c972b86f9d2..94c348bb39a 100644 --- a/src/Nethermind/Nethermind.Consensus/Processing/BlockCachePreWarmer.cs +++ b/src/Nethermind/Nethermind.Consensus/Processing/BlockCachePreWarmer.cs @@ -132,7 +132,7 @@ void WarmupTransactions(ParallelOptions parallelOptions, IReleaseSpec spec, Bloc { scope.WorldState.WarmUp(tx.AccessList); // eip-2930 } - TransactionResult result = scope.TransactionProcessor.Trace(systemTransaction, new BlockExecutionContext(block.Header.Clone()), NullTxTracer.Instance); + TransactionResult result = scope.TransactionProcessor.Trace(scope.WorldState, systemTransaction, new BlockExecutionContext(block.Header.Clone()), NullTxTracer.Instance); if (_logger.IsTrace) _logger.Trace($"Finished pre-warming cache for tx[{i}] {tx.Hash} with {result}"); } catch (Exception ex) diff --git a/src/Nethermind/Nethermind.Consensus/Processing/BlockProcessor.cs b/src/Nethermind/Nethermind.Consensus/Processing/BlockProcessor.cs index d3ea3d0fea5..164a02c7e62 100644 --- a/src/Nethermind/Nethermind.Consensus/Processing/BlockProcessor.cs +++ b/src/Nethermind/Nethermind.Consensus/Processing/BlockProcessor.cs @@ -121,7 +121,7 @@ the previous head state.*/ Task? preWarmTask = suggestedBlock.Transactions.Length < 3 ? null : _preWarmer?.PreWarmCaches(suggestedBlock, preBlockStateRoot!, cancellationTokenSource.Token); - (Block processedBlock, TxReceipt[] receipts) = ProcessOne(suggestedBlock, options, blockTracer); + (Block processedBlock, TxReceipt[] receipts) = ProcessOne(_stateProvider, suggestedBlock, options, blockTracer); cancellationTokenSource.Cancel(); preWarmTask?.GetAwaiter().GetResult(); processedBlocks[i] = processedBlock; @@ -212,13 +212,14 @@ private void RestoreBranch(Hash256 branchingPointStateRoot) } // TODO: block processor pipeline - private (Block Block, TxReceipt[] Receipts) ProcessOne(Block suggestedBlock, ProcessingOptions options, IBlockTracer blockTracer) + private (Block Block, TxReceipt[] Receipts) ProcessOne(IWorldState worldState, Block suggestedBlock, + ProcessingOptions options, IBlockTracer blockTracer) { if (_logger.IsTrace) _logger.Trace($"Processing block {suggestedBlock.ToString(Block.Format.Short)} ({options})"); ApplyDaoTransition(suggestedBlock); Block block = PrepareBlockForProcessing(suggestedBlock); - TxReceipt[] receipts = ProcessBlock(block, blockTracer, options); + TxReceipt[] receipts = ProcessBlock(worldState, block, blockTracer, options); ValidateProcessedBlock(suggestedBlock, options, block, receipts); if (options.ContainsFlag(ProcessingOptions.StoreReceipts)) { @@ -246,8 +247,7 @@ private bool ShouldComputeStateRoot(BlockHeader header) => !header.IsGenesis || !_specProvider.GenesisStateUnavailable; // TODO: block processor pipeline - protected virtual TxReceipt[] ProcessBlock( - Block block, + protected virtual TxReceipt[] ProcessBlock(IWorldState worldState, Block block, IBlockTracer blockTracer, ProcessingOptions options) { @@ -269,8 +269,8 @@ protected virtual TxReceipt[] ProcessBlock( } block.Header.ReceiptsRoot = _receiptsRootCalculator.GetReceiptsRoot(receipts, spec, block.ReceiptsRoot); - ApplyMinerRewards(block, blockTracer, spec); - _withdrawalProcessor.ProcessWithdrawals(block, spec); + ApplyMinerRewards(block, blockTracer, spec, worldState); + _withdrawalProcessor.ProcessWithdrawals(block, spec, worldState); ReceiptsTracer.EndBlockTrace(); _stateProvider.Commit(spec, commitStorageRoots: true); @@ -341,10 +341,10 @@ private Block PrepareBlockForProcessing(Block suggestedBlock) } // TODO: block processor pipeline - private void ApplyMinerRewards(Block block, IBlockTracer tracer, IReleaseSpec spec) + private void ApplyMinerRewards(Block block, IBlockTracer tracer, IReleaseSpec spec, IWorldState worldState) { if (_logger.IsTrace) _logger.Trace("Applying miner rewards:"); - BlockReward[] rewards = _rewardCalculator.CalculateRewards(block); + BlockReward[] rewards = _rewardCalculator.CalculateRewards(block, worldState); for (int i = 0; i < rewards.Length; i++) { BlockReward reward = rewards[i]; diff --git a/src/Nethermind/Nethermind.Consensus/Processing/ReadOnlyTxProcessingEnv.cs b/src/Nethermind/Nethermind.Consensus/Processing/ReadOnlyTxProcessingEnv.cs index 183a594d6d0..90c84fbbf0f 100644 --- a/src/Nethermind/Nethermind.Consensus/Processing/ReadOnlyTxProcessingEnv.cs +++ b/src/Nethermind/Nethermind.Consensus/Processing/ReadOnlyTxProcessingEnv.cs @@ -58,7 +58,7 @@ public ReadOnlyTxProcessingEnv( protected virtual TransactionProcessor CreateTransactionProcessor() { - return new TransactionProcessor(SpecProvider, StateProvider, Machine, CodeInfoRepository, _logManager); + return new TransactionProcessor(SpecProvider, Machine, CodeInfoRepository, _logManager); } public IReadOnlyTxProcessingScope Build(Hash256 stateRoot) diff --git a/src/Nethermind/Nethermind.Consensus/Processing/TransactionProcessorAdapterExtensions.cs b/src/Nethermind/Nethermind.Consensus/Processing/TransactionProcessorAdapterExtensions.cs index bd569caf479..e090960c5fe 100644 --- a/src/Nethermind/Nethermind.Consensus/Processing/TransactionProcessorAdapterExtensions.cs +++ b/src/Nethermind/Nethermind.Consensus/Processing/TransactionProcessorAdapterExtensions.cs @@ -24,7 +24,7 @@ public static TransactionResult ProcessTransaction(this ITransactionProcessorAda } using ITxTracer tracer = receiptsTracer.StartNewTxTrace(currentTx); - TransactionResult result = transactionProcessor.Execute(currentTx, in blkCtx, receiptsTracer); + TransactionResult result = transactionProcessor.Execute(stateProvider, currentTx, in blkCtx, receiptsTracer); receiptsTracer.EndTxTrace(); return result; } diff --git a/src/Nethermind/Nethermind.Consensus/Rewards/IRewardCalculator.cs b/src/Nethermind/Nethermind.Consensus/Rewards/IRewardCalculator.cs index b5bf1ccb106..b8fdf8a67e7 100644 --- a/src/Nethermind/Nethermind.Consensus/Rewards/IRewardCalculator.cs +++ b/src/Nethermind/Nethermind.Consensus/Rewards/IRewardCalculator.cs @@ -2,11 +2,12 @@ // SPDX-License-Identifier: LGPL-3.0-only using Nethermind.Core; +using Nethermind.State; namespace Nethermind.Consensus.Rewards { public interface IRewardCalculator { - BlockReward[] CalculateRewards(Block block); + BlockReward[] CalculateRewards(Block block, IWorldState worldState); } } diff --git a/src/Nethermind/Nethermind.Consensus/Rewards/NoBlockRewards.cs b/src/Nethermind/Nethermind.Consensus/Rewards/NoBlockRewards.cs index 9f067e47704..44e8d788679 100644 --- a/src/Nethermind/Nethermind.Consensus/Rewards/NoBlockRewards.cs +++ b/src/Nethermind/Nethermind.Consensus/Rewards/NoBlockRewards.cs @@ -4,6 +4,7 @@ using System; using Nethermind.Core; using Nethermind.Evm.TransactionProcessing; +using Nethermind.State; namespace Nethermind.Consensus.Rewards { @@ -15,7 +16,7 @@ private NoBlockRewards() { } private static readonly BlockReward[] _noRewards = Array.Empty(); - public BlockReward[] CalculateRewards(Block block) => _noRewards; + public BlockReward[] CalculateRewards(Block block, IWorldState worldState) => _noRewards; public IRewardCalculator Get(ITransactionProcessor processor) => Instance; } diff --git a/src/Nethermind/Nethermind.Consensus/Rewards/RewardCalculator.cs b/src/Nethermind/Nethermind.Consensus/Rewards/RewardCalculator.cs index bd0f6cad29e..9408e6923ee 100644 --- a/src/Nethermind/Nethermind.Consensus/Rewards/RewardCalculator.cs +++ b/src/Nethermind/Nethermind.Consensus/Rewards/RewardCalculator.cs @@ -6,6 +6,7 @@ using Nethermind.Core.Specs; using Nethermind.Evm.TransactionProcessing; using Nethermind.Int256; +using Nethermind.State; namespace Nethermind.Consensus.Rewards { @@ -24,7 +25,7 @@ private UInt256 GetBlockReward(Block block) return spec.BlockReward; } - public BlockReward[] CalculateRewards(Block block) + public BlockReward[] CalculateRewards(Block block, IWorldState worldState) { if (block.IsGenesis) { diff --git a/src/Nethermind/Nethermind.Consensus/Rewards/ZeroWeiRewards.cs b/src/Nethermind/Nethermind.Consensus/Rewards/ZeroWeiRewards.cs index 982b01b3bc9..8bb25b225eb 100644 --- a/src/Nethermind/Nethermind.Consensus/Rewards/ZeroWeiRewards.cs +++ b/src/Nethermind/Nethermind.Consensus/Rewards/ZeroWeiRewards.cs @@ -2,6 +2,7 @@ // SPDX-License-Identifier: LGPL-3.0-only using Nethermind.Core; +using Nethermind.State; namespace Nethermind.Consensus.Rewards { @@ -14,7 +15,7 @@ private ZeroWeiRewards() { } public static ZeroWeiRewards Instance { get; } = new(); - public BlockReward[] CalculateRewards(Block block) + public BlockReward[] CalculateRewards(Block block, IWorldState worldState) { return new[] { new BlockReward(block.Beneficiary, 0) }; } diff --git a/src/Nethermind/Nethermind.Consensus/Withdrawals/BlockProductionWithdrawalProcessor.cs b/src/Nethermind/Nethermind.Consensus/Withdrawals/BlockProductionWithdrawalProcessor.cs index c03f0702002..f51abc354d5 100644 --- a/src/Nethermind/Nethermind.Consensus/Withdrawals/BlockProductionWithdrawalProcessor.cs +++ b/src/Nethermind/Nethermind.Consensus/Withdrawals/BlockProductionWithdrawalProcessor.cs @@ -5,6 +5,7 @@ using Nethermind.Core; using Nethermind.Core.Crypto; using Nethermind.Core.Specs; +using Nethermind.State; using Nethermind.State.Proofs; namespace Nethermind.Consensus.Withdrawals; @@ -16,9 +17,9 @@ public class BlockProductionWithdrawalProcessor : IWithdrawalProcessor public BlockProductionWithdrawalProcessor(IWithdrawalProcessor processor) => _processor = processor ?? throw new ArgumentNullException(nameof(processor)); - public void ProcessWithdrawals(Block block, IReleaseSpec spec) + public void ProcessWithdrawals(Block block, IReleaseSpec spec, IWorldState worldState) { - _processor.ProcessWithdrawals(block, spec); + _processor.ProcessWithdrawals(block, spec, worldState); if (spec.WithdrawalsEnabled) { diff --git a/src/Nethermind/Nethermind.Consensus/Withdrawals/IWithdrawalProcessor.cs b/src/Nethermind/Nethermind.Consensus/Withdrawals/IWithdrawalProcessor.cs index 5909ba1f220..bf0b41eb4f8 100644 --- a/src/Nethermind/Nethermind.Consensus/Withdrawals/IWithdrawalProcessor.cs +++ b/src/Nethermind/Nethermind.Consensus/Withdrawals/IWithdrawalProcessor.cs @@ -3,10 +3,11 @@ using Nethermind.Core; using Nethermind.Core.Specs; +using Nethermind.State; namespace Nethermind.Consensus.Withdrawals; public interface IWithdrawalProcessor { - void ProcessWithdrawals(Block block, IReleaseSpec spec); + void ProcessWithdrawals(Block block, IReleaseSpec spec, IWorldState worldState); } diff --git a/src/Nethermind/Nethermind.Consensus/Withdrawals/WithdrawalProcessor.cs b/src/Nethermind/Nethermind.Consensus/Withdrawals/WithdrawalProcessor.cs index e315c5a5a8e..8994a037721 100644 --- a/src/Nethermind/Nethermind.Consensus/Withdrawals/WithdrawalProcessor.cs +++ b/src/Nethermind/Nethermind.Consensus/Withdrawals/WithdrawalProcessor.cs @@ -22,7 +22,7 @@ public WithdrawalProcessor(IWorldState stateProvider, ILogManager logManager) _stateProvider = stateProvider ?? throw new ArgumentNullException(nameof(stateProvider)); } - public void ProcessWithdrawals(Block block, IReleaseSpec spec) + public void ProcessWithdrawals(Block block, IReleaseSpec spec, IWorldState worldState) { if (!spec.WithdrawalsEnabled) return; diff --git a/src/Nethermind/Nethermind.Core.Test/Blockchain/TestBlockchain.cs b/src/Nethermind/Nethermind.Core.Test/Blockchain/TestBlockchain.cs index 87df1dec034..5b42b3625d6 100644 --- a/src/Nethermind/Nethermind.Core.Test/Blockchain/TestBlockchain.cs +++ b/src/Nethermind/Nethermind.Core.Test/Blockchain/TestBlockchain.cs @@ -187,7 +187,7 @@ protected virtual async Task Build(ISpecProvider? specProvider = CodeInfoRepository codeInfoRepository = new(); ReceiptStorage = new InMemoryReceiptStorage(blockTree: BlockTree); VirtualMachine virtualMachine = new(new BlockhashProvider(BlockTree, SpecProvider, State, LogManager), SpecProvider, codeInfoRepository, LogManager); - TxProcessor = new TransactionProcessor(SpecProvider, State, virtualMachine, codeInfoRepository, LogManager); + TxProcessor = new TransactionProcessor(SpecProvider, virtualMachine, codeInfoRepository, LogManager); BlockPreprocessorStep = new RecoverSignatures(EthereumEcdsa, TxPool, SpecProvider, LogManager); HeaderValidator = new HeaderValidator(BlockTree, Always.Valid, SpecProvider, LogManager); diff --git a/src/Nethermind/Nethermind.Evm.Test/Eip2935Tests.cs b/src/Nethermind/Nethermind.Evm.Test/Eip2935Tests.cs index 83e09c99131..47c99f1e8d0 100644 --- a/src/Nethermind/Nethermind.Evm.Test/Eip2935Tests.cs +++ b/src/Nethermind/Nethermind.Evm.Test/Eip2935Tests.cs @@ -46,7 +46,7 @@ public void CorrectBlockhashBeingUsed(ulong timestamp) (Block block, Transaction transaction) = PrepareTx(new ForkActivation(BlockNumber, timestamp), 100000, bytecode); CallOutputTracer callOutputTracer = new(); - _processor.Execute(transaction, block.Header, callOutputTracer); + _processor.Execute(TestState, transaction, block.Header, callOutputTracer); long expected = blockNumber; callOutputTracer.ReturnValue!.Should().BeEquivalentTo(Keccak.Compute(expected.ToString()).BytesToArray()); diff --git a/src/Nethermind/Nethermind.Evm.Test/Eip3198BaseFeeTests.cs b/src/Nethermind/Nethermind.Evm.Test/Eip3198BaseFeeTests.cs index 75430c258c1..ec807f9afb2 100644 --- a/src/Nethermind/Nethermind.Evm.Test/Eip3198BaseFeeTests.cs +++ b/src/Nethermind/Nethermind.Evm.Test/Eip3198BaseFeeTests.cs @@ -26,7 +26,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, Machine, CodeInfoRepository, LimboLogs.Instance); + _processor = new TransactionProcessor(SpecProvider, Machine, CodeInfoRepository, LimboLogs.Instance); byte[] code = Prepare.EvmCode .Op(Instruction.BASEFEE) .PushData(0) @@ -47,7 +47,7 @@ public void Base_fee_opcode_should_return_expected_results(bool eip3198Enabled, } TestAllTracerWithOutput tracer = CreateTracer(); - _processor.Execute(transaction, block.Header, tracer); + _processor.Execute(TestState, transaction, block.Header, tracer); if (eip3198Enabled) { diff --git a/src/Nethermind/Nethermind.Evm.Test/Eip3529RefundsTests.cs b/src/Nethermind/Nethermind.Evm.Test/Eip3529RefundsTests.cs index 510bc998b7d..4694ea4baf9 100644 --- a/src/Nethermind/Nethermind.Evm.Test/Eip3529RefundsTests.cs +++ b/src/Nethermind/Nethermind.Evm.Test/Eip3529RefundsTests.cs @@ -73,13 +73,13 @@ private void Test(string codeHex, long gasUsed, long refund, byte originalValue, 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, Machine, CodeInfoRepository, LimboLogs.Instance); + _processor = new TransactionProcessor(SpecProvider, Machine, CodeInfoRepository, LimboLogs.Instance); long blockNumber = eip3529Enabled ? MainnetSpecProvider.LondonBlockNumber : MainnetSpecProvider.LondonBlockNumber - 1; (Block block, Transaction transaction) = PrepareTx(blockNumber, 100000, Bytes.FromHexString(codeHex)); transaction.GasPrice = 20.GWei(); TestAllTracerWithOutput tracer = CreateTracer(); - _processor.Execute(transaction, block.Header, tracer); + _processor.Execute(TestState, transaction, block.Header, tracer); Assert.That(tracer.Refund, Is.EqualTo(refund)); AssertGas(tracer, gasUsed + GasCostOf.Transaction - Math.Min((gasUsed + GasCostOf.Transaction) / (eip3529Enabled ? RefundHelper.MaxRefundQuotientEIP3529 : RefundHelper.MaxRefundQuotient), refund)); @@ -161,16 +161,16 @@ public void After_3529_self_destruct_has_zero_refund(bool eip3529Enabled) Block block = Build.A.Block.WithNumber(blockNumber).WithTransactions(tx0, tx1, tx2, tx3).WithGasLimit(2 * gasLimit).TestObject; ParityLikeTxTracer tracer0 = new(block, tx0, ParityTraceTypes.Trace | ParityTraceTypes.StateDiff); - _processor.Execute(tx0, block.Header, tracer0); + _processor.Execute(TestState, tx0, block.Header, tracer0); TestAllTracerWithOutput tracer = CreateTracer(); - _processor.Execute(tx1, block.Header, tracer); + _processor.Execute(TestState, tx1, block.Header, tracer); tracer = CreateTracer(); - _processor.Execute(tx2, block.Header, tracer); + _processor.Execute(TestState, tx2, block.Header, tracer); tracer = CreateTracer(); - _processor.Execute(tx3, block.Header, tracer); + _processor.Execute(TestState, tx3, block.Header, tracer); long expectedRefund = eip3529Enabled ? 0 : 24000; Assert.That(tracer.Refund, Is.EqualTo(expectedRefund)); diff --git a/src/Nethermind/Nethermind.Evm.Test/Eip3541Tests.cs b/src/Nethermind/Nethermind.Evm.Test/Eip3541Tests.cs index 0c5f2219dd3..701dbc02416 100644 --- a/src/Nethermind/Nethermind.Evm.Test/Eip3541Tests.cs +++ b/src/Nethermind/Nethermind.Evm.Test/Eip3541Tests.cs @@ -96,7 +96,7 @@ void DeployCodeAndAssertTx(string code, bool eip3541Enabled, ContractDeployment break; } - _processor = new TransactionProcessor(SpecProvider, TestState, Machine, CodeInfoRepository, LimboLogs.Instance); + _processor = new TransactionProcessor(SpecProvider, Machine, CodeInfoRepository, LimboLogs.Instance); long blockNumber = eip3541Enabled ? MainnetSpecProvider.LondonBlockNumber : MainnetSpecProvider.LondonBlockNumber - 1; (Block block, Transaction transaction) = PrepareTx(blockNumber, 100000, createContract); @@ -104,7 +104,7 @@ void DeployCodeAndAssertTx(string code, bool eip3541Enabled, ContractDeployment transaction.To = null; transaction.Data = createContract; TestAllTracerWithOutput tracer = CreateTracer(); - _processor.Execute(transaction, block.Header, tracer); + _processor.Execute(TestState, transaction, block.Header, tracer); Assert.That(tracer.ReportedActionErrors.All(x => x != EvmExceptionType.InvalidCode), Is.EqualTo(withoutAnyInvalidCodeErrors), $"Code {code}, Context {context}"); } diff --git a/src/Nethermind/Nethermind.Evm.Test/Eip3860Tests.cs b/src/Nethermind/Nethermind.Evm.Test/Eip3860Tests.cs index 0e4029bffa2..784f1ced135 100644 --- a/src/Nethermind/Nethermind.Evm.Test/Eip3860Tests.cs +++ b/src/Nethermind/Nethermind.Evm.Test/Eip3860Tests.cs @@ -110,7 +110,7 @@ public void Test_EIP_3860_Enabled_InitCode_TxCreation_Within_Limit_Succeeds() transaction.To = null; transaction.Data = createCode; TestAllTracerWithOutput tracer = CreateTracer(); - TransactionResult result = _processor.Execute(transaction, block.Header, tracer); + TransactionResult result = _processor.Execute(TestState, transaction, block.Header, tracer); return (result, tracer); } } diff --git a/src/Nethermind/Nethermind.Evm.Test/Eip6780Tests.cs b/src/Nethermind/Nethermind.Evm.Test/Eip6780Tests.cs index 91e5329b87b..0b5c2f69e5c 100644 --- a/src/Nethermind/Nethermind.Evm.Test/Eip6780Tests.cs +++ b/src/Nethermind/Nethermind.Evm.Test/Eip6780Tests.cs @@ -70,9 +70,9 @@ public void self_destruct_not_in_same_transaction(ulong timestamp, bool onlyOnSa .WithTimestamp(timestamp) .WithTransactions(initTx, tx1).WithGasLimit(2 * _gasLimit).TestObject; - _processor.Execute(initTx, block.Header, NullTxTracer.Instance); + _processor.Execute(TestState, initTx, block.Header, NullTxTracer.Instance); UInt256 contractBalanceAfterInit = TestState.GetBalance(_contractAddress); - _processor.Execute(tx1, block.Header, NullTxTracer.Instance); + _processor.Execute(TestState, tx1, block.Header, NullTxTracer.Instance); contractBalanceAfterInit.Should().Be(99.Ether()); AssertSendAll(); @@ -101,9 +101,9 @@ public void self_destruct_not_in_same_transaction_should_not_burn(ulong timestam .WithTimestamp(timestamp) .WithTransactions(initTx, tx1).WithGasLimit(2 * _gasLimit).TestObject; - _processor.Execute(initTx, block.Header, NullTxTracer.Instance); + _processor.Execute(TestState, initTx, block.Header, NullTxTracer.Instance); UInt256 contractBalanceAfterInit = TestState.GetBalance(_contractAddress); - _processor.Execute(tx1, block.Header, NullTxTracer.Instance); + _processor.Execute(TestState, tx1, block.Header, NullTxTracer.Instance); contractBalanceAfterInit.Should().Be(99.Ether()); if (onlyOnSameTransaction) @@ -133,7 +133,7 @@ public void self_destruct_in_same_transaction() .WithTimestamp(Timestamp) .WithTransactions(createTx).WithGasLimit(2 * _gasLimit).TestObject; - _processor.Execute(createTx, block.Header, NullTxTracer.Instance); + _processor.Execute(TestState, createTx, block.Header, NullTxTracer.Instance); AssertDestroyed(); AssertSendAll(); @@ -155,7 +155,7 @@ public void self_destruct_in_initcode_of_create_opcodes() .WithTimestamp(Timestamp) .WithTransactions(createTx).WithGasLimit(2 * _gasLimit).TestObject; - _processor.Execute(createTx, block.Header, NullTxTracer.Instance); + _processor.Execute(TestState, createTx, block.Header, NullTxTracer.Instance); AssertDestroyed(); AssertSendAll(); @@ -169,7 +169,7 @@ public void self_destruct_in_initcode_of_create_tx() .WithTimestamp(Timestamp) .WithTransactions(createTx).WithGasLimit(2 * _gasLimit).TestObject; - _processor.Execute(createTx, block.Header, NullTxTracer.Instance); + _processor.Execute(TestState, createTx, block.Header, NullTxTracer.Instance); AssertDestroyed(); AssertSendAll(); diff --git a/src/Nethermind/Nethermind.Evm.Test/Eip7516BlobBaseFeeTests.cs b/src/Nethermind/Nethermind.Evm.Test/Eip7516BlobBaseFeeTests.cs index f62d8c595f6..73e498a59ea 100644 --- a/src/Nethermind/Nethermind.Evm.Test/Eip7516BlobBaseFeeTests.cs +++ b/src/Nethermind/Nethermind.Evm.Test/Eip7516BlobBaseFeeTests.cs @@ -27,7 +27,7 @@ public class Eip7516BlobBaseFeeTests : VirtualMachineTestsBase [TestCase(false, 0ul)] public void Blob_Base_fee_opcode_should_return_expected_results(bool eip7516Enabled, ulong excessBlobGas) { - _processor = new TransactionProcessor(SpecProvider, TestState, Machine, CodeInfoRepository, LimboLogs.Instance); + _processor = new TransactionProcessor(SpecProvider, Machine, CodeInfoRepository, LimboLogs.Instance); byte[] code = Prepare.EvmCode .Op(Instruction.BLOBBASEFEE) .PushData(0) @@ -39,7 +39,7 @@ public void Blob_Base_fee_opcode_should_return_expected_results(bool eip7516Enab block.Header.ExcessBlobGas = excessBlobGas; TestAllTracerWithOutput tracer = CreateTracer(); - _processor.Execute(transaction, block.Header, tracer); + _processor.Execute(TestState, transaction, block.Header, tracer); _ = BlobGasCalculator.TryCalculateBlobGasPricePerUnit(excessBlobGas, out UInt256 expectedGasPrice); if (eip7516Enabled) diff --git a/src/Nethermind/Nethermind.Evm.Test/EvmPooledMemoryTests.cs b/src/Nethermind/Nethermind.Evm.Test/EvmPooledMemoryTests.cs index 69e75399a8f..fc385494518 100644 --- a/src/Nethermind/Nethermind.Evm.Test/EvmPooledMemoryTests.cs +++ b/src/Nethermind/Nethermind.Evm.Test/EvmPooledMemoryTests.cs @@ -166,7 +166,6 @@ private static string Run(byte[] input) LimboLogs.Instance); TransactionProcessor transactionProcessor = new TransactionProcessor( specProvider, - stateProvider, virtualMachine, codeInfoRepository, LimboLogs.Instance); @@ -197,6 +196,7 @@ private static string Run(byte[] input) TestObject; MyTracer tracer = new(); transactionProcessor.Execute( + stateProvider, tx, new BlockExecutionContext(block.Header), tracer); diff --git a/src/Nethermind/Nethermind.Evm.Test/GasPriceExtractorTests.cs b/src/Nethermind/Nethermind.Evm.Test/GasPriceExtractorTests.cs index 874b16e4908..6df28d269d5 100644 --- a/src/Nethermind/Nethermind.Evm.Test/GasPriceExtractorTests.cs +++ b/src/Nethermind/Nethermind.Evm.Test/GasPriceExtractorTests.cs @@ -60,7 +60,7 @@ public void Keccak_gas_cost_assumption_is_correct() BlockNumber, 1000000, bytecode, rlp.Bytes, 0); CallOutputTracer callOutputTracer = new(); - _processor.Execute(transaction, block.Header, callOutputTracer); + _processor.Execute(TestState, transaction, block.Header, callOutputTracer); long minorCostsEstimate = 100; long keccakCostEstimate = 30 + 512 / 6; callOutputTracer.GasSpent.Should().BeLessThan(21000 + 9600 + minorCostsEstimate + keccakCostEstimate); @@ -92,7 +92,7 @@ public void Blockhash_times_256_gas_cost_assumption_is_correct() BlockNumber, 1000000, bytecode, rlp.Bytes, 0); CallOutputTracer callOutputTracer = new(); - _processor.Execute(transaction, block.Header, callOutputTracer); + _processor.Execute(TestState, transaction, block.Header, callOutputTracer); callOutputTracer.GasSpent.Should().BeLessThan(21000 + 9600 + 20000); } @@ -117,7 +117,7 @@ public void Blockhash_times_256_no_loop() BlockNumber, 1000000, bytecode, rlp.Bytes, 0); CallOutputTracer callOutputTracer = new(); - _processor.Execute(transaction, block.Header, callOutputTracer); + _processor.Execute(TestState, transaction, block.Header, callOutputTracer); callOutputTracer.GasSpent.Should().BeLessThan(21000 + 9600 + 20000); } diff --git a/src/Nethermind/Nethermind.Evm.Test/StorageAndSelfDestructTests.cs b/src/Nethermind/Nethermind.Evm.Test/StorageAndSelfDestructTests.cs index 97b553f28d8..187740c1727 100644 --- a/src/Nethermind/Nethermind.Evm.Test/StorageAndSelfDestructTests.cs +++ b/src/Nethermind/Nethermind.Evm.Test/StorageAndSelfDestructTests.cs @@ -70,15 +70,15 @@ public void Load_self_destruct() Block block = Build.A.Block.WithNumber(MainnetSpecProvider.MuirGlacierBlockNumber).WithTransactions(initTx, tx1, tx2).WithGasLimit(2 * gasLimit).TestObject; ParityLikeTxTracer initTracer = new(block, initTx, ParityTraceTypes.Trace | ParityTraceTypes.StateDiff); - _processor.Execute(initTx, block.Header, initTracer); + _processor.Execute(TestState,initTx, block.Header, initTracer); AssertStorage(new StorageCell(contractAddress, 1), 0); ParityLikeTxTracer tracer1 = new(block, tx1, ParityTraceTypes.Trace | ParityTraceTypes.StateDiff); - _processor.Execute(tx1, block.Header, tracer1); + _processor.Execute(TestState, tx1, block.Header, tracer1); AssertStorage(new StorageCell(contractAddress, 1), 1); ParityLikeTxTracer tracer2 = new(block, tx2, ParityTraceTypes.Trace | ParityTraceTypes.StateDiff); - _processor.Execute(tx2, block.Header, tracer2); + _processor.Execute(TestState, tx2, block.Header, tracer2); AssertStorage(new StorageCell(contractAddress, 1), 0); } @@ -158,31 +158,31 @@ public void Destroy_restore_store() Block block = Build.A.Block.WithNumber(MainnetSpecProvider.MuirGlacierBlockNumber).WithTransactions(tx0, tx1, tx2, tx3, tx4, tx5).WithGasLimit(2 * gasLimit).TestObject; ParityLikeTxTracer tracer0 = new(block, tx0, ParityTraceTypes.Trace | ParityTraceTypes.StateDiff); - _processor.Execute(tx0, block.Header, tracer0); + _processor.Execute(TestState, tx0, block.Header, tracer0); // AssertStorage(new StorageCell(deploymentAddress, 1), 0); ParityLikeTxTracer tracer = new(block, tx1, ParityTraceTypes.Trace | ParityTraceTypes.StateDiff); - _processor.Execute(tx1, block.Header, tracer); + _processor.Execute(TestState, tx1, block.Header, tracer); // AssertStorage(new StorageCell(deploymentAddress, 1), 0); // AssertStorage(new StorageCell(deploymentAddress, 2), 2); tracer = new ParityLikeTxTracer(block, tx2, ParityTraceTypes.Trace | ParityTraceTypes.StateDiff); - _processor.Execute(tx2, block.Header, tracer); + _processor.Execute(TestState, tx2, block.Header, tracer); // AssertStorage(new StorageCell(deploymentAddress, 1), 1); // AssertStorage(new StorageCell(deploymentAddress, 2), 2); tracer = new ParityLikeTxTracer(block, tx3, ParityTraceTypes.Trace | ParityTraceTypes.StateDiff); - _processor.Execute(tx3, block.Header, tracer); + _processor.Execute(TestState, tx3, block.Header, tracer); // AssertStorage(new StorageCell(deploymentAddress, 1), 0); // AssertStorage(new StorageCell(deploymentAddress, 2), 0); tracer = new ParityLikeTxTracer(block, tx4, ParityTraceTypes.Trace | ParityTraceTypes.StateDiff); - _processor.Execute(tx4, block.Header, tracer); + _processor.Execute(TestState, tx4, block.Header, tracer); // AssertStorage(new StorageCell(deploymentAddress, 1), 0); // AssertStorage(new StorageCell(deploymentAddress, 2), 2); tracer = new ParityLikeTxTracer(block, tx5, ParityTraceTypes.Trace | ParityTraceTypes.StateDiff); - _processor.Execute(tx5, block.Header, tracer); + _processor.Execute(TestState, tx5, block.Header, tracer); AssertStorage(new StorageCell(deploymentAddress, 1), 1); AssertStorage(new StorageCell(deploymentAddress, 2), 2); } @@ -263,34 +263,34 @@ public void Destroy_restore_store_different_cells() Block block = Build.A.Block.WithNumber(MainnetSpecProvider.MuirGlacierBlockNumber).WithTransactions(tx0, tx1, tx2, tx3, tx4, tx5).WithGasLimit(2 * gasLimit).TestObject; ParityLikeTxTracer tracer0 = new(block, tx0, ParityTraceTypes.Trace | ParityTraceTypes.StateDiff); - _processor.Execute(tx0, block.Header, tracer0); + _processor.Execute(TestState, tx0, block.Header, tracer0); AssertStorage(new StorageCell(deploymentAddress, 1), 0); ParityLikeTxTracer tracer = new(block, tx1, ParityTraceTypes.Trace | ParityTraceTypes.StateDiff); - _processor.Execute(tx1, block.Header, tracer); + _processor.Execute(TestState, tx1, block.Header, tracer); // AssertStorage(new StorageCell(deploymentAddress, 1), 0); // AssertStorage(new StorageCell(deploymentAddress, 2), 2); tracer = new ParityLikeTxTracer(block, tx2, ParityTraceTypes.Trace | ParityTraceTypes.StateDiff); - _processor.Execute(tx2, block.Header, tracer); + _processor.Execute(TestState, tx2, block.Header, tracer); // AssertStorage(new StorageCell(deploymentAddress, 1), 1); // AssertStorage(new StorageCell(deploymentAddress, 2), 2); // AssertStorage(new StorageCell(deploymentAddress, 3), 0); tracer = new ParityLikeTxTracer(block, tx3, ParityTraceTypes.Trace | ParityTraceTypes.StateDiff); - _processor.Execute(tx3, block.Header, tracer); + _processor.Execute(TestState, tx3, block.Header, tracer); // AssertStorage(new StorageCell(deploymentAddress, 1), 0); // AssertStorage(new StorageCell(deploymentAddress, 2), 0); // AssertStorage(new StorageCell(deploymentAddress, 3), 0); tracer = new ParityLikeTxTracer(block, tx4, ParityTraceTypes.Trace | ParityTraceTypes.StateDiff); - _processor.Execute(tx4, block.Header, tracer); + _processor.Execute(TestState, tx4, block.Header, tracer); // AssertStorage(new StorageCell(deploymentAddress, 1), 0); // AssertStorage(new StorageCell(deploymentAddress, 2), 0); // AssertStorage(new StorageCell(deploymentAddress, 3), 2); tracer = new ParityLikeTxTracer(block, tx5, ParityTraceTypes.Trace | ParityTraceTypes.StateDiff); - _processor.Execute(tx5, block.Header, tracer); + _processor.Execute(TestState, tx5, block.Header, tracer); AssertStorage(new StorageCell(deploymentAddress, 1), 1); AssertStorage(new StorageCell(deploymentAddress, 2), 0); AssertStorage(new StorageCell(deploymentAddress, 3), 2); @@ -378,22 +378,22 @@ public void Destroy_restore_store_different_cells_previously_existing() Block block = Build.A.Block.WithNumber(MainnetSpecProvider.MuirGlacierBlockNumber).WithTransactions(tx0, tx1, tx2, tx3, tx4).WithGasLimit(2 * gasLimit).TestObject; ParityLikeTxTracer tracer = new(block, tx0, ParityTraceTypes.Trace | ParityTraceTypes.StateDiff); - _processor.Execute(tx0, block.Header, tracer); + _processor.Execute(TestState, tx0, block.Header, tracer); tracer = new ParityLikeTxTracer(block, tx1, ParityTraceTypes.Trace | ParityTraceTypes.StateDiff); - _processor.Execute(tx1, block.Header, tracer); + _processor.Execute(TestState, tx1, block.Header, tracer); // AssertStorage(new StorageCell(deploymentAddress, 7), 7); tracer = new ParityLikeTxTracer(block, tx2, ParityTraceTypes.Trace | ParityTraceTypes.StateDiff); - _processor.Execute(tx2, block.Header, tracer); + _processor.Execute(TestState, tx2, block.Header, tracer); // AssertStorage(new StorageCell(deploymentAddress, 7), 0); tracer = new ParityLikeTxTracer(block, tx3, ParityTraceTypes.Trace | ParityTraceTypes.StateDiff); - _processor.Execute(tx3, block.Header, tracer); + _processor.Execute(TestState, tx3, block.Header, tracer); AssertStorage(new StorageCell(deploymentAddress, 7), 0); tracer = new ParityLikeTxTracer(block, tx4, ParityTraceTypes.Trace | ParityTraceTypes.StateDiff); - _processor.Execute(tx4, block.Header, tracer); + _processor.Execute(TestState, tx4, block.Header, tracer); AssertStorage(new StorageCell(deploymentAddress, 7), 0); } } diff --git a/src/Nethermind/Nethermind.Evm.Test/Tracing/AccessTxTracerTests.cs b/src/Nethermind/Nethermind.Evm.Test/Tracing/AccessTxTracerTests.cs index 8adbf775e74..3e5ce3a746c 100644 --- a/src/Nethermind/Nethermind.Evm.Test/Tracing/AccessTxTracerTests.cs +++ b/src/Nethermind/Nethermind.Evm.Test/Tracing/AccessTxTracerTests.cs @@ -123,7 +123,7 @@ public void ReportAccess_AddressAIsSetToOptmizedAndHasStorageCell_AccesslistHasC { (Block block, Transaction transaction) = PrepareTx(BlockNumber, 100000, code, addresses); AccessTxTracer tracer = new(); - _processor.Execute(transaction, block.Header, tracer); + _processor.Execute(TestState, transaction, block.Header, tracer); return (tracer, block, transaction); } } diff --git a/src/Nethermind/Nethermind.Evm.Test/Tracing/GasEstimationTests.cs b/src/Nethermind/Nethermind.Evm.Test/Tracing/GasEstimationTests.cs index c6af6bf6b3e..5d683580e7b 100644 --- a/src/Nethermind/Nethermind.Evm.Test/Tracing/GasEstimationTests.cs +++ b/src/Nethermind/Nethermind.Evm.Test/Tracing/GasEstimationTests.cs @@ -49,7 +49,7 @@ public void Does_not_take_into_account_precompiles() Array.Empty()); // this would not happen but we want to ensure that precompiles are ignored testEnvironment.tracer.ReportActionEnd(600, Array.Empty()); - testEnvironment.estimator.Estimate(tx, block.Header, testEnvironment.tracer).Should().Be(0); + testEnvironment.estimator.Estimate(testEnvironment._stateProvider, tx, block.Header, testEnvironment.tracer).Should().Be(0); } [Test] @@ -78,7 +78,7 @@ public void Handles_well_top_level() ExecutionType.TRANSACTION, false); testEnvironment.tracer.ReportActionEnd(600, Array.Empty()); - testEnvironment.estimator.Estimate(tx, block.Header, testEnvironment.tracer).Should().Be(0); + testEnvironment.estimator.Estimate(testEnvironment._stateProvider, tx, block.Header, testEnvironment.tracer).Should().Be(0); } [Test] @@ -105,7 +105,7 @@ public void Handles_well_serial_calls() testEnvironment.tracer.ReportActionEnd(300, Array.Empty()); // should not happen } - testEnvironment.estimator.Estimate(tx, block.Header, testEnvironment.tracer).Should().Be(14L); + testEnvironment.estimator.Estimate(testEnvironment._stateProvider, tx, block.Header, testEnvironment.tracer).Should().Be(14L); } [Test] @@ -134,7 +134,7 @@ public void Handles_well_errors() testEnvironment.tracer.ReportActionEnd(500, Array.Empty()); // should not happen } - testEnvironment.estimator.Estimate(tx, block.Header, testEnvironment.tracer).Should().Be(24L); + testEnvironment.estimator.Estimate(testEnvironment._stateProvider, tx, block.Header, testEnvironment.tracer).Should().Be(24L); } [Test] @@ -158,7 +158,7 @@ public void Handles_well_revert() testEnvironment.tracer.ReportActionError(EvmExceptionType.Revert, 96000000); testEnvironment.tracer.ReportActionError(EvmExceptionType.Revert, 98000000); testEnvironment.tracer.ReportActionError(EvmExceptionType.Revert, 99000000); - testEnvironment.estimator.Estimate(tx, block.Header, testEnvironment.tracer).Should().Be(35146L); + testEnvironment.estimator.Estimate(testEnvironment._stateProvider, tx, block.Header, testEnvironment.tracer).Should().Be(35146L); } [Test] @@ -175,7 +175,7 @@ public void Easy_one_level_case() testEnvironment.tracer.ReportActionEnd(63, Array.Empty()); // second level testEnvironment.tracer.ReportActionEnd(65, Array.Empty()); - testEnvironment.estimator.Estimate(tx, block.Header, testEnvironment.tracer).Should().Be(1); + testEnvironment.estimator.Estimate(testEnvironment._stateProvider, tx, block.Header, testEnvironment.tracer).Should().Be(1); } [Test] @@ -223,7 +223,7 @@ public void Handles_well_nested_calls_where_most_nested_defines_excess() testEnvironment.tracer.ReportActionEnd(500, Array.Empty()); // should not happen } - testEnvironment.estimator.Estimate(tx, block.Header, testEnvironment.tracer).Should().Be(18); + testEnvironment.estimator.Estimate(testEnvironment._stateProvider, tx, block.Header, testEnvironment.tracer).Should().Be(18); } [Test] @@ -252,7 +252,7 @@ public void Handles_well_nested_calls_where_least_nested_defines_excess() testEnvironment.tracer.ReportActionEnd(500, Array.Empty()); // should not happen } - testEnvironment.estimator.Estimate(tx, block.Header, testEnvironment.tracer).Should().Be(17); + testEnvironment.estimator.Estimate(testEnvironment._stateProvider, tx, block.Header, testEnvironment.tracer).Should().Be(17); } [TestCase(-1)] @@ -264,15 +264,14 @@ public void Estimate_UseErrorMarginOutsideBounds_ThrowArgumentOutOfRangeExceptio Block block = Build.A.Block.WithTransactions(tx).TestObject; EstimateGasTracer tracer = new(); tracer.MarkAsSuccess(Address.Zero, 1, Array.Empty(), Array.Empty()); - IReadOnlyStateProvider stateProvider = Substitute.For(); + IWorldState stateProvider = Substitute.For(); stateProvider.GetBalance(Arg.Any
()).Returns(new UInt256(1)); GasEstimator sut = new GasEstimator( Substitute.For(), - stateProvider, MainnetSpecProvider.Instance, new BlocksConfig()); - Assert.That(() => sut.Estimate(tx, block.Header, tracer, errorMargin), Throws.TypeOf()); + Assert.That(() => sut.Estimate(stateProvider, tx, block.Header, tracer, errorMargin), Throws.TypeOf()); } @@ -288,15 +287,14 @@ public void Estimate_DifferentAmountOfGasAndMargin_EstimationResultIsWithinMargi Block block = Build.A.Block.WithNumber(1).WithTransactions(tx).TestObject; EstimateGasTracer tracer = new(); tracer.MarkAsSuccess(Address.Zero, totalGas, Array.Empty(), Array.Empty()); - IReadOnlyStateProvider stateProvider = Substitute.For(); + IWorldState stateProvider = Substitute.For(); stateProvider.GetBalance(Arg.Any
()).Returns(new UInt256(1)); GasEstimator sut = new GasEstimator( Substitute.For(), - stateProvider, MainnetSpecProvider.Instance, new BlocksConfig()); - long result = sut.Estimate(tx, block.Header, tracer, errorMargin); + long result = sut.Estimate(stateProvider, tx, block.Header, tracer, errorMargin); Assert.That(result, Is.EqualTo(totalGas).Within(totalGas * (errorMargin / 10000d + 1))); } @@ -309,15 +307,14 @@ public void Estimate_UseErrorMargin_EstimationResultIsNotExact() EstimateGasTracer tracer = new(); const int totalGas = Transaction.BaseTxGasCost; tracer.MarkAsSuccess(Address.Zero, totalGas, Array.Empty(), Array.Empty()); - IReadOnlyStateProvider stateProvider = Substitute.For(); + IWorldState stateProvider = Substitute.For(); stateProvider.GetBalance(Arg.Any
()).Returns(new UInt256(1)); GasEstimator sut = new GasEstimator( Substitute.For(), - stateProvider, MainnetSpecProvider.Instance, new BlocksConfig()); - long result = sut.Estimate(tx, block.Header, tracer, GasEstimator.DefaultErrorMargin); + long result = sut.Estimate(stateProvider, tx, block.Header, tracer, GasEstimator.DefaultErrorMargin); Assert.That(result, Is.Not.EqualTo(totalGas).Within(10)); } @@ -330,15 +327,14 @@ public void Estimate_UseZeroErrorMargin_EstimationResultIsExact() EstimateGasTracer tracer = new(); const int totalGas = Transaction.BaseTxGasCost; tracer.MarkAsSuccess(Address.Zero, totalGas, Array.Empty(), Array.Empty()); - IReadOnlyStateProvider stateProvider = Substitute.For(); + IWorldState stateProvider = Substitute.For(); stateProvider.GetBalance(Arg.Any
()).Returns(new UInt256(1)); GasEstimator sut = new GasEstimator( Substitute.For(), - stateProvider, MainnetSpecProvider.Instance, new BlocksConfig()); - long result = sut.Estimate(tx, block.Header, tracer, 0); + long result = sut.Estimate(stateProvider, tx, block.Header, tracer, 0); Assert.That(result, Is.EqualTo(totalGas)); } @@ -364,12 +360,12 @@ public TestEnvironment() CodeInfoRepository codeInfoRepository = new(); VirtualMachine virtualMachine = new(new TestBlockhashProvider(_specProvider), _specProvider, codeInfoRepository, LimboLogs.Instance); - _transactionProcessor = new TransactionProcessor(_specProvider, _stateProvider, virtualMachine, codeInfoRepository, LimboLogs.Instance); + _transactionProcessor = new TransactionProcessor(_specProvider, virtualMachine, codeInfoRepository, LimboLogs.Instance); _ethereumEcdsa = new EthereumEcdsa(_specProvider.ChainId); tracer = new(); BlocksConfig blocksConfig = new(); - estimator = new(_transactionProcessor, _stateProvider, _specProvider, blocksConfig); + estimator = new(_transactionProcessor, _specProvider, blocksConfig); } } } diff --git a/src/Nethermind/Nethermind.Evm.Test/Tracing/GethLike4byteTracerTests.cs b/src/Nethermind/Nethermind.Evm.Test/Tracing/GethLike4byteTracerTests.cs index e59053f8107..667ab43b9c1 100644 --- a/src/Nethermind/Nethermind.Evm.Test/Tracing/GethLike4byteTracerTests.cs +++ b/src/Nethermind/Nethermind.Evm.Test/Tracing/GethLike4byteTracerTests.cs @@ -27,7 +27,7 @@ private GethLikeTxTrace ExecuteAndTrace( { Native4ByteTracer tracer = new Native4ByteTracer(GethTraceOptions.Default); (Block block, Transaction transaction) = input is null ? PrepareTx(Activation, 100000, code) : PrepareTx(Activation, 100000, code, input, value); - _processor.Execute(transaction, block.Header, tracer); + _processor.Execute(TestState, transaction, block.Header, tracer); return tracer.BuildResult(); } diff --git a/src/Nethermind/Nethermind.Evm.Test/Tracing/ParityLikeTxTracerTests.cs b/src/Nethermind/Nethermind.Evm.Test/Tracing/ParityLikeTxTracerTests.cs index a9a4e54b844..06c315a7a60 100644 --- a/src/Nethermind/Nethermind.Evm.Test/Tracing/ParityLikeTxTracerTests.cs +++ b/src/Nethermind/Nethermind.Evm.Test/Tracing/ParityLikeTxTracerTests.cs @@ -819,7 +819,7 @@ public void Is_tracing_rewards_only_when_rewards_trace_type_selected() { (Block block, Transaction transaction) = PrepareInitTx((BlockNumber, Timestamp), 100000, code); ParityLikeTxTracer tracer = new(block, transaction, ParityTraceTypes.Trace | ParityTraceTypes.StateDiff); - _processor.Execute(transaction, block.Header, tracer); + _processor.Execute(TestState, transaction, block.Header, tracer); return (tracer.BuildResult(), block, transaction); } @@ -827,7 +827,7 @@ public void Is_tracing_rewards_only_when_rewards_trace_type_selected() { (Block block, Transaction transaction) = PrepareTx(BlockNumber, 100000, code); ParityLikeTxTracer tracer = new(block, transaction, ParityTraceTypes.Trace | ParityTraceTypes.StateDiff | ParityTraceTypes.VmTrace); - _processor.Execute(transaction, block.Header, tracer); + _processor.Execute(TestState, transaction, block.Header, tracer); return (tracer.BuildResult(), block, transaction); } @@ -835,7 +835,7 @@ public void Is_tracing_rewards_only_when_rewards_trace_type_selected() { (Block block, Transaction transaction) = PrepareTx(BlockNumber, 100000, code); ParityLikeTxTracer tracer = new(block, transaction, traceTypes); - _processor.Execute(transaction, block.Header, tracer); + _processor.Execute(TestState, transaction, block.Header, tracer); return (tracer.BuildResult(), block, transaction); } @@ -843,7 +843,7 @@ public void Is_tracing_rewards_only_when_rewards_trace_type_selected() { (Block block, Transaction transaction) = PrepareTx(BlockNumber, 100000, code, input, value); ParityLikeTxTracer tracer = new(block, transaction, ParityTraceTypes.Trace | ParityTraceTypes.StateDiff); - TransactionResult result = _processor.Execute(transaction, block.Header, tracer); + TransactionResult result = _processor.Execute(TestState, transaction, block.Header, tracer); return (tracer.BuildResult(), block, transaction); } } diff --git a/src/Nethermind/Nethermind.Evm.Test/Tracing/ProofTxTracerTests.cs b/src/Nethermind/Nethermind.Evm.Test/Tracing/ProofTxTracerTests.cs index 53201b141c4..943f623af39 100644 --- a/src/Nethermind/Nethermind.Evm.Test/Tracing/ProofTxTracerTests.cs +++ b/src/Nethermind/Nethermind.Evm.Test/Tracing/ProofTxTracerTests.cs @@ -283,7 +283,7 @@ public void Can_trace_on_failure() { (Block block, Transaction transaction) = PrepareTx(BlockNumber, 100000, code, addresses); ProofTxTracer tracer = new(_treatSystemAccountDifferently); - _processor.Execute(transaction, block.Header, tracer); + _processor.Execute(TestState, transaction, block.Header, tracer); return (tracer, block, transaction); } } diff --git a/src/Nethermind/Nethermind.Evm.Test/TransactionProcessorEip4844Tests.cs b/src/Nethermind/Nethermind.Evm.Test/TransactionProcessorEip4844Tests.cs index fcd0eda8227..c97b97cba92 100644 --- a/src/Nethermind/Nethermind.Evm.Test/TransactionProcessorEip4844Tests.cs +++ b/src/Nethermind/Nethermind.Evm.Test/TransactionProcessorEip4844Tests.cs @@ -37,7 +37,7 @@ public void Setup() _stateProvider = new WorldState(trieStore, new MemDb(), LimboLogs.Instance); CodeInfoRepository codeInfoRepository = new(); VirtualMachine virtualMachine = new(new TestBlockhashProvider(_specProvider), _specProvider, codeInfoRepository, LimboLogs.Instance); - _transactionProcessor = new TransactionProcessor(_specProvider, _stateProvider, virtualMachine, codeInfoRepository, LimboLogs.Instance); + _transactionProcessor = new TransactionProcessor(_specProvider, virtualMachine, codeInfoRepository, LimboLogs.Instance); _ethereumEcdsa = new EthereumEcdsa(_specProvider.ChainId); } @@ -70,11 +70,11 @@ public UInt256 Balance_is_affected_by_blob_gas_on_execution(UInt256 balance, int .WithBaseFeePerGas(1) .TestObject; - _transactionProcessor.CallAndRestore(blobTx, block.Header, NullTxTracer.Instance); + _transactionProcessor.CallAndRestore(_stateProvider, blobTx, block.Header, NullTxTracer.Instance); UInt256 deltaBalance = balance - _stateProvider.GetBalance(TestItem.PrivateKeyA.Address); Assert.That(deltaBalance, Is.EqualTo(UInt256.Zero)); - _transactionProcessor.Execute(blobTx, block.Header, NullTxTracer.Instance); + _transactionProcessor.Execute(_stateProvider, blobTx, block.Header, NullTxTracer.Instance); deltaBalance = balance - _stateProvider.GetBalance(TestItem.PrivateKeyA.Address); return deltaBalance; diff --git a/src/Nethermind/Nethermind.Evm.Test/TransactionProcessorFeeTests.cs b/src/Nethermind/Nethermind.Evm.Test/TransactionProcessorFeeTests.cs index 574dcdbc171..fc857bccd43 100644 --- a/src/Nethermind/Nethermind.Evm.Test/TransactionProcessorFeeTests.cs +++ b/src/Nethermind/Nethermind.Evm.Test/TransactionProcessorFeeTests.cs @@ -44,7 +44,7 @@ public void Setup() CodeInfoRepository codeInfoRepository = new(); VirtualMachine virtualMachine = new(new TestBlockhashProvider(_specProvider), _specProvider, codeInfoRepository, LimboLogs.Instance); - _transactionProcessor = new TransactionProcessor(_specProvider, _stateProvider, virtualMachine, codeInfoRepository, LimboLogs.Instance); + _transactionProcessor = new TransactionProcessor(_specProvider, virtualMachine, codeInfoRepository, LimboLogs.Instance); _ethereumEcdsa = new EthereumEcdsa(_specProvider.ChainId); } @@ -173,7 +173,7 @@ public void Should_stop_when_cancellation(bool withCancellation) blockTracer.StartNewBlockTrace(block); { var txTracer = blockTracer.StartNewTxTrace(tx1); - _transactionProcessor.Execute(tx1, block.Header, txTracer); + _transactionProcessor.Execute(_stateProvider, tx1, block.Header, txTracer); blockTracer.EndTxTrace(); } @@ -185,7 +185,7 @@ public void Should_stop_when_cancellation(bool withCancellation) try { var txTracer = blockTracer.StartNewTxTrace(tx2); - _transactionProcessor.Execute(tx2, block.Header, txTracer); + _transactionProcessor.Execute(_stateProvider, tx2, block.Header, txTracer); blockTracer.EndTxTrace(); blockTracer.EndBlockTrace(); } @@ -237,7 +237,7 @@ private void ExecuteAndTrace(Block block, IBlockTracer otherTracer) foreach (Transaction tx in block.Transactions) { var txTracer = tracer.StartNewTxTrace(tx); - _transactionProcessor.Execute(tx, block.Header, txTracer); + _transactionProcessor.Execute(_stateProvider, tx, block.Header, txTracer); tracer.EndTxTrace(); } tracer.EndBlockTrace(); diff --git a/src/Nethermind/Nethermind.Evm.Test/TransactionProcessorTests.cs b/src/Nethermind/Nethermind.Evm.Test/TransactionProcessorTests.cs index 59b07b4e72a..48774aea189 100644 --- a/src/Nethermind/Nethermind.Evm.Test/TransactionProcessorTests.cs +++ b/src/Nethermind/Nethermind.Evm.Test/TransactionProcessorTests.cs @@ -60,7 +60,7 @@ public void Setup() CodeInfoRepository codeInfoRepository = new(); VirtualMachine virtualMachine = new(new TestBlockhashProvider(_specProvider), _specProvider, codeInfoRepository, LimboLogs.Instance); - _transactionProcessor = new TransactionProcessor(_specProvider, _stateProvider, virtualMachine, codeInfoRepository, LimboLogs.Instance); + _transactionProcessor = new TransactionProcessor(_specProvider, virtualMachine, codeInfoRepository, LimboLogs.Instance); _ethereumEcdsa = new EthereumEcdsa(_specProvider.ChainId); } @@ -246,7 +246,7 @@ public void Balance_is_not_changed_on_call_and_restore() .SignedAndResolved(_ethereumEcdsa, TestItem.PrivateKeyA, _isEip155Enabled).TestObject; Block block = Build.A.Block.WithNumber(1).WithTransactions(tx).WithGasLimit(gasLimit).TestObject; - _transactionProcessor.CallAndRestore(tx, block.Header, NullTxTracer.Instance); + _transactionProcessor.CallAndRestore(_stateProvider, tx, block.Header, NullTxTracer.Instance); _stateProvider.GetBalance(TestItem.PrivateKeyA.Address).Should().Be(1.Ether()); } @@ -264,7 +264,7 @@ public void Account_is_not_created_on_call_and_restore() Block block = Build.A.Block.WithNumber(1).WithTransactions(tx).WithGasLimit(gasLimit).TestObject; _stateProvider.AccountExists(TestItem.PrivateKeyD.Address).Should().BeFalse(); - _transactionProcessor.CallAndRestore(tx, block.Header, NullTxTracer.Instance); + _transactionProcessor.CallAndRestore(_stateProvider, tx, block.Header, NullTxTracer.Instance); _stateProvider.AccountExists(TestItem.PrivateKeyD.Address).Should().BeFalse(); } @@ -275,7 +275,7 @@ public void Nonce_is_not_changed_on_call_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(1).WithTransactions(tx).WithGasLimit(gasLimit).TestObject; - _transactionProcessor.CallAndRestore(tx, block.Header, NullTxTracer.Instance); + _transactionProcessor.CallAndRestore(_stateProvider, tx, block.Header, NullTxTracer.Instance); _stateProvider.GetNonce(TestItem.PrivateKeyA.Address).Should().Be(0); } @@ -289,7 +289,7 @@ public void Can_estimate_with_value(bool systemUser) Block block = Build.A.Block.WithNumber(1).WithTransactions(tx).WithGasLimit(gasLimit).TestObject; EstimateGasTracer tracer = new(); - Action action = () => _transactionProcessor.CallAndRestore(tx, block.Header, tracer); + Action action = () => _transactionProcessor.CallAndRestore(_stateProvider, tx, block.Header, tracer); if (!systemUser) { action.Should().Throw(); @@ -314,9 +314,9 @@ public long Should_not_estimate_tx_with_high_value(UInt256 txValue) EstimateGasTracer tracer = new(); BlocksConfig blocksConfig = new(); - GasEstimator estimator = new(_transactionProcessor, _stateProvider, _specProvider, blocksConfig); + GasEstimator estimator = new(_transactionProcessor, _specProvider, blocksConfig); - return estimator.Estimate(tx, block.Header, tracer, 0); + return estimator.Estimate(_stateProvider, tx, block.Header, tracer, 0); } public static IEnumerable EstimateWithHighTxValueTestCases @@ -366,11 +366,11 @@ public void Can_estimate_simple() EstimateGasTracer tracer = new(); BlocksConfig blocksConfig = new(); - GasEstimator estimator = new(_transactionProcessor, _stateProvider, _specProvider, blocksConfig); - _transactionProcessor.CallAndRestore(tx, block.Header, tracer); + GasEstimator estimator = new(_transactionProcessor, _specProvider, blocksConfig); + _transactionProcessor.CallAndRestore(_stateProvider, tx, block.Header, tracer); tracer.GasSpent.Should().Be(21000); - estimator.Estimate(tx, block.Header, tracer, 0).Should().Be(21000); + estimator.Estimate(_stateProvider, tx, block.Header, tracer, 0).Should().Be(21000); } [TestCase] @@ -394,21 +394,21 @@ public void Can_estimate_with_refund() long intrinsic = IntrinsicGasCalculator.Calculate(tx, MuirGlacier.Instance); GethLikeTxMemoryTracer gethTracer = new(GethTraceOptions.Default); - _transactionProcessor.CallAndRestore(tx, block.Header, gethTracer); + _transactionProcessor.CallAndRestore(_stateProvider, tx, block.Header, gethTracer); TestContext.WriteLine(new EthereumJsonSerializer().Serialize(gethTracer.BuildResult(), true)); EstimateGasTracer tracer = new(); - _transactionProcessor.CallAndRestore(tx, block.Header, tracer); + _transactionProcessor.CallAndRestore(_stateProvider,tx, block.Header, tracer); BlocksConfig blocksConfig = new(); - GasEstimator estimator = new(_transactionProcessor, _stateProvider, _specProvider, blocksConfig); + GasEstimator estimator = new(_transactionProcessor, _specProvider, blocksConfig); long actualIntrinsic = tx.GasLimit - tracer.IntrinsicGasAt; actualIntrinsic.Should().Be(intrinsic); IReleaseSpec releaseSpec = Berlin.Instance; tracer.CalculateAdditionalGasRequired(tx, releaseSpec).Should().Be(RefundOf.SSetReversedEip2200 + GasCostOf.CallStipend - GasCostOf.SStoreNetMeteredEip2200 + 1); tracer.GasSpent.Should().Be(54764L); - long estimate = estimator.Estimate(tx, block.Header, tracer, 0); + long estimate = estimator.Estimate(_stateProvider, tx, block.Header, tracer, 0); estimate.Should().Be(75465L); ConfirmEnoughEstimate(tx, block, estimate); @@ -434,22 +434,22 @@ public void Can_estimate_with_destroy_refund_and_below_intrinsic_pre_berlin() IReleaseSpec releaseSpec = MuirGlacier.Instance; long intrinsic = IntrinsicGasCalculator.Calculate(tx, releaseSpec); - _transactionProcessor.Execute(initTx, block.Header, NullTxTracer.Instance); + _transactionProcessor.Execute(_stateProvider, initTx, block.Header, NullTxTracer.Instance); EstimateGasTracer tracer = new(); GethLikeTxMemoryTracer gethTracer = new(GethTraceOptions.Default); - _transactionProcessor.CallAndRestore(tx, block.Header, tracer); - _transactionProcessor.CallAndRestore(tx, block.Header, gethTracer); + _transactionProcessor.CallAndRestore(_stateProvider,tx, block.Header, tracer); + _transactionProcessor.CallAndRestore(_stateProvider,tx, block.Header, gethTracer); TestContext.WriteLine(new EthereumJsonSerializer().Serialize(gethTracer.BuildResult(), true)); BlocksConfig blocksConfig = new(); - GasEstimator estimator = new(_transactionProcessor, _stateProvider, _specProvider, blocksConfig); + GasEstimator estimator = new(_transactionProcessor, _specProvider, blocksConfig); long actualIntrinsic = tx.GasLimit - tracer.IntrinsicGasAt; actualIntrinsic.Should().Be(intrinsic); tracer.CalculateAdditionalGasRequired(tx, releaseSpec).Should().Be(24080); tracer.GasSpent.Should().Be(35228L); - long estimate = estimator.Estimate(tx, block.Header, tracer, 0); + long estimate = estimator.Estimate(_stateProvider, tx, block.Header, tracer, 0); estimate.Should().Be(59307); ConfirmEnoughEstimate(tx, block, estimate); @@ -462,10 +462,10 @@ private void ConfirmEnoughEstimate(Transaction tx, Block block, long estimate) TestContext.WriteLine(tx.GasLimit); GethLikeTxMemoryTracer gethTracer = new(GethTraceOptions.Default); - _transactionProcessor.CallAndRestore(tx, block.Header, gethTracer); + _transactionProcessor.CallAndRestore(_stateProvider,tx, block.Header, gethTracer); string traceEnoughGas = new EthereumJsonSerializer().Serialize(gethTracer.BuildResult(), true); - _transactionProcessor.CallAndRestore(tx, block.Header, outputTracer); + _transactionProcessor.CallAndRestore(_stateProvider, tx, block.Header, outputTracer); traceEnoughGas.Should().NotContain("OutOfGas"); outputTracer = new CallOutputTracer(); @@ -473,12 +473,12 @@ private void ConfirmEnoughEstimate(Transaction tx, Block block, long estimate) TestContext.WriteLine(tx.GasLimit); gethTracer = new GethLikeTxMemoryTracer(GethTraceOptions.Default); - _transactionProcessor.CallAndRestore(tx, block.Header, gethTracer); + _transactionProcessor.CallAndRestore(_stateProvider, tx, block.Header, gethTracer); string traceOutOfGas = new EthereumJsonSerializer().Serialize(gethTracer.BuildResult(), true); TestContext.WriteLine(traceOutOfGas); - _transactionProcessor.CallAndRestore(tx, block.Header, outputTracer); + _transactionProcessor.CallAndRestore(_stateProvider, tx, block.Header, outputTracer); bool failed = traceEnoughGas.Contains("failed") || traceEnoughGas.Contains("OutOfGas"); failed.Should().BeTrue(); @@ -501,20 +501,20 @@ public void Can_estimate_with_stipend() long intrinsic = IntrinsicGasCalculator.Calculate(tx, releaseSpec); GethLikeTxMemoryTracer gethTracer = new(GethTraceOptions.Default); - _transactionProcessor.CallAndRestore(tx, block.Header, gethTracer); + _transactionProcessor.CallAndRestore(_stateProvider, tx, block.Header, gethTracer); TestContext.WriteLine(new EthereumJsonSerializer().Serialize(gethTracer.BuildResult(), true)); EstimateGasTracer tracer = new(); - _transactionProcessor.CallAndRestore(tx, block.Header, tracer); + _transactionProcessor.CallAndRestore(_stateProvider, tx, block.Header, tracer); BlocksConfig blocksConfig = new(); - GasEstimator estimator = new(_transactionProcessor, _stateProvider, _specProvider, blocksConfig); + GasEstimator estimator = new(_transactionProcessor, _specProvider, blocksConfig); long actualIntrinsic = tx.GasLimit - tracer.IntrinsicGasAt; actualIntrinsic.Should().Be(intrinsic); tracer.CalculateAdditionalGasRequired(tx, releaseSpec).Should().Be(2300); tracer.GasSpent.Should().Be(85669L); - long estimate = estimator.Estimate(tx, block.Header, tracer, 0); + long estimate = estimator.Estimate(_stateProvider, tx, block.Header, tracer, 0); estimate.Should().Be(87969L); ConfirmEnoughEstimate(tx, block, estimate); @@ -543,20 +543,20 @@ public void Can_estimate_with_stipend_and_refund() long intrinsic = IntrinsicGasCalculator.Calculate(tx, releaseSpec); GethLikeTxMemoryTracer gethTracer = new(GethTraceOptions.Default); - _transactionProcessor.CallAndRestore(tx, block.Header, gethTracer); + _transactionProcessor.CallAndRestore(_stateProvider, tx, block.Header, gethTracer); TestContext.WriteLine(new EthereumJsonSerializer().Serialize(gethTracer.BuildResult(), true)); EstimateGasTracer tracer = new(); - _transactionProcessor.CallAndRestore(tx, block.Header, tracer); + _transactionProcessor.CallAndRestore(_stateProvider, tx, block.Header, tracer); BlocksConfig blocksConfig = new(); - GasEstimator estimator = new(_transactionProcessor, _stateProvider, _specProvider, blocksConfig); + GasEstimator estimator = new(_transactionProcessor, _specProvider, blocksConfig); long actualIntrinsic = tx.GasLimit - tracer.IntrinsicGasAt; actualIntrinsic.Should().Be(intrinsic); tracer.CalculateAdditionalGasRequired(tx, releaseSpec).Should().Be(RefundOf.SSetReversedEip2200 + GasCostOf.CallStipend); tracer.GasSpent.Should().Be(87429L); - long estimate = estimator.Estimate(tx, block.Header, tracer, 0); + long estimate = estimator.Estimate(_stateProvider, tx, block.Header, tracer, 0); estimate.Should().Be(108130L); ConfirmEnoughEstimate(tx, block, estimate); @@ -582,19 +582,19 @@ public void Can_estimate_with_single_call() IReleaseSpec releaseSpec = Berlin.Instance; long intrinsic = IntrinsicGasCalculator.Calculate(tx, releaseSpec); - _transactionProcessor.Execute(initTx, block.Header, NullTxTracer.Instance); + _transactionProcessor.Execute(_stateProvider, initTx, block.Header, NullTxTracer.Instance); EstimateGasTracer tracer = new(); - _transactionProcessor.CallAndRestore(tx, block.Header, tracer); + _transactionProcessor.CallAndRestore(_stateProvider, tx, block.Header, tracer); BlocksConfig blocksConfig = new(); - GasEstimator estimator = new(_transactionProcessor, _stateProvider, _specProvider, blocksConfig); + GasEstimator estimator = new(_transactionProcessor, _specProvider, blocksConfig); long actualIntrinsic = tx.GasLimit - tracer.IntrinsicGasAt; actualIntrinsic.Should().Be(intrinsic); tracer.CalculateAdditionalGasRequired(tx, releaseSpec).Should().Be(1); tracer.GasSpent.Should().Be(54224L); - long estimate = estimator.Estimate(tx, block.Header, tracer, 0); + long estimate = estimator.Estimate(_stateProvider, tx, block.Header, tracer, 0); estimate.Should().Be(54224L); ConfirmEnoughEstimate(tx, block, estimate); @@ -627,7 +627,7 @@ public void Balance_is_changed_on_buildup_and_restored() Block block = Build.A.Block.WithNumber(MainnetSpecProvider.ByzantiumBlockNumber).WithTransactions(tx).WithGasLimit(gasLimit).TestObject; Snapshot state = _stateProvider.TakeSnapshot(); - _transactionProcessor.BuildUp(tx, block.Header, NullTxTracer.Instance); + _transactionProcessor.BuildUp(_stateProvider, tx, block.Header, NullTxTracer.Instance); _stateProvider.GetBalance(TestItem.PrivateKeyA.Address).Should().Be(AccountBalance - GasCostOf.Transaction); _stateProvider.Restore(state); @@ -648,7 +648,7 @@ public void Account_is_not_created_on_buildup_and_restore() _stateProvider.AccountExists(TestItem.PrivateKeyD.Address).Should().BeFalse(); Snapshot state = _stateProvider.TakeSnapshot(); - _transactionProcessor.BuildUp(tx, block.Header, NullTxTracer.Instance); + _transactionProcessor.BuildUp(_stateProvider, tx, block.Header, NullTxTracer.Instance); _stateProvider.AccountExists(TestItem.PrivateKeyD.Address).Should().BeTrue(); _stateProvider.Restore(state); _stateProvider.AccountExists(TestItem.PrivateKeyD.Address).Should().BeFalse(); @@ -667,7 +667,7 @@ public void Nonce_is_not_changed_on_buildup_and_restore() Block block = Build.A.Block.WithNumber(MainnetSpecProvider.ByzantiumBlockNumber).WithTransactions(tx).WithGasLimit(gasLimit).TestObject; Snapshot state = _stateProvider.TakeSnapshot(); - _transactionProcessor.BuildUp(tx, block.Header, NullTxTracer.Instance); + _transactionProcessor.BuildUp(_stateProvider, tx, block.Header, NullTxTracer.Instance); _stateProvider.GetNonce(TestItem.PrivateKeyA.Address).Should().Be(1); _stateProvider.Restore(state); _stateProvider.GetNonce(TestItem.PrivateKeyA.Address).Should().Be(0); @@ -688,10 +688,10 @@ public void State_changed_twice_in_buildup_should_have_correct_gas_cost() Block block = Build.A.Block.WithNumber(MainnetSpecProvider.ByzantiumBlockNumber).WithTransactions(tx1, tx2).WithGasLimit(gasLimit).TestObject; Snapshot state = _stateProvider.TakeSnapshot(); - _transactionProcessor.BuildUp(tx1, block.Header, NullTxTracer.Instance); + _transactionProcessor.BuildUp(_stateProvider, tx1, block.Header, NullTxTracer.Instance); _stateProvider.GetBalance(TestItem.PrivateKeyA.Address).Should().Be(AccountBalance - GasCostOf.Transaction); - _transactionProcessor.BuildUp(tx2, block.Header, NullTxTracer.Instance); + _transactionProcessor.BuildUp(_stateProvider, tx2, block.Header, NullTxTracer.Instance); _stateProvider.GetBalance(TestItem.PrivateKeyA.Address).Should().Be(AccountBalance - GasCostOf.Transaction * 2); _stateProvider.Restore(state); @@ -721,7 +721,7 @@ private TransactionResult Execute(Transaction tx, Block block, BlockReceiptsTrac { tracer?.StartNewBlockTrace(block); tracer?.StartNewTxTrace(tx); - TransactionResult result = _transactionProcessor.Execute(tx, block.Header, tracer ?? NullTxTracer.Instance); + TransactionResult result = _transactionProcessor.Execute(_stateProvider, tx, block.Header, tracer ?? NullTxTracer.Instance); if (result) { tracer?.EndTxTrace(); @@ -735,7 +735,7 @@ private TransactionResult CallAndRestore(Transaction tx, Block block, BlockRecei { tracer?.StartNewBlockTrace(block); tracer?.StartNewTxTrace(tx); - TransactionResult result = _transactionProcessor.CallAndRestore(tx, block.Header, tracer ?? NullTxTracer.Instance); + TransactionResult result = _transactionProcessor.CallAndRestore(_stateProvider, tx, block.Header, tracer ?? NullTxTracer.Instance); if (result) { tracer?.EndTxTrace(); diff --git a/src/Nethermind/Nethermind.Evm.Test/TransactionProcessorTraceTest.cs b/src/Nethermind/Nethermind.Evm.Test/TransactionProcessorTraceTest.cs index 637a39ca3b9..d62cd4918a3 100644 --- a/src/Nethermind/Nethermind.Evm.Test/TransactionProcessorTraceTest.cs +++ b/src/Nethermind/Nethermind.Evm.Test/TransactionProcessorTraceTest.cs @@ -21,7 +21,7 @@ public void Trace_should_not_charge_gas(long gasLimit) { (Block block, Transaction transaction) = PrepareTx(BlockNumber, gasLimit); ParityLikeTxTracer tracer = new(block, transaction, ParityTraceTypes.All); - _processor.Trace(transaction, block.Header, tracer); + _processor.Trace(TestState, transaction, block.Header, tracer); var senderBalance = tracer.BuildResult().StateChanges[TestItem.AddressA].Balance; (senderBalance.Before - senderBalance.After).Should().Be(transaction.Value); } diff --git a/src/Nethermind/Nethermind.Evm.Test/VirtualMachineTestsBase.cs b/src/Nethermind/Nethermind.Evm.Test/VirtualMachineTestsBase.cs index c0985fdc74e..90a07c06a69 100644 --- a/src/Nethermind/Nethermind.Evm.Test/VirtualMachineTestsBase.cs +++ b/src/Nethermind/Nethermind.Evm.Test/VirtualMachineTestsBase.cs @@ -70,7 +70,7 @@ public virtual void Setup() IBlockhashProvider blockhashProvider = new TestBlockhashProvider(SpecProvider); CodeInfoRepository = new CodeInfoRepository(); Machine = new VirtualMachine(blockhashProvider, SpecProvider, CodeInfoRepository, logManager); - _processor = new TransactionProcessor(SpecProvider, TestState, Machine, CodeInfoRepository, logManager); + _processor = new TransactionProcessor(SpecProvider, Machine, CodeInfoRepository, logManager); } [TearDown] @@ -80,7 +80,7 @@ protected GethLikeTxTrace ExecuteAndTrace(params byte[] code) { GethLikeTxMemoryTracer tracer = new(GethTraceOptions.Default with { EnableMemory = true }); (Block block, Transaction transaction) = PrepareTx(Activation, 100000, code); - _processor.Execute(transaction, block.Header, tracer); + _processor.Execute(TestState, transaction, block.Header, tracer); return tracer.BuildResult(); } @@ -88,7 +88,7 @@ protected GethLikeTxTrace ExecuteAndTrace(long blockNumber, long gasLimit, param { GethLikeTxMemoryTracer tracer = new(GethTraceOptions.Default); (Block block, Transaction transaction) = PrepareTx((blockNumber, Timestamp), gasLimit, code); - _processor.Execute(transaction, block.Header, tracer); + _processor.Execute(TestState, transaction, block.Header, tracer); return tracer.BuildResult(); } @@ -96,7 +96,7 @@ protected GethLikeTxTrace ExecuteAndTraceToFile(Action dum { GethLikeTxFileTracer tracer = new(dumpCallback, options); (Block block, Transaction transaction) = PrepareTx(Activation, 100000, code); - _processor.Execute(transaction, block.Header, tracer); + _processor.Execute(TestState, transaction, block.Header, tracer); return tracer.BuildResult(); } @@ -112,7 +112,7 @@ protected TestAllTracerWithOutput Execute(ForkActivation activation, params byte { (Block block, Transaction transaction) = PrepareTx(activation, 100000, code); TestAllTracerWithOutput tracer = CreateTracer(); - _processor.Execute(transaction, block.Header, tracer); + _processor.Execute(TestState, transaction, block.Header, tracer); return tracer; } @@ -129,7 +129,7 @@ protected T ExecuteBlock(T tracer, byte[] code, ForkActivation? forkActivatio (Block block, Transaction transaction) = PrepareTx(forkActivation ?? Activation, 100000, code); tracer.StartNewBlockTrace(block); ITxTracer txTracer = tracer.StartNewTxTrace(transaction); - _processor.Execute(transaction, block.Header, txTracer); + _processor.Execute(TestState, transaction, block.Header, txTracer); tracer.EndTxTrace(); tracer.EndBlockTrace(); return tracer; @@ -138,7 +138,7 @@ protected T ExecuteBlock(T tracer, byte[] code, ForkActivation? forkActivatio protected T Execute(T tracer, byte[] code, ForkActivation? forkActivation = null) where T : ITxTracer { (Block block, Transaction transaction) = PrepareTx(forkActivation ?? Activation, 100000, code); - _processor.Execute(transaction, block.Header, tracer); + _processor.Execute(TestState, transaction, block.Header, tracer); return tracer; } @@ -151,7 +151,7 @@ protected TestAllTracerWithOutput Execute(long blockNumber, long gasLimit, byte[ (Block block, Transaction transaction) = PrepareTx((blockNumber, Timestamp), gasLimit, code, blockGasLimit: blockGasLimit, blobVersionedHashes: blobVersionedHashes); TestAllTracerWithOutput tracer = CreateTracer(); - _processor.Execute(transaction, block.Header, tracer); + _processor.Execute(TestState, transaction, block.Header, tracer); return tracer; } @@ -161,7 +161,7 @@ protected TestAllTracerWithOutput Execute(ForkActivation activation, long gasLim (Block block, Transaction transaction) = PrepareTx(activation, gasLimit, code, blockGasLimit: blockGasLimit, blobVersionedHashes: blobVersionedHashes); TestAllTracerWithOutput tracer = CreateTracer(); - _processor.Execute(transaction, block.Header, tracer); + _processor.Execute(TestState, transaction, block.Header, tracer); return tracer; } diff --git a/src/Nethermind/Nethermind.Evm/Tracing/GasEstimator.cs b/src/Nethermind/Nethermind.Evm/Tracing/GasEstimator.cs index a673ef8b657..723473fc6df 100644 --- a/src/Nethermind/Nethermind.Evm/Tracing/GasEstimator.cs +++ b/src/Nethermind/Nethermind.Evm/Tracing/GasEstimator.cs @@ -21,20 +21,17 @@ public class GasEstimator public const int DefaultErrorMargin = 150; private readonly ITransactionProcessor _transactionProcessor; - private readonly IReadOnlyStateProvider _stateProvider; private readonly ISpecProvider _specProvider; private readonly IBlocksConfig _blocksConfig; - public GasEstimator(ITransactionProcessor transactionProcessor, IReadOnlyStateProvider stateProvider, - ISpecProvider specProvider, IBlocksConfig blocksConfig) + public GasEstimator(ITransactionProcessor transactionProcessor, ISpecProvider specProvider, IBlocksConfig blocksConfig) { _transactionProcessor = transactionProcessor; - _stateProvider = stateProvider; _specProvider = specProvider; _blocksConfig = blocksConfig; } - public long Estimate(Transaction tx, BlockHeader header, EstimateGasTracer gasTracer, int errorMargin = DefaultErrorMargin, CancellationToken token = new()) + public long Estimate(IWorldState worldState, Transaction tx, BlockHeader header, EstimateGasTracer gasTracer, int errorMargin = DefaultErrorMargin, CancellationToken token = new()) { ArgumentOutOfRangeException.ThrowIfNegative(errorMargin, nameof(errorMargin)); ArgumentOutOfRangeException.ThrowIfGreaterThanOrEqual(errorMargin, 10000, nameof(errorMargin)); @@ -44,7 +41,7 @@ public GasEstimator(ITransactionProcessor transactionProcessor, IReadOnlyStatePr tx.GasLimit = Math.Min(tx.GasLimit, header.GasLimit); // Limit Gas to the header // Calculate and return additional gas required in case of insufficient funds. - UInt256 senderBalance = _stateProvider.GetBalance(tx.SenderAddress); + UInt256 senderBalance = worldState.GetBalance(tx.SenderAddress); if (tx.Value != UInt256.Zero && tx.Value > senderBalance && !tx.IsSystem()) { return gasTracer.CalculateAdditionalGasRequired(tx, releaseSpec); @@ -65,17 +62,17 @@ public GasEstimator(ITransactionProcessor transactionProcessor, IReadOnlyStatePr return 0; // Execute binary search to find the optimal gas estimation. - return BinarySearchEstimate(leftBound, rightBound, tx, header, gasTracer, errorMargin, token); + return BinarySearchEstimate(worldState, leftBound, rightBound, tx, header, gasTracer, errorMargin, token); } - private long BinarySearchEstimate(long leftBound, long rightBound, Transaction tx, BlockHeader header, EstimateGasTracer gasTracer, int errorMargin, CancellationToken token) + private long BinarySearchEstimate(IWorldState worldState, long leftBound, long rightBound, Transaction tx, BlockHeader header, EstimateGasTracer gasTracer, int errorMargin, CancellationToken token) { double marginWithDecimals = errorMargin == 0 ? 1 : errorMargin / 10000d + 1; //This approach is similar to Geth, by starting from an optimistic guess the number of iterations is greatly reduced in most cases long optimisticGasEstimate = (long)((gasTracer.GasSpent + gasTracer.TotalRefund + GasCostOf.CallStipend) * marginWithDecimals); if (optimisticGasEstimate > leftBound && optimisticGasEstimate < rightBound) { - if (TryExecutableTransaction(tx, header, optimisticGasEstimate, token)) + if (TryExecutableTransaction(worldState, tx, header, optimisticGasEstimate, token)) rightBound = optimisticGasEstimate; else leftBound = optimisticGasEstimate; @@ -87,7 +84,7 @@ private long BinarySearchEstimate(long leftBound, long rightBound, Transaction t && leftBound + 1 < rightBound) { long mid = (leftBound + rightBound) / 2; - if (!TryExecutableTransaction(tx, header, mid, token)) + if (!TryExecutableTransaction(worldState, tx, header, mid, token)) { leftBound = mid; } @@ -97,7 +94,7 @@ private long BinarySearchEstimate(long leftBound, long rightBound, Transaction t } } - if (rightBound == cap && !TryExecutableTransaction(tx, header, rightBound, token)) + if (rightBound == cap && !TryExecutableTransaction(worldState, tx, header, rightBound, token)) { return 0; } @@ -105,7 +102,7 @@ private long BinarySearchEstimate(long leftBound, long rightBound, Transaction t return rightBound; } - private bool TryExecutableTransaction(Transaction transaction, BlockHeader block, long gasLimit, CancellationToken token) + private bool TryExecutableTransaction(IWorldState worldState, Transaction transaction, BlockHeader block, long gasLimit, CancellationToken token) { OutOfGasTracer tracer = new(); @@ -115,7 +112,7 @@ private bool TryExecutableTransaction(Transaction transaction, BlockHeader block transaction.GasLimit = gasLimit; BlockExecutionContext blCtx = new(block); - _transactionProcessor.CallAndRestore(transaction, in blCtx, tracer.WithCancellation(token)); + _transactionProcessor.CallAndRestore(worldState, transaction, in blCtx, tracer.WithCancellation(token)); transaction.GasLimit = originalGasLimit; return !tracer.OutOfGas; diff --git a/src/Nethermind/Nethermind.Evm/TransactionProcessing/BuildUpTransactionProcessorAdapter.cs b/src/Nethermind/Nethermind.Evm/TransactionProcessing/BuildUpTransactionProcessorAdapter.cs index 2ac0a3b8fcb..42d02e32a36 100644 --- a/src/Nethermind/Nethermind.Evm/TransactionProcessing/BuildUpTransactionProcessorAdapter.cs +++ b/src/Nethermind/Nethermind.Evm/TransactionProcessing/BuildUpTransactionProcessorAdapter.cs @@ -3,12 +3,13 @@ using Nethermind.Core; using Nethermind.Evm.Tracing; +using Nethermind.State; namespace Nethermind.Evm.TransactionProcessing { public class BuildUpTransactionProcessorAdapter(ITransactionProcessor transactionProcessor) : ITransactionProcessorAdapter { - public TransactionResult Execute(Transaction transaction, in BlockExecutionContext blkCtx, ITxTracer txTracer) => - transactionProcessor.BuildUp(transaction, in blkCtx, txTracer); + public TransactionResult Execute(IWorldState worldState, Transaction transaction, in BlockExecutionContext blkCtx, ITxTracer txTracer) => + transactionProcessor.BuildUp(worldState, transaction, in blkCtx, txTracer); } } diff --git a/src/Nethermind/Nethermind.Evm/TransactionProcessing/CallAndRestoreTransactionProcessorAdapter.cs b/src/Nethermind/Nethermind.Evm/TransactionProcessing/CallAndRestoreTransactionProcessorAdapter.cs index 31232e3b7c6..f01b983cf65 100644 --- a/src/Nethermind/Nethermind.Evm/TransactionProcessing/CallAndRestoreTransactionProcessorAdapter.cs +++ b/src/Nethermind/Nethermind.Evm/TransactionProcessing/CallAndRestoreTransactionProcessorAdapter.cs @@ -3,6 +3,7 @@ // using Nethermind.Core; using Nethermind.Evm.Tracing; +using Nethermind.State; namespace Nethermind.Evm.TransactionProcessing { @@ -15,7 +16,7 @@ public CallAndRestoreTransactionProcessorAdapter(ITransactionProcessor transacti _transactionProcessor = transactionProcessor; } - public TransactionResult Execute(Transaction transaction, in BlockExecutionContext blkCtx, ITxTracer txTracer) => - _transactionProcessor.CallAndRestore(transaction, in blkCtx, txTracer); + public TransactionResult Execute(IWorldState worldState, Transaction transaction, in BlockExecutionContext blkCtx, ITxTracer txTracer) => + _transactionProcessor.CallAndRestore(worldState, transaction, in blkCtx, txTracer); } } diff --git a/src/Nethermind/Nethermind.Evm/TransactionProcessing/ChangeableTransactionProcessorAdapter.cs b/src/Nethermind/Nethermind.Evm/TransactionProcessing/ChangeableTransactionProcessorAdapter.cs index 38d9ccf67c9..522c6be4757 100644 --- a/src/Nethermind/Nethermind.Evm/TransactionProcessing/ChangeableTransactionProcessorAdapter.cs +++ b/src/Nethermind/Nethermind.Evm/TransactionProcessing/ChangeableTransactionProcessorAdapter.cs @@ -3,6 +3,7 @@ using Nethermind.Core; using Nethermind.Evm.Tracing; +using Nethermind.State; namespace Nethermind.Evm.TransactionProcessing { @@ -22,7 +23,7 @@ public ChangeableTransactionProcessorAdapter(ITransactionProcessor transactionPr TransactionProcessor = transactionProcessor; } - public TransactionResult Execute(Transaction transaction, in BlockExecutionContext blkCtx, ITxTracer txTracer) => - CurrentAdapter.Execute(transaction, in blkCtx, txTracer); + public TransactionResult Execute(IWorldState worldState, Transaction transaction, in BlockExecutionContext blkCtx, ITxTracer txTracer) => + CurrentAdapter.Execute(worldState, transaction, in blkCtx, txTracer); } } diff --git a/src/Nethermind/Nethermind.Evm/TransactionProcessing/ExecuteTransactionProcessorAdapter.cs b/src/Nethermind/Nethermind.Evm/TransactionProcessing/ExecuteTransactionProcessorAdapter.cs index 729db62505e..ba5ebb49ebf 100644 --- a/src/Nethermind/Nethermind.Evm/TransactionProcessing/ExecuteTransactionProcessorAdapter.cs +++ b/src/Nethermind/Nethermind.Evm/TransactionProcessing/ExecuteTransactionProcessorAdapter.cs @@ -3,6 +3,7 @@ using Nethermind.Core; using Nethermind.Evm.Tracing; +using Nethermind.State; namespace Nethermind.Evm.TransactionProcessing { @@ -15,7 +16,7 @@ public ExecuteTransactionProcessorAdapter(ITransactionProcessor transactionProce _transactionProcessor = transactionProcessor; } - public TransactionResult Execute(Transaction transaction, in BlockExecutionContext blkCtx, ITxTracer txTracer) => - _transactionProcessor.Execute(transaction, in blkCtx, txTracer); + public TransactionResult Execute(IWorldState worldState, Transaction transaction, in BlockExecutionContext blkCtx, ITxTracer txTracer) => + _transactionProcessor.Execute(worldState, transaction, in blkCtx, txTracer); } } diff --git a/src/Nethermind/Nethermind.Evm/TransactionProcessing/ITransactionProcessor.cs b/src/Nethermind/Nethermind.Evm/TransactionProcessing/ITransactionProcessor.cs index 96ac8e27948..9cca01b8d5a 100644 --- a/src/Nethermind/Nethermind.Evm/TransactionProcessing/ITransactionProcessor.cs +++ b/src/Nethermind/Nethermind.Evm/TransactionProcessing/ITransactionProcessor.cs @@ -3,6 +3,7 @@ using Nethermind.Core; using Nethermind.Evm.Tracing; +using Nethermind.State; namespace Nethermind.Evm.TransactionProcessing; @@ -11,21 +12,21 @@ public interface ITransactionProcessor /// /// Execute transaction, commit state /// - TransactionResult Execute(Transaction transaction, in BlockExecutionContext blCtx, ITxTracer txTracer); + TransactionResult Execute(IWorldState worldState, Transaction transaction, in BlockExecutionContext blCtx, ITxTracer txTracer); /// /// Call transaction, rollback state /// - TransactionResult CallAndRestore(Transaction transaction, in BlockExecutionContext blCtx, ITxTracer txTracer); + TransactionResult CallAndRestore(IWorldState worldState, Transaction transaction, in BlockExecutionContext blCtx, ITxTracer txTracer); /// /// Execute transaction, keep the state uncommitted /// - TransactionResult BuildUp(Transaction transaction, in BlockExecutionContext blCtx, ITxTracer txTracer); + TransactionResult BuildUp(IWorldState worldState, Transaction transaction, in BlockExecutionContext blCtx, ITxTracer txTracer); /// /// Call transaction, no validations, commit state /// Will NOT charge gas from sender account, so stateDiff will miss gas fee /// - TransactionResult Trace(Transaction transaction, in BlockExecutionContext blCtx, ITxTracer txTracer); + TransactionResult Trace(IWorldState worldState, Transaction transaction, in BlockExecutionContext blCtx, ITxTracer txTracer); } diff --git a/src/Nethermind/Nethermind.Evm/TransactionProcessing/ITransactionProcessorAdapter.cs b/src/Nethermind/Nethermind.Evm/TransactionProcessing/ITransactionProcessorAdapter.cs index ba77066d81a..6a15e30e91a 100644 --- a/src/Nethermind/Nethermind.Evm/TransactionProcessing/ITransactionProcessorAdapter.cs +++ b/src/Nethermind/Nethermind.Evm/TransactionProcessing/ITransactionProcessorAdapter.cs @@ -3,11 +3,12 @@ using Nethermind.Core; using Nethermind.Evm.Tracing; +using Nethermind.State; namespace Nethermind.Evm.TransactionProcessing { public interface ITransactionProcessorAdapter { - TransactionResult Execute(Transaction transaction, in BlockExecutionContext blkCtx, ITxTracer txTracer); + TransactionResult Execute(IWorldState worldState, Transaction transaction, in BlockExecutionContext blkCtx, ITxTracer txTracer); } } diff --git a/src/Nethermind/Nethermind.Evm/TransactionProcessing/TraceTransactionProcessorAdapter.cs b/src/Nethermind/Nethermind.Evm/TransactionProcessing/TraceTransactionProcessorAdapter.cs index f272308db25..97a6176e771 100644 --- a/src/Nethermind/Nethermind.Evm/TransactionProcessing/TraceTransactionProcessorAdapter.cs +++ b/src/Nethermind/Nethermind.Evm/TransactionProcessing/TraceTransactionProcessorAdapter.cs @@ -3,6 +3,7 @@ using Nethermind.Core; using Nethermind.Evm.Tracing; +using Nethermind.State; namespace Nethermind.Evm.TransactionProcessing { @@ -15,7 +16,7 @@ public TraceTransactionProcessorAdapter(ITransactionProcessor transactionProcess _transactionProcessor = transactionProcessor; } - public TransactionResult Execute(Transaction transaction, in BlockExecutionContext blkCtx, ITxTracer txTracer) => - _transactionProcessor.Trace(transaction, in blkCtx, txTracer); + public TransactionResult Execute(IWorldState worldState, Transaction transaction, in BlockExecutionContext blkCtx, ITxTracer txTracer) => + _transactionProcessor.Trace(worldState, transaction, in blkCtx, txTracer); } } diff --git a/src/Nethermind/Nethermind.Evm/TransactionProcessing/TransactionProcessor.cs b/src/Nethermind/Nethermind.Evm/TransactionProcessing/TransactionProcessor.cs index f01be3bfdeb..f26b6feab20 100644 --- a/src/Nethermind/Nethermind.Evm/TransactionProcessing/TransactionProcessor.cs +++ b/src/Nethermind/Nethermind.Evm/TransactionProcessing/TransactionProcessor.cs @@ -29,7 +29,6 @@ public class TransactionProcessor : ITransactionProcessor protected EthereumEcdsa Ecdsa { get; private init; } protected ILogger Logger { get; private init; } protected ISpecProvider SpecProvider { get; private init; } - protected IWorldState WorldState { get; private init; } protected IVirtualMachine VirtualMachine { get; private init; } private readonly ICodeInfoRepository _codeInfoRepository; @@ -64,44 +63,41 @@ protected enum ExecutionOptions public TransactionProcessor( ISpecProvider? specProvider, - IWorldState? worldState, IVirtualMachine? virtualMachine, ICodeInfoRepository? codeInfoRepository, ILogManager? logManager) { ArgumentNullException.ThrowIfNull(logManager, nameof(logManager)); ArgumentNullException.ThrowIfNull(specProvider, nameof(specProvider)); - ArgumentNullException.ThrowIfNull(worldState, nameof(worldState)); ArgumentNullException.ThrowIfNull(virtualMachine, nameof(virtualMachine)); ArgumentNullException.ThrowIfNull(codeInfoRepository, nameof(codeInfoRepository)); Logger = logManager.GetClassLogger(); SpecProvider = specProvider; - WorldState = worldState; VirtualMachine = virtualMachine; _codeInfoRepository = codeInfoRepository; Ecdsa = new EthereumEcdsa(specProvider.ChainId); } - public TransactionResult CallAndRestore(Transaction transaction, in BlockExecutionContext blCtx, ITxTracer txTracer) => - Execute(transaction, in blCtx, txTracer, ExecutionOptions.CommitAndRestore); + public TransactionResult CallAndRestore(IWorldState worldState, Transaction transaction, in BlockExecutionContext blCtx, ITxTracer txTracer) => + Execute(worldState, transaction, in blCtx, txTracer, ExecutionOptions.CommitAndRestore); - public TransactionResult BuildUp(Transaction transaction, in BlockExecutionContext blCtx, ITxTracer txTracer) + public TransactionResult BuildUp(IWorldState worldState, Transaction transaction, in BlockExecutionContext blCtx, ITxTracer txTracer) { // we need to treat the result of previous transaction as the original value of next transaction // when we do not commit - WorldState.TakeSnapshot(true); - return Execute(transaction, in blCtx, txTracer, ExecutionOptions.None); + worldState.TakeSnapshot(true); + return Execute(worldState, transaction, in blCtx, txTracer, ExecutionOptions.None); } - public TransactionResult Execute(Transaction transaction, in BlockExecutionContext blCtx, ITxTracer txTracer) => - Execute(transaction, in blCtx, txTracer, ExecutionOptions.Commit); + public TransactionResult Execute(IWorldState worldState, Transaction transaction, in BlockExecutionContext blCtx, ITxTracer txTracer) => + Execute(worldState, transaction, in blCtx, txTracer, ExecutionOptions.Commit); - public TransactionResult Trace(Transaction transaction, in BlockExecutionContext blCtx, ITxTracer txTracer) => - Execute(transaction, in blCtx, txTracer, ExecutionOptions.NoValidation); + public TransactionResult Trace(IWorldState worldState, Transaction transaction, in BlockExecutionContext blCtx, ITxTracer txTracer) => + Execute(worldState, transaction, in blCtx, txTracer, ExecutionOptions.NoValidation); - protected virtual TransactionResult Execute(Transaction tx, in BlockExecutionContext blCtx, ITxTracer tracer, ExecutionOptions opts) + protected virtual TransactionResult Execute(IWorldState worldState, Transaction tx, in BlockExecutionContext blCtx, ITxTracer tracer, ExecutionOptions opts) { BlockHeader header = blCtx.Header; IReleaseSpec spec = SpecProvider.GetSpec(header); @@ -122,41 +118,41 @@ protected virtual TransactionResult Execute(Transaction tx, in BlockExecutionCon UpdateMetrics(opts, effectiveGasPrice); - bool deleteCallerAccount = RecoverSenderIfNeeded(tx, spec, opts, effectiveGasPrice); + bool deleteCallerAccount = RecoverSenderIfNeeded(worldState, tx, spec, opts, effectiveGasPrice); - if (!(result = ValidateSender(tx, header, spec, tracer, opts))) return result; - if (!(result = BuyGas(tx, header, spec, tracer, opts, effectiveGasPrice, out UInt256 premiumPerGas, out UInt256 senderReservedGasPayment))) return result; - if (!(result = IncrementNonce(tx, header, spec, tracer, opts))) return result; + if (!(result = ValidateSender(worldState, tx, header, spec, tracer, opts))) return result; + if (!(result = BuyGas(worldState, tx, header, spec, tracer, opts, effectiveGasPrice, out UInt256 premiumPerGas, out UInt256 senderReservedGasPayment))) return result; + if (!(result = IncrementNonce(worldState, tx, header, spec, tracer, opts))) return result; - if (commit) WorldState.Commit(spec, tracer.IsTracingState ? tracer : NullTxTracer.Instance, commitStorageRoots: false); + if (commit) worldState.Commit(spec, tracer.IsTracingState ? tracer : NullTxTracer.Instance, commitStorageRoots: false); - ExecutionEnvironment env = BuildExecutionEnvironment(tx, in blCtx, spec, effectiveGasPrice); + ExecutionEnvironment env = BuildExecutionEnvironment(worldState, tx, in blCtx, spec, effectiveGasPrice); long gasAvailable = tx.GasLimit - intrinsicGas; - ExecuteEvmCall(tx, header, spec, tracer, opts, gasAvailable, env, out TransactionSubstate? substate, out long spentGas, out byte statusCode); - PayFees(tx, header, spec, tracer, substate, spentGas, premiumPerGas, statusCode); + ExecuteEvmCall(worldState, tx, header, spec, tracer, opts, gasAvailable, env, out TransactionSubstate? substate, out long spentGas, out byte statusCode); + PayFees(worldState, tx, header, spec, tracer, substate, spentGas, premiumPerGas, statusCode); // Finalize if (restore) { - WorldState.Reset(); + worldState.Reset(); if (deleteCallerAccount) { - WorldState.DeleteAccount(tx.SenderAddress); + worldState.DeleteAccount(tx.SenderAddress); } else { if (!opts.HasFlag(ExecutionOptions.NoValidation)) - WorldState.AddToBalance(tx.SenderAddress, senderReservedGasPayment, spec); + worldState.AddToBalance(tx.SenderAddress, senderReservedGasPayment, spec); if (!tx.IsSystem()) - WorldState.DecrementNonce(tx.SenderAddress); + worldState.DecrementNonce(tx.SenderAddress); - WorldState.Commit(spec); + worldState.Commit(spec); } } else if (commit) { - WorldState.Commit(spec, tracer.IsTracingState ? tracer : NullStateTracer.Instance, commitStorageRoots: !spec.IsEip658Enabled); + worldState.Commit(spec, tracer.IsTracingState ? tracer : NullStateTracer.Instance, commitStorageRoots: !spec.IsEip658Enabled); } if (tracer.IsTracingReceipt) @@ -164,8 +160,8 @@ protected virtual TransactionResult Execute(Transaction tx, in BlockExecutionCon Hash256 stateRoot = null; if (!spec.IsEip658Enabled) { - WorldState.RecalculateStateRoot(); - stateRoot = WorldState.StateRoot; + worldState.RecalculateStateRoot(); + stateRoot = worldState.StateRoot; } if (statusCode == StatusCode.Failure) @@ -266,7 +262,7 @@ protected virtual TransactionResult ValidateStatic(Transaction tx, BlockHeader h } // TODO Should we remove this already - protected bool RecoverSenderIfNeeded(Transaction tx, IReleaseSpec spec, ExecutionOptions opts, in UInt256 effectiveGasPrice) + protected bool RecoverSenderIfNeeded(IWorldState worldState, Transaction tx, IReleaseSpec spec, ExecutionOptions opts, in UInt256 effectiveGasPrice) { bool commit = opts.HasFlag(ExecutionOptions.Commit) || !spec.IsEip658Enabled; bool restore = opts.HasFlag(ExecutionOptions.Restore); @@ -275,7 +271,7 @@ protected bool RecoverSenderIfNeeded(Transaction tx, IReleaseSpec spec, Executio bool deleteCallerAccount = false; Address sender = tx.SenderAddress; - if (sender is null || !WorldState.AccountExists(sender)) + if (sender is null || !worldState.AccountExists(sender)) { if (Logger.IsDebug) Logger.Debug($"TX sender account does not exist {sender} - trying to recover it"); @@ -295,7 +291,7 @@ protected bool RecoverSenderIfNeeded(Transaction tx, IReleaseSpec spec, Executio if (!commit || noValidation || effectiveGasPrice.IsZero) { deleteCallerAccount = !commit || restore; - WorldState.CreateAccount(sender, in UInt256.Zero); + worldState.CreateAccount(sender, in UInt256.Zero); } } @@ -309,11 +305,11 @@ protected bool RecoverSenderIfNeeded(Transaction tx, IReleaseSpec spec, Executio } - protected virtual TransactionResult ValidateSender(Transaction tx, BlockHeader header, IReleaseSpec spec, ITxTracer tracer, ExecutionOptions opts) + protected virtual TransactionResult ValidateSender(IWorldState worldState, Transaction tx, BlockHeader header, IReleaseSpec spec, ITxTracer tracer, ExecutionOptions opts) { bool validate = !opts.HasFlag(ExecutionOptions.NoValidation); - if (validate && WorldState.IsInvalidContractSender(spec, tx.SenderAddress)) + if (validate && worldState.IsInvalidContractSender(spec, tx.SenderAddress)) { TraceLogInvalidTx(tx, "SENDER_IS_CONTRACT"); return "sender has deployed code"; @@ -322,7 +318,7 @@ protected virtual TransactionResult ValidateSender(Transaction tx, BlockHeader h return TransactionResult.Ok; } - protected virtual TransactionResult BuyGas(Transaction tx, BlockHeader header, IReleaseSpec spec, ITxTracer tracer, ExecutionOptions opts, + protected virtual TransactionResult BuyGas(IWorldState worldState, Transaction tx, BlockHeader header, IReleaseSpec spec, ITxTracer tracer, ExecutionOptions opts, in UInt256 effectiveGasPrice, out UInt256 premiumPerGas, out UInt256 senderReservedGasPayment) { premiumPerGas = UInt256.Zero; @@ -337,7 +333,7 @@ protected virtual TransactionResult BuyGas(Transaction tx, BlockHeader header, I return "miner premium is negative"; } - UInt256 senderBalance = WorldState.GetBalance(tx.SenderAddress); + UInt256 senderBalance = worldState.GetBalance(tx.SenderAddress); if (UInt256.SubtractUnderflow(senderBalance, tx.Value, out UInt256 balanceLeft)) { TraceLogInvalidTx(tx, $"INSUFFICIENT_SENDER_BALANCE: ({tx.SenderAddress})_BALANCE = {senderBalance}"); @@ -381,39 +377,40 @@ protected virtual TransactionResult BuyGas(Transaction tx, BlockHeader header, I } } - if (validate) WorldState.SubtractFromBalance(tx.SenderAddress, senderReservedGasPayment, spec); + if (validate) worldState.SubtractFromBalance(tx.SenderAddress, senderReservedGasPayment, spec); return TransactionResult.Ok; } - protected virtual TransactionResult IncrementNonce(Transaction tx, BlockHeader header, IReleaseSpec spec, ITxTracer tracer, ExecutionOptions opts) + protected virtual TransactionResult IncrementNonce(IWorldState worldState, Transaction tx, BlockHeader header, IReleaseSpec spec, ITxTracer tracer, ExecutionOptions opts) { if (tx.IsSystem()) return TransactionResult.Ok; - if (tx.Nonce != WorldState.GetNonce(tx.SenderAddress)) + if (tx.Nonce != worldState.GetNonce(tx.SenderAddress)) { - TraceLogInvalidTx(tx, $"WRONG_TRANSACTION_NONCE: {tx.Nonce} (expected {WorldState.GetNonce(tx.SenderAddress)})"); + TraceLogInvalidTx(tx, $"WRONG_TRANSACTION_NONCE: {tx.Nonce} (expected {worldState.GetNonce(tx.SenderAddress)})"); return "wrong transaction nonce"; } - WorldState.IncrementNonce(tx.SenderAddress); + worldState.IncrementNonce(tx.SenderAddress); return TransactionResult.Ok; } protected ExecutionEnvironment BuildExecutionEnvironment( + IWorldState worldState, Transaction tx, in BlockExecutionContext blCtx, IReleaseSpec spec, in UInt256 effectiveGasPrice) { - Address recipient = tx.GetRecipient(tx.IsContractCreation ? WorldState.GetNonce(tx.SenderAddress) : 0); + Address recipient = tx.GetRecipient(tx.IsContractCreation ? worldState.GetNonce(tx.SenderAddress) : 0); if (recipient is null) ThrowInvalidDataException("Recipient has not been resolved properly before tx execution"); TxExecutionContext executionContext = new(in blCtx, tx.SenderAddress, effectiveGasPrice, tx.BlobVersionedHashes); CodeInfo codeInfo = tx.IsContractCreation ? new(tx.Data ?? Memory.Empty) - : _codeInfoRepository.GetCachedCodeInfo(WorldState, recipient, spec); + : _codeInfoRepository.GetCachedCodeInfo(worldState, recipient, spec); codeInfo.AnalyseInBackgroundIfRequired(); @@ -435,6 +432,7 @@ protected ExecutionEnvironment BuildExecutionEnvironment( protected virtual bool ShouldValidate(ExecutionOptions opts) => !opts.HasFlag(ExecutionOptions.NoValidation); protected void ExecuteEvmCall( + IWorldState worldState, Transaction tx, BlockHeader header, IReleaseSpec spec, @@ -454,19 +452,19 @@ protected void ExecuteEvmCall( long unspentGas = gasAvailable; - Snapshot snapshot = WorldState.TakeSnapshot(); + Snapshot snapshot = worldState.TakeSnapshot(); // Fixes eth_estimateGas. // If sender is SystemUser subtracting value will cause InsufficientBalanceException if (validate || !tx.IsSystem()) - WorldState.SubtractFromBalance(tx.SenderAddress, tx.Value, spec); + worldState.SubtractFromBalance(tx.SenderAddress, tx.Value, spec); try { if (tx.IsContractCreation) { // if transaction is a contract creation then recipient address is the contract deployment address - PrepareAccountForContractDeployment(env.ExecutingAccount, spec); + PrepareAccountForContractDeployment(worldState, env.ExecutingAccount, spec); } ExecutionType executionType = tx.IsContractCreation ? ExecutionType.CREATE : ExecutionType.TRANSACTION; @@ -490,8 +488,8 @@ protected void ExecuteEvmCall( } substate = !tracer.IsTracingActions - ? VirtualMachine.Run(state, WorldState, tracer) - : VirtualMachine.Run(state, WorldState, tracer); + ? VirtualMachine.Run(state, worldState, tracer) + : VirtualMachine.Run(state, worldState, tracer); unspentGas = state.GasAvailable; @@ -505,7 +503,7 @@ protected void ExecuteEvmCall( { if (Logger.IsTrace) Logger.Trace("Restoring state from before transaction"); - WorldState.Restore(snapshot); + worldState.Restore(snapshot); } else { @@ -527,7 +525,7 @@ protected void ExecuteEvmCall( if (unspentGas >= codeDepositGasCost) { var code = substate.Output.ToArray(); - _codeInfoRepository.InsertCode(WorldState, code, env.ExecutingAccount, spec); + _codeInfoRepository.InsertCode(worldState, code, env.ExecutingAccount, spec); unspentGas -= codeDepositGasCost; } @@ -538,8 +536,8 @@ protected void ExecuteEvmCall( if (Logger.IsTrace) Logger.Trace($"Destroying account {toBeDestroyed}"); - WorldState.ClearStorage(toBeDestroyed); - WorldState.DeleteAccount(toBeDestroyed); + worldState.ClearStorage(toBeDestroyed); + worldState.DeleteAccount(toBeDestroyed); if (tracer.IsTracingRefunds) tracer.ReportRefund(RefundOf.Destroy(spec.IsEip3529Enabled)); @@ -548,19 +546,19 @@ protected void ExecuteEvmCall( statusCode = StatusCode.Success; } - spentGas = Refund(tx, header, spec, opts, substate, unspentGas, env.TxExecutionContext.GasPrice); + spentGas = Refund(worldState, tx, header, spec, opts, substate, unspentGas, env.TxExecutionContext.GasPrice); } catch (Exception ex) when (ex is EvmException or OverflowException) // TODO: OverflowException? still needed? hope not { if (Logger.IsTrace) Logger.Trace($"EVM EXCEPTION: {ex.GetType().Name}:{ex.Message}"); - WorldState.Restore(snapshot); + worldState.Restore(snapshot); } if (validate && !tx.IsSystem()) header.GasUsed += spentGas; } - protected virtual void PayFees(Transaction tx, BlockHeader header, IReleaseSpec spec, ITxTracer tracer, in TransactionSubstate substate, in long spentGas, in UInt256 premiumPerGas, in byte statusCode) + protected virtual void PayFees(IWorldState worldState, Transaction tx, BlockHeader header, IReleaseSpec spec, ITxTracer tracer, in TransactionSubstate substate, in long spentGas, in UInt256 premiumPerGas, in byte statusCode) { if (!tx.IsSystem()) { @@ -570,10 +568,10 @@ protected virtual void PayFees(Transaction tx, BlockHeader header, IReleaseSpec UInt256 fees = (UInt256)spentGas * premiumPerGas; UInt256 burntFees = !tx.IsFree() ? (UInt256)spentGas * header.BaseFeePerGas : 0; - WorldState.AddToBalanceAndCreateIfNotExists(header.GasBeneficiary, fees, spec); + worldState.AddToBalanceAndCreateIfNotExists(header.GasBeneficiary, fees, spec); if (spec.IsEip1559Enabled && spec.Eip1559FeeCollector is not null && !burntFees.IsZero) - WorldState.AddToBalanceAndCreateIfNotExists(spec.Eip1559FeeCollector, burntFees, spec); + worldState.AddToBalanceAndCreateIfNotExists(spec.Eip1559FeeCollector, burntFees, spec); if (tracer.IsTracingFees) tracer.ReportFees(fees, burntFees); @@ -581,9 +579,9 @@ protected virtual void PayFees(Transaction tx, BlockHeader header, IReleaseSpec } } - protected void PrepareAccountForContractDeployment(Address contractAddress, IReleaseSpec spec) + protected void PrepareAccountForContractDeployment(IWorldState worldState, Address contractAddress, IReleaseSpec spec) { - if (WorldState.AccountExists(contractAddress) && contractAddress.IsNonZeroAccount(spec, _codeInfoRepository, WorldState)) + if (worldState.AccountExists(contractAddress) && contractAddress.IsNonZeroAccount(spec, _codeInfoRepository, worldState)) { if (Logger.IsTrace) Logger.Trace($"Contract collision at {contractAddress}"); @@ -597,7 +595,7 @@ protected void TraceLogInvalidTx(Transaction transaction, string reason) if (Logger.IsTrace) Logger.Trace($"Invalid tx {transaction.Hash} ({reason})"); } - protected virtual long Refund(Transaction tx, BlockHeader header, IReleaseSpec spec, ExecutionOptions opts, + protected virtual long Refund(IWorldState worldState, Transaction tx, BlockHeader header, IReleaseSpec spec, ExecutionOptions opts, in TransactionSubstate substate, in long unspentGas, in UInt256 gasPrice) { long spentGas = tx.GasLimit; @@ -613,7 +611,7 @@ protected virtual long Refund(Transaction tx, BlockHeader header, IReleaseSpec s Logger.Trace("Refunding unused gas of " + unspentGas + " and refund of " + refund); // If noValidation we didn't charge for gas, so do not refund if (!opts.HasFlag(ExecutionOptions.NoValidation)) - WorldState.AddToBalance(tx.SenderAddress, (ulong)(unspentGas + refund) * gasPrice, spec); + worldState.AddToBalance(tx.SenderAddress, (ulong)(unspentGas + refund) * gasPrice, spec); spentGas -= refund; } diff --git a/src/Nethermind/Nethermind.Facade.Test/BlockchainBridgeTests.cs b/src/Nethermind/Nethermind.Facade.Test/BlockchainBridgeTests.cs index 77fa79f865b..e96596b5e3c 100644 --- a/src/Nethermind/Nethermind.Facade.Test/BlockchainBridgeTests.cs +++ b/src/Nethermind/Nethermind.Facade.Test/BlockchainBridgeTests.cs @@ -158,6 +158,7 @@ public void Call_uses_valid_post_merge_and_random_value() _blockchainBridge.Call(header, tx, CancellationToken.None); _transactionProcessor.Received().CallAndRestore( + Arg.Any(), tx, Arg.Is(blkCtx => blkCtx.Header.IsPostMerge && blkCtx.Header.Random == TestItem.KeccakA), @@ -174,6 +175,7 @@ public void Call_uses_valid_block_number() _blockchainBridge.Call(header, tx, CancellationToken.None); _transactionProcessor.Received().CallAndRestore( + Arg.Any(), tx, Arg.Is(blkCtx => blkCtx.Header.Number == 10), Arg.Any()); @@ -189,6 +191,7 @@ public void Call_uses_valid_mix_hash() _blockchainBridge.Call(header, tx, CancellationToken.None); _transactionProcessor.Received().CallAndRestore( + Arg.Any(), tx, Arg.Is(blkCtx => blkCtx.Header.MixHash == TestItem.KeccakA), Arg.Any()); @@ -204,6 +207,7 @@ public void Call_uses_valid_beneficiary() _blockchainBridge.Call(header, tx, CancellationToken.None); _transactionProcessor.Received().CallAndRestore( + Arg.Any(), tx, Arg.Is(blkCtx => blkCtx.Header.Beneficiary == TestItem.AddressB), Arg.Any()); diff --git a/src/Nethermind/Nethermind.Facade/BlockchainBridge.cs b/src/Nethermind/Nethermind.Facade/BlockchainBridge.cs index b95f0646548..9db523e3628 100644 --- a/src/Nethermind/Nethermind.Facade/BlockchainBridge.cs +++ b/src/Nethermind/Nethermind.Facade/BlockchainBridge.cs @@ -194,9 +194,9 @@ public CallOutput EstimateGas(BlockHeader header, Transaction tx, int errorMargi true, estimateGasTracer.WithCancellation(cancellationToken)); - GasEstimator gasEstimator = new(scope.TransactionProcessor, scope.WorldState, + GasEstimator gasEstimator = new(scope.TransactionProcessor, _specProvider, _blocksConfig); - long estimate = gasEstimator.Estimate(tx, header, estimateGasTracer, errorMargin, cancellationToken); + long estimate = gasEstimator.Estimate(scope.WorldState, tx, header, estimateGasTracer, errorMargin, cancellationToken); return new CallOutput { @@ -294,7 +294,7 @@ private TransactionResult CallAndRestore( callHeader.MixHash = blockHeader.MixHash; callHeader.IsPostMerge = blockHeader.Difficulty == 0; transaction.Hash = transaction.CalculateHash(); - return scope.TransactionProcessor.CallAndRestore(transaction, new(callHeader), tracer); + return scope.TransactionProcessor.CallAndRestore(scope.WorldState, transaction, new(callHeader), tracer); } public ulong GetChainId() diff --git a/src/Nethermind/Nethermind.Facade/Simulate/SimulateReadOnlyBlocksProcessingEnv.cs b/src/Nethermind/Nethermind.Facade/Simulate/SimulateReadOnlyBlocksProcessingEnv.cs index 3f70c14789f..c155bd8e06e 100644 --- a/src/Nethermind/Nethermind.Facade/Simulate/SimulateReadOnlyBlocksProcessingEnv.cs +++ b/src/Nethermind/Nethermind.Facade/Simulate/SimulateReadOnlyBlocksProcessingEnv.cs @@ -71,7 +71,7 @@ public SimulateReadOnlyBlocksProcessingEnv( StateReader = WorldStateManager.GlobalStateReader; CodeInfoRepository = new OverridableCodeInfoRepository(new CodeInfoRepository()); VirtualMachine = new SimulateVirtualMachine(new VirtualMachine(BlockhashProvider, specProvider, CodeInfoRepository, logManager)); - _transactionProcessor = new SimulateTransactionProcessor(SpecProvider, StateProvider, VirtualMachine, CodeInfoRepository, _logManager, validate); + _transactionProcessor = new SimulateTransactionProcessor(SpecProvider, VirtualMachine, CodeInfoRepository, _logManager, validate); _blockValidator = CreateValidator(); BlockTransactionPicker = new BlockProductionTransactionPicker(specProvider, true); } diff --git a/src/Nethermind/Nethermind.Facade/Simulate/SimulateTransactionProcessor.cs b/src/Nethermind/Nethermind.Facade/Simulate/SimulateTransactionProcessor.cs index 9b6ebb52192..41058294247 100644 --- a/src/Nethermind/Nethermind.Facade/Simulate/SimulateTransactionProcessor.cs +++ b/src/Nethermind/Nethermind.Facade/Simulate/SimulateTransactionProcessor.cs @@ -14,22 +14,21 @@ namespace Nethermind.Facade.Simulate; public class SimulateTransactionProcessor( ISpecProvider? specProvider, - IWorldState? worldState, IVirtualMachine? virtualMachine, ICodeInfoRepository? codeInfoRepository, ILogManager? logManager, bool validate) - : TransactionProcessor(specProvider, worldState, virtualMachine, codeInfoRepository, logManager), ITransactionProcessor + : TransactionProcessor(specProvider, virtualMachine, codeInfoRepository, logManager), ITransactionProcessor { protected override bool ShouldValidate(ExecutionOptions opts) => true; - protected override TransactionResult Execute(Transaction tx, in BlockExecutionContext blCtx, ITxTracer tracer, ExecutionOptions opts) + protected override TransactionResult Execute(IWorldState worldState, Transaction tx, in BlockExecutionContext blCtx, ITxTracer tracer, ExecutionOptions opts) { if (!validate) { opts |= ExecutionOptions.NoValidation; } - return base.Execute(tx, in blCtx, tracer, opts); + return base.Execute(worldState, tx, in blCtx, tracer, opts); } } diff --git a/src/Nethermind/Nethermind.Init/Steps/InitializeBlockchain.cs b/src/Nethermind/Nethermind.Init/Steps/InitializeBlockchain.cs index 21189802d53..2917c492dc3 100644 --- a/src/Nethermind/Nethermind.Init/Steps/InitializeBlockchain.cs +++ b/src/Nethermind/Nethermind.Init/Steps/InitializeBlockchain.cs @@ -169,7 +169,6 @@ protected virtual ITransactionProcessor CreateTransactionProcessor(CodeInfoRepos return new TransactionProcessor( _api.SpecProvider, - _api.WorldState, virtualMachine, codeInfoRepository, _api.LogManager); diff --git a/src/Nethermind/Nethermind.Init/Steps/LoadGenesisBlock.cs b/src/Nethermind/Nethermind.Init/Steps/LoadGenesisBlock.cs index a87d9f01663..07eebd7cacb 100644 --- a/src/Nethermind/Nethermind.Init/Steps/LoadGenesisBlock.cs +++ b/src/Nethermind/Nethermind.Init/Steps/LoadGenesisBlock.cs @@ -68,7 +68,7 @@ protected virtual void Load(IWorldState worldState) _api.SpecProvider, worldState, _api.TransactionProcessor) - .Load(); + .Load(worldState); ManualResetEventSlim genesisProcessedEvent = new(false); diff --git a/src/Nethermind/Nethermind.JsonRpc.Test/Modules/Trace/ParityStyleTracerTests.cs b/src/Nethermind/Nethermind.JsonRpc.Test/Modules/Trace/ParityStyleTracerTests.cs index e45f59a631b..44a36eb51aa 100644 --- a/src/Nethermind/Nethermind.JsonRpc.Test/Modules/Trace/ParityStyleTracerTests.cs +++ b/src/Nethermind/Nethermind.JsonRpc.Test/Modules/Trace/ParityStyleTracerTests.cs @@ -65,7 +65,7 @@ public void Setup() BlockhashProvider blockhashProvider = new(_blockTree, specProvider, stateProvider, LimboLogs.Instance); CodeInfoRepository codeInfoRepository = new(); VirtualMachine virtualMachine = new(blockhashProvider, specProvider, codeInfoRepository, LimboLogs.Instance); - TransactionProcessor transactionProcessor = new(specProvider, stateProvider, virtualMachine, codeInfoRepository, LimboLogs.Instance); + TransactionProcessor transactionProcessor = new(specProvider, virtualMachine, codeInfoRepository, LimboLogs.Instance); _poSSwitcher = Substitute.For(); BlockProcessor blockProcessor = new( diff --git a/src/Nethermind/Nethermind.JsonRpc/Modules/Eth/SimulateTxExecutor.cs b/src/Nethermind/Nethermind.JsonRpc/Modules/Eth/SimulateTxExecutor.cs index c0bf2db8e26..3fe72066b20 100644 --- a/src/Nethermind/Nethermind.JsonRpc/Modules/Eth/SimulateTxExecutor.cs +++ b/src/Nethermind/Nethermind.JsonRpc/Modules/Eth/SimulateTxExecutor.cs @@ -15,6 +15,7 @@ using Nethermind.Facade.Proxy.Models.Simulate; using Nethermind.Facade.Simulate; using Nethermind.JsonRpc.Data; +using Nethermind.State; namespace Nethermind.JsonRpc.Modules.Eth; diff --git a/src/Nethermind/Nethermind.JsonRpc/Modules/Trace/MergeRpcRewardCalculator.cs b/src/Nethermind/Nethermind.JsonRpc/Modules/Trace/MergeRpcRewardCalculator.cs index 828f90bbf2b..e087e0773ad 100644 --- a/src/Nethermind/Nethermind.JsonRpc/Modules/Trace/MergeRpcRewardCalculator.cs +++ b/src/Nethermind/Nethermind.JsonRpc/Modules/Trace/MergeRpcRewardCalculator.cs @@ -5,6 +5,7 @@ using Nethermind.Consensus.Rewards; using Nethermind.Core; using Nethermind.Int256; +using Nethermind.State; namespace Nethermind.JsonRpc.Modules.Trace; @@ -19,13 +20,13 @@ public MergeRpcRewardCalculator(IRewardCalculator beforeTheMerge, IPoSSwitcher p _poSSwitcher = poSSwitcher; } - public BlockReward[] CalculateRewards(Block block) + public BlockReward[] CalculateRewards(Block block, IWorldState worldState) { if (_poSSwitcher.IsPostMerge(block.Header)) { return new[] { new BlockReward(block.Beneficiary!, UInt256.Zero) }; } - return _beforeTheMerge.CalculateRewards(block); + return _beforeTheMerge.CalculateRewards(block, worldState); } } diff --git a/src/Nethermind/Nethermind.Merge.AuRa.Test/AuraWithdrawalProcessorTests.cs b/src/Nethermind/Nethermind.Merge.AuRa.Test/AuraWithdrawalProcessorTests.cs index 0b445936112..d9771a2d391 100644 --- a/src/Nethermind/Nethermind.Merge.AuRa.Test/AuraWithdrawalProcessorTests.cs +++ b/src/Nethermind/Nethermind.Merge.AuRa.Test/AuraWithdrawalProcessorTests.cs @@ -11,6 +11,7 @@ using Nethermind.Logging; using Nethermind.Merge.AuRa.Contracts; using Nethermind.Merge.AuRa.Withdrawals; +using Nethermind.State; using NSubstitute; using NUnit.Framework; @@ -44,18 +45,17 @@ public void Should_invoke_contract_as_expected() // we need to capture those values, because the ArrayPools will be disposed before we can match them ulong[] values = Array.Empty(); Address[] addresses = Array.Empty
(); - contract.ExecuteWithdrawals( - block.Header, + IWorldState worldState = Substitute.For(); + contract.ExecuteWithdrawals(worldState, block.Header, 4, Arg.Do>(a => values = a.ToArray()), Arg.Do>(a => addresses = a.ToArray())); - withdrawalProcessor.ProcessWithdrawals(block, spec); + withdrawalProcessor.ProcessWithdrawals(block, spec, worldState); contract .Received(1) - .ExecuteWithdrawals( - Arg.Is(block.Header), + .ExecuteWithdrawals(worldState, Arg.Is(block.Header), Arg.Is(4), Arg.Is>(a => values.SequenceEqual(new[] { 1_000_000UL, 2_000_000UL })), Arg.Is>(a => addresses.SequenceEqual(new[] { Address.SystemUser, Address.Zero }))); @@ -72,12 +72,11 @@ public void Should_not_invoke_contract_before_Shanghai() spec.WithdrawalsEnabled.Returns(false); - withdrawalProcessor.ProcessWithdrawals(block, spec); + withdrawalProcessor.ProcessWithdrawals(block, spec, Substitute.For()); contract .Received(0) - .ExecuteWithdrawals( - Arg.Any(), + .ExecuteWithdrawals(Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any()); diff --git a/src/Nethermind/Nethermind.Merge.AuRa/AuRaMergeBlockProcessor.cs b/src/Nethermind/Nethermind.Merge.AuRa/AuRaMergeBlockProcessor.cs index 1a55b725abd..a8d561d8747 100644 --- a/src/Nethermind/Nethermind.Merge.AuRa/AuRaMergeBlockProcessor.cs +++ b/src/Nethermind/Nethermind.Merge.AuRa/AuRaMergeBlockProcessor.cs @@ -53,8 +53,9 @@ public AuRaMergeBlockProcessor( ) { } - protected override TxReceipt[] ProcessBlock(Block block, IBlockTracer blockTracer, ProcessingOptions options) => + protected override TxReceipt[] ProcessBlock(IWorldState worldState, Block block, IBlockTracer blockTracer, + ProcessingOptions options) => block.IsPostMerge - ? PostMergeProcessBlock(block, blockTracer, options) - : base.ProcessBlock(block, blockTracer, options); + ? PostMergeProcessBlock(worldState, block, blockTracer, options) + : base.ProcessBlock(worldState, block, blockTracer, options); } diff --git a/src/Nethermind/Nethermind.Merge.AuRa/Contracts/IWithdrawalContract.cs b/src/Nethermind/Nethermind.Merge.AuRa/Contracts/IWithdrawalContract.cs index e18cc9c0030..edd1594ff77 100644 --- a/src/Nethermind/Nethermind.Merge.AuRa/Contracts/IWithdrawalContract.cs +++ b/src/Nethermind/Nethermind.Merge.AuRa/Contracts/IWithdrawalContract.cs @@ -4,10 +4,12 @@ using System.Collections.Generic; using Nethermind.Core; using Nethermind.Int256; +using Nethermind.State; namespace Nethermind.Merge.AuRa.Contracts; public interface IWithdrawalContract { - void ExecuteWithdrawals(BlockHeader blockHeader, UInt256 failedMaxCount, IList amounts, IList
addresses); + void ExecuteWithdrawals(IWorldState worldState, BlockHeader blockHeader, UInt256 failedMaxCount, + IList amounts, IList
addresses); } diff --git a/src/Nethermind/Nethermind.Merge.AuRa/Contracts/WithdrawalContract.cs b/src/Nethermind/Nethermind.Merge.AuRa/Contracts/WithdrawalContract.cs index 4f6b82d7595..a313648ffe6 100644 --- a/src/Nethermind/Nethermind.Merge.AuRa/Contracts/WithdrawalContract.cs +++ b/src/Nethermind/Nethermind.Merge.AuRa/Contracts/WithdrawalContract.cs @@ -8,6 +8,7 @@ using Nethermind.Core; using Nethermind.Evm.TransactionProcessing; using Nethermind.Int256; +using Nethermind.State; namespace Nethermind.Merge.AuRa.Contracts; @@ -26,12 +27,13 @@ public WithdrawalContract( Address contractAddress) : base(transactionProcessor, abiEncoder, contractAddress) { } - public void ExecuteWithdrawals(BlockHeader blockHeader, UInt256 failedMaxCount, IList amounts, IList
addresses) + public void ExecuteWithdrawals(IWorldState worldState, BlockHeader blockHeader, UInt256 failedMaxCount, + IList amounts, IList
addresses) { ArgumentNullException.ThrowIfNull(blockHeader); ArgumentNullException.ThrowIfNull(amounts); ArgumentNullException.ThrowIfNull(addresses); - Call(blockHeader, "executeSystemWithdrawals", Address.SystemUser, GasLimit, failedMaxCount, amounts, addresses); + Call(blockHeader, (string)(string)"executeSystemWithdrawals", Address.SystemUser, GasLimit, worldState, failedMaxCount, amounts, addresses); } } diff --git a/src/Nethermind/Nethermind.Merge.AuRa/Withdrawals/AuraWithdrawalProcessor.cs b/src/Nethermind/Nethermind.Merge.AuRa/Withdrawals/AuraWithdrawalProcessor.cs index 85776645e9a..9bb9a92e46c 100644 --- a/src/Nethermind/Nethermind.Merge.AuRa/Withdrawals/AuraWithdrawalProcessor.cs +++ b/src/Nethermind/Nethermind.Merge.AuRa/Withdrawals/AuraWithdrawalProcessor.cs @@ -12,6 +12,7 @@ using Nethermind.Int256; using Nethermind.Logging; using Nethermind.Merge.AuRa.Contracts; +using Nethermind.State; namespace Nethermind.Merge.AuRa.Withdrawals; @@ -29,7 +30,7 @@ public AuraWithdrawalProcessor(IWithdrawalContract contract, ILogManager logMana _logger = logManager.GetClassLogger(); } - public void ProcessWithdrawals(Block block, IReleaseSpec spec) + public void ProcessWithdrawals(Block block, IReleaseSpec spec, IWorldState worldState) { if (!spec.WithdrawalsEnabled || block.Withdrawals is null) // The second check seems redundant return; @@ -52,7 +53,7 @@ public void ProcessWithdrawals(Block block, IReleaseSpec spec) try { - _contract.ExecuteWithdrawals(block.Header, _failedWithdrawalsMaxCount, amounts, addresses); + _contract.ExecuteWithdrawals(worldState, block.Header, _failedWithdrawalsMaxCount, amounts, addresses); } catch (Exception ex) when (ex is ArgumentNullException || ex is EvmException) { diff --git a/src/Nethermind/Nethermind.Merge.Plugin.Test/EngineModuleTests.HelperFunctions.cs b/src/Nethermind/Nethermind.Merge.Plugin.Test/EngineModuleTests.HelperFunctions.cs index dd4de68d98d..a8891f577bb 100644 --- a/src/Nethermind/Nethermind.Merge.Plugin.Test/EngineModuleTests.HelperFunctions.cs +++ b/src/Nethermind/Nethermind.Merge.Plugin.Test/EngineModuleTests.HelperFunctions.cs @@ -105,7 +105,7 @@ private static ExecutionPayload CreateBlockRequest(MergeTestBlockchain chain, Ex blockRequest.TryGetBlock(out Block? block); Snapshot before = chain.State.TakeSnapshot(); - chain.WithdrawalProcessor?.ProcessWithdrawals(block!, chain.SpecProvider.GenesisSpec); + chain.WithdrawalProcessor?.ProcessWithdrawals(block!, chain.SpecProvider.GenesisSpec, chain.State); chain.State.Commit(chain.SpecProvider.GenesisSpec); chain.State.RecalculateStateRoot(); @@ -127,7 +127,7 @@ private static ExecutionPayloadV3 CreateBlockRequestV3(MergeTestBlockchain chain _beaconBlockRootHandler.ApplyContractStateChanges(block!, chain.SpecProvider.GenesisSpec, chain.State); var blockHashStore = new BlockhashStore(chain.SpecProvider, chain.State); blockHashStore.ApplyBlockhashStateChanges(block!.Header); - chain.WithdrawalProcessor?.ProcessWithdrawals(block!, chain.SpecProvider.GenesisSpec); + chain.WithdrawalProcessor?.ProcessWithdrawals(block!, chain.SpecProvider.GenesisSpec, chain.State); chain.State.Commit(chain.SpecProvider.GenesisSpec); chain.State.RecalculateStateRoot(); diff --git a/src/Nethermind/Nethermind.Merge.Plugin.Test/MergeRewardCalculatorTests.cs b/src/Nethermind/Nethermind.Merge.Plugin.Test/MergeRewardCalculatorTests.cs index 3c49333bdaa..b38f4edd7d7 100644 --- a/src/Nethermind/Nethermind.Merge.Plugin.Test/MergeRewardCalculatorTests.cs +++ b/src/Nethermind/Nethermind.Merge.Plugin.Test/MergeRewardCalculatorTests.cs @@ -12,6 +12,7 @@ using Nethermind.Specs; using Nethermind.Specs.ChainSpecStyle; using Nethermind.Specs.Forks; +using Nethermind.State; using NSubstitute; using NUnit.Framework; @@ -30,14 +31,14 @@ public void Two_uncles_from_the_same_coinbase() PoSSwitcher poSSwitcher = CreatePosSwitcher(); poSSwitcher.TryUpdateTerminalBlock(block.Header); MergeRewardCalculator calculator = new(new RewardCalculator(MainnetSpecProvider.Instance), poSSwitcher); - BlockReward[] rewards = calculator.CalculateRewards(block); + BlockReward[] rewards = calculator.CalculateRewards(block, Substitute.For()); Assert.That(rewards.Length, Is.EqualTo(3)); Assert.That((long)rewards[0].Value, Is.EqualTo(5312500000000000000), "miner"); Assert.That((long)rewards[1].Value, Is.EqualTo(3750000000000000000), "uncle1"); Assert.That((long)rewards[2].Value, Is.EqualTo(3750000000000000000), "uncle2"); - rewards = calculator.CalculateRewards(block2); + rewards = calculator.CalculateRewards(block2, Substitute.For()); Assert.That(rewards.Length, Is.EqualTo(0)); } @@ -53,13 +54,13 @@ public void One_uncle() poSSwitcher.TryUpdateTerminalBlock(block.Header); MergeRewardCalculator calculator = new(new RewardCalculator(MainnetSpecProvider.Instance), poSSwitcher); - BlockReward[] rewards = calculator.CalculateRewards(block); + BlockReward[] rewards = calculator.CalculateRewards(block, Substitute.For()); Assert.That(rewards.Length, Is.EqualTo(2)); Assert.That((long)rewards[0].Value, Is.EqualTo(5156250000000000000), "miner"); Assert.That((long)rewards[1].Value, Is.EqualTo(3750000000000000000), "uncle1"); - rewards = calculator.CalculateRewards(block2); + rewards = calculator.CalculateRewards(block2, Substitute.For()); Assert.That(rewards.Length, Is.EqualTo(0)); } @@ -73,12 +74,12 @@ public void No_uncles() poSSwitcher.TryUpdateTerminalBlock(block.Header); MergeRewardCalculator calculator = new(new RewardCalculator(MainnetSpecProvider.Instance), poSSwitcher); - BlockReward[] rewards = calculator.CalculateRewards(block); + BlockReward[] rewards = calculator.CalculateRewards(block, Substitute.For()); Assert.That(rewards.Length, Is.EqualTo(1)); Assert.That((long)rewards[0].Value, Is.EqualTo(5000000000000000000), "miner"); - rewards = calculator.CalculateRewards(block2); + rewards = calculator.CalculateRewards(block2, Substitute.For()); Assert.That(rewards.Length, Is.EqualTo(0)); } @@ -95,14 +96,14 @@ public void Byzantium_reward_two_uncles() poSSwitcher.TryUpdateTerminalBlock(block.Header); MergeRewardCalculator calculator = new(new RewardCalculator(MainnetSpecProvider.Instance), poSSwitcher); - BlockReward[] rewards = calculator.CalculateRewards(block); + BlockReward[] rewards = calculator.CalculateRewards(block, Substitute.For()); Assert.That(rewards.Length, Is.EqualTo(3)); Assert.That((long)rewards[0].Value, Is.EqualTo(3187500000000000000), "miner"); Assert.That((long)rewards[1].Value, Is.EqualTo(2250000000000000000), "uncle1"); Assert.That((long)rewards[2].Value, Is.EqualTo(2250000000000000000), "uncle2"); - rewards = calculator.CalculateRewards(block2); + rewards = calculator.CalculateRewards(block2, Substitute.For()); Assert.That(rewards.Length, Is.EqualTo(0)); } @@ -120,14 +121,14 @@ public void Constantinople_reward_two_uncles() PoSSwitcher poSSwitcher = CreatePosSwitcher(); poSSwitcher.TryUpdateTerminalBlock(block.Header); MergeRewardCalculator calculator = new(new RewardCalculator(MainnetSpecProvider.Instance), poSSwitcher); - BlockReward[] rewards = calculator.CalculateRewards(block); + BlockReward[] rewards = calculator.CalculateRewards(block, Substitute.For()); Assert.That(rewards.Length, Is.EqualTo(3)); Assert.That((long)rewards[0].Value, Is.EqualTo(2125000000000000000), "miner"); Assert.That((long)rewards[1].Value, Is.EqualTo(1500000000000000000), "uncle1"); Assert.That((long)rewards[2].Value, Is.EqualTo(1500000000000000000), "uncle2"); - rewards = calculator.CalculateRewards(block2); + rewards = calculator.CalculateRewards(block2, Substitute.For()); Assert.That(rewards.Length, Is.EqualTo(0)); } @@ -141,10 +142,10 @@ public void No_block_rewards_calculator() poSSwitcher.TryUpdateTerminalBlock(block.Header); MergeRewardCalculator calculator = new(NoBlockRewards.Instance, poSSwitcher); - BlockReward[] rewards = calculator.CalculateRewards(block); + BlockReward[] rewards = calculator.CalculateRewards(block, Substitute.For()); Assert.That(rewards.Length, Is.EqualTo(0)); - rewards = calculator.CalculateRewards(block2); + rewards = calculator.CalculateRewards(block2, Substitute.For()); Assert.That(rewards.Length, Is.EqualTo(0)); } diff --git a/src/Nethermind/Nethermind.Merge.Plugin/MergeRewardCalculator.cs b/src/Nethermind/Nethermind.Merge.Plugin/MergeRewardCalculator.cs index 8d3a91c7c2e..9d6fafef9c6 100644 --- a/src/Nethermind/Nethermind.Merge.Plugin/MergeRewardCalculator.cs +++ b/src/Nethermind/Nethermind.Merge.Plugin/MergeRewardCalculator.cs @@ -5,6 +5,7 @@ using Nethermind.Consensus; using Nethermind.Consensus.Rewards; using Nethermind.Core; +using Nethermind.State; namespace Nethermind.Merge.Plugin { @@ -19,14 +20,14 @@ public MergeRewardCalculator(IRewardCalculator? beforeTheMerge, IPoSSwitcher poS _poSSwitcher = poSSwitcher ?? throw new ArgumentNullException(nameof(poSSwitcher)); } - public BlockReward[] CalculateRewards(Block block) + public BlockReward[] CalculateRewards(Block block, IWorldState worldState) { if (_poSSwitcher.IsPostMerge(block.Header)) { - return NoBlockRewards.Instance.CalculateRewards(block); + return NoBlockRewards.Instance.CalculateRewards(block, worldState); } - return _beforeTheMerge.CalculateRewards(block); + return _beforeTheMerge.CalculateRewards(block, worldState); } } } diff --git a/src/Nethermind/Nethermind.Optimism/InitializeBlockchainOptimism.cs b/src/Nethermind/Nethermind.Optimism/InitializeBlockchainOptimism.cs index 92ab38d4aad..a35a01a0394 100644 --- a/src/Nethermind/Nethermind.Optimism/InitializeBlockchainOptimism.cs +++ b/src/Nethermind/Nethermind.Optimism/InitializeBlockchainOptimism.cs @@ -46,7 +46,6 @@ protected override ITransactionProcessor CreateTransactionProcessor(CodeInfoRepo return new OptimismTransactionProcessor( _api.SpecProvider, - _api.WorldState, virtualMachine, _api.LogManager, _api.L1CostHelper, diff --git a/src/Nethermind/Nethermind.Optimism/OptimismBlockProcessor.cs b/src/Nethermind/Nethermind.Optimism/OptimismBlockProcessor.cs index 385e7217e3c..fc50ddcbf6c 100644 --- a/src/Nethermind/Nethermind.Optimism/OptimismBlockProcessor.cs +++ b/src/Nethermind/Nethermind.Optimism/OptimismBlockProcessor.cs @@ -42,9 +42,10 @@ public OptimismBlockProcessor( ReceiptsTracer = new OptimismBlockReceiptTracer(opSpecHelper, stateProvider); } - protected override TxReceipt[] ProcessBlock(Block block, IBlockTracer blockTracer, ProcessingOptions options) + protected override TxReceipt[] ProcessBlock(IWorldState worldState, Block block, IBlockTracer blockTracer, + ProcessingOptions options) { _contractRewriter?.RewriteContract(block.Header, _stateProvider); - return base.ProcessBlock(block, blockTracer, options); + return base.ProcessBlock(worldState, block, blockTracer, options); } } diff --git a/src/Nethermind/Nethermind.Optimism/OptimismReadOnlyTxProcessingEnv.cs b/src/Nethermind/Nethermind.Optimism/OptimismReadOnlyTxProcessingEnv.cs index 499a0c9883f..e656c915265 100644 --- a/src/Nethermind/Nethermind.Optimism/OptimismReadOnlyTxProcessingEnv.cs +++ b/src/Nethermind/Nethermind.Optimism/OptimismReadOnlyTxProcessingEnv.cs @@ -33,6 +33,6 @@ protected override TransactionProcessor CreateTransactionProcessor() BlockhashProvider blockhashProvider = new(BlockTree, SpecProvider, StateProvider, LogManager); VirtualMachine virtualMachine = new(blockhashProvider, SpecProvider, CodeInfoRepository, LogManager); - return new OptimismTransactionProcessor(SpecProvider, StateProvider, virtualMachine, LogManager, l1CostHelper, opSpecHelper, CodeInfoRepository); + return new OptimismTransactionProcessor(SpecProvider, virtualMachine, LogManager, l1CostHelper, opSpecHelper, CodeInfoRepository); } } diff --git a/src/Nethermind/Nethermind.Optimism/OptimismTransactionProcessor.cs b/src/Nethermind/Nethermind.Optimism/OptimismTransactionProcessor.cs index aa71d1fae45..72ebe3eb74d 100644 --- a/src/Nethermind/Nethermind.Optimism/OptimismTransactionProcessor.cs +++ b/src/Nethermind/Nethermind.Optimism/OptimismTransactionProcessor.cs @@ -15,17 +15,16 @@ namespace Nethermind.Optimism; public class OptimismTransactionProcessor( ISpecProvider specProvider, - IWorldState worldState, IVirtualMachine virtualMachine, ILogManager logManager, IL1CostHelper l1CostHelper, IOptimismSpecHelper opSpecHelper, ICodeInfoRepository? codeInfoRepository - ) : TransactionProcessor(specProvider, worldState, virtualMachine, codeInfoRepository, logManager) + ) : TransactionProcessor(specProvider, virtualMachine, codeInfoRepository, logManager) { private UInt256? _currentTxL1Cost; - protected override TransactionResult Execute(Transaction tx, in BlockExecutionContext blCtx, ITxTracer tracer, ExecutionOptions opts) + protected override TransactionResult Execute(IWorldState worldState, Transaction tx, in BlockExecutionContext blCtx, ITxTracer tracer, ExecutionOptions opts) { if (tx.SupportsBlobs) { @@ -37,24 +36,24 @@ protected override TransactionResult Execute(Transaction tx, in BlockExecutionCo _currentTxL1Cost = null; if (tx.IsDeposit()) { - WorldState.AddToBalanceAndCreateIfNotExists(tx.SenderAddress!, tx.Mint, spec); + worldState.AddToBalanceAndCreateIfNotExists(tx.SenderAddress!, tx.Mint, spec); } - Snapshot snapshot = WorldState.TakeSnapshot(); + Snapshot snapshot = worldState.TakeSnapshot(); - TransactionResult result = base.Execute(tx, blCtx, tracer, opts); + TransactionResult result = base.Execute(worldState, tx, blCtx, tracer, opts); if (!result && tx.IsDeposit() && result.Error != "block gas limit exceeded") { // deposit tx should be included - WorldState.Restore(snapshot); - if (!WorldState.AccountExists(tx.SenderAddress!)) + worldState.Restore(snapshot); + if (!worldState.AccountExists(tx.SenderAddress!)) { - WorldState.CreateAccount(tx.SenderAddress!, 0, 1); + worldState.CreateAccount(tx.SenderAddress!, 0, 1); } else { - WorldState.IncrementNonce(tx.SenderAddress!); + worldState.IncrementNonce(tx.SenderAddress!); } blCtx.Header.GasUsed += tx.GasLimit; tracer.MarkAsFailed(tx.To!, tx.GasLimit, Array.Empty(), $"failed deposit: {result.Error}"); @@ -72,7 +71,7 @@ protected override TransactionResult ValidateStatic(Transaction tx, BlockHeader return result; } - protected override TransactionResult BuyGas(Transaction tx, BlockHeader header, IReleaseSpec spec, ITxTracer tracer, ExecutionOptions opts, + protected override TransactionResult BuyGas(IWorldState worldState, Transaction tx, BlockHeader header, IReleaseSpec spec, ITxTracer tracer, ExecutionOptions opts, in UInt256 effectiveGasPrice, out UInt256 premiumPerGas, out UInt256 senderReservedGasPayment) { premiumPerGas = UInt256.Zero; @@ -80,7 +79,7 @@ protected override TransactionResult BuyGas(Transaction tx, BlockHeader header, bool validate = !opts.HasFlag(ExecutionOptions.NoValidation); - UInt256 senderBalance = WorldState.GetBalance(tx.SenderAddress!); + UInt256 senderBalance = worldState.GetBalance(tx.SenderAddress!); if (tx.IsDeposit() && !tx.IsOPSystemTransaction && senderBalance < tx.Value) { @@ -101,7 +100,7 @@ protected override TransactionResult BuyGas(Transaction tx, BlockHeader header, return "insufficient sender balance"; } - UInt256 l1Cost = _currentTxL1Cost ??= l1CostHelper.ComputeL1Cost(tx, header, WorldState); + UInt256 l1Cost = _currentTxL1Cost ??= l1CostHelper.ComputeL1Cost(tx, header, worldState); if (UInt256.SubtractUnderflow(balanceLeft, l1Cost, out balanceLeft)) { TraceLogInvalidTx(tx, $"INSUFFICIENT_SENDER_BALANCE: ({tx.SenderAddress})_BALANCE = {senderBalance}"); @@ -126,40 +125,40 @@ protected override TransactionResult BuyGas(Transaction tx, BlockHeader header, } if (validate) - WorldState.SubtractFromBalance(tx.SenderAddress!, senderReservedGasPayment, spec); + worldState.SubtractFromBalance(tx.SenderAddress!, senderReservedGasPayment, spec); return TransactionResult.Ok; } - protected override TransactionResult IncrementNonce(Transaction tx, BlockHeader header, IReleaseSpec spec, ITxTracer tracer, ExecutionOptions opts) + protected override TransactionResult IncrementNonce(IWorldState worldState, Transaction tx, BlockHeader header, IReleaseSpec spec, ITxTracer tracer, ExecutionOptions opts) { if (!tx.IsDeposit()) - return base.IncrementNonce(tx, header, spec, tracer, opts); + return base.IncrementNonce(worldState, tx, header, spec, tracer, opts); - WorldState.IncrementNonce(tx.SenderAddress!); + worldState.IncrementNonce(tx.SenderAddress!); return TransactionResult.Ok; } - protected override TransactionResult ValidateSender(Transaction tx, BlockHeader header, IReleaseSpec spec, ITxTracer tracer, ExecutionOptions opts) => - tx.IsDeposit() ? TransactionResult.Ok : base.ValidateSender(tx, header, spec, tracer, opts); + protected override TransactionResult ValidateSender(IWorldState worldState, Transaction tx, BlockHeader header, IReleaseSpec spec, ITxTracer tracer, ExecutionOptions opts) => + tx.IsDeposit() ? TransactionResult.Ok : base.ValidateSender(worldState, tx, header, spec, tracer, opts); - protected override void PayFees(Transaction tx, BlockHeader header, IReleaseSpec spec, ITxTracer tracer, + protected override void PayFees(IWorldState worldState, Transaction tx, BlockHeader header, IReleaseSpec spec, ITxTracer tracer, in TransactionSubstate substate, in long spentGas, in UInt256 premiumPerGas, in byte statusCode) { if (!tx.IsDeposit()) { // Skip coinbase payments for deposit tx in Regolith - base.PayFees(tx, header, spec, tracer, substate, spentGas, premiumPerGas, statusCode); + base.PayFees(worldState, tx, header, spec, tracer, substate, spentGas, premiumPerGas, statusCode); if (opSpecHelper.IsBedrock(header)) { - UInt256 l1Cost = _currentTxL1Cost ??= l1CostHelper.ComputeL1Cost(tx, header, WorldState); - WorldState.AddToBalanceAndCreateIfNotExists(opSpecHelper.L1FeeReceiver, l1Cost, spec); + UInt256 l1Cost = _currentTxL1Cost ??= l1CostHelper.ComputeL1Cost(tx, header, worldState); + worldState.AddToBalanceAndCreateIfNotExists(opSpecHelper.L1FeeReceiver, l1Cost, spec); } } } - protected override long Refund(Transaction tx, BlockHeader header, IReleaseSpec spec, ExecutionOptions opts, + protected override long Refund(IWorldState worldState, Transaction tx, BlockHeader header, IReleaseSpec spec, ExecutionOptions opts, in TransactionSubstate substate, in long unspentGas, in UInt256 gasPrice) { // if deposit: skip refunds, skip tipping coinbase @@ -171,6 +170,6 @@ protected override long Refund(Transaction tx, BlockHeader header, IReleaseSpec return tx.IsOPSystemTransaction ? 0 : tx.GasLimit; } - return base.Refund(tx, header, spec, opts, substate, unspentGas, gasPrice); + return base.Refund(worldState, tx, header, spec, opts, substate, unspentGas, gasPrice); } } diff --git a/src/Nethermind/Nethermind.Synchronization.Test/SyncThreadTests.cs b/src/Nethermind/Nethermind.Synchronization.Test/SyncThreadTests.cs index 1a0ba7d72ee..50d115a462d 100644 --- a/src/Nethermind/Nethermind.Synchronization.Test/SyncThreadTests.cs +++ b/src/Nethermind/Nethermind.Synchronization.Test/SyncThreadTests.cs @@ -292,7 +292,7 @@ private SyncTestContext CreateSyncManager(int index) RewardCalculator rewardCalculator = new(specProvider); TransactionProcessor txProcessor = - new(specProvider, stateProvider, virtualMachine, codeInfoRepository, logManager); + new(specProvider, virtualMachine, codeInfoRepository, logManager); BlockProcessor blockProcessor = new( specProvider, @@ -314,7 +314,7 @@ private SyncTestContext CreateSyncManager(int index) WorldState devState = new(trieStore, codeDb, logManager); VirtualMachine devEvm = new(blockhashProvider, specProvider, codeInfoRepository, logManager); - TransactionProcessor devTxProcessor = new(specProvider, devState, devEvm, codeInfoRepository, logManager); + TransactionProcessor devTxProcessor = new(specProvider, devEvm, codeInfoRepository, logManager); BlockProcessor devBlockProcessor = new( specProvider,