Skip to content

Commit

Permalink
pass in world state where there in no context which worldState to use
Browse files Browse the repository at this point in the history
  • Loading branch information
tanishqjasoria committed Aug 15, 2024
1 parent 52ecf6d commit d81ce27
Show file tree
Hide file tree
Showing 94 changed files with 489 additions and 430 deletions.
2 changes: 1 addition & 1 deletion src/Nethermind/Nethermind.Analytics/AnalyticsPlugin.cs
Original file line number Diff line number Diff line change
Expand Up @@ -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<IAnalyticsRpcModule>(analyticsRpcModule));
return Task.CompletedTask;
}
Expand Down
6 changes: 4 additions & 2 deletions src/Nethermind/Nethermind.Analytics/AnalyticsRpcModule.cs
Original file line number Diff line number Diff line change
Expand Up @@ -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<UInt256> analytics_verifySupply()
Expand All @@ -33,7 +35,7 @@ public ResultWrapper<UInt256> analytics_verifySupply()

public ResultWrapper<UInt256> 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<UInt256>.Success(rewardsVerifier.BlockRewards);
}
Expand Down
7 changes: 5 additions & 2 deletions src/Nethermind/Nethermind.Analytics/RewardsVerifier.cs
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@
using Nethermind.Int256;
using Nethermind.Logging;
using Nethermind.Specs;
using Nethermind.State;

namespace Nethermind.Analytics
{
Expand All @@ -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<BlockVisitOutcome> 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)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -44,6 +44,6 @@ protected override Block GetGenesisBlock() =>
SpecProvider,
State,
TxProcessor)
.Load();
.Load(State);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -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<IWorldState>(),
Arg.Is<Transaction>(t => IsEquivalentTo(expectation, t)), Arg.Is<BlockExecutionContext>(blkCtx => blkCtx.Header.Equals(_block.Header)), Arg.Any<ITxTracer>());
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@
using NSubstitute;
using NUnit.Framework;
using Nethermind.Evm;
using Nethermind.State;

namespace Nethermind.AuRa.Test.Reward
{
Expand All @@ -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;
Expand All @@ -49,6 +51,7 @@ public void SetUp()

_abiEncoder = Substitute.For<IAbiEncoder>();
_transactionProcessor = Substitute.For<ITransactionProcessor>();
_worldState = Substitute.For<IWorldState>();

_block = new Block(Build.A.BlockHeader.TestObject, new BlockBody());

Expand Down Expand Up @@ -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));
}

Expand All @@ -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();
}

Expand All @@ -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<Address, BlockReward[]>() { { _address10, new[] { expected } } });
AuRaRewardCalculator calculator = new(_auraParameters, _abiEncoder, _transactionProcessor);
BlockReward[] result = calculator.CalculateRewards(_block);
BlockReward[] result = calculator.CalculateRewards(_block, _worldState);
result.Should().BeEquivalentTo(expected);
}

Expand All @@ -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, BlockReward[]>() { { address, new[] { expected } } });
AuRaRewardCalculator calculator = new(_auraParameters, _abiEncoder, _transactionProcessor);
BlockReward[] result = calculator.CalculateRewards(_block);
BlockReward[] result = calculator.CalculateRewards(_block, _worldState);
result.Should().BeEquivalentTo(expected);
}

Expand All @@ -167,7 +170,7 @@ public void calculates_rewards_correctly_for_uncles(long blockNumber, ulong expe

SetupBlockRewards(new Dictionary<Address, BlockReward[]>() { { _address10, expected } });
AuRaRewardCalculator calculator = new(_auraParameters, _abiEncoder, _transactionProcessor);
BlockReward[] result = calculator.CalculateRewards(_block);
BlockReward[] result = calculator.CalculateRewards(_block, _worldState);
result.Should().BeEquivalentTo(expected);
}

Expand All @@ -190,13 +193,14 @@ public void calculates_rewards_correctly_for_external_addresses()

SetupBlockRewards(new Dictionary<Address, BlockReward[]>() { { _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<Address, BlockReward[]> rewards)
{
_transactionProcessor.When(x => x.Execute(
Arg.Any<IWorldState>(),
Arg.Is<Transaction>(t => CheckTransaction(t, rewards.Keys, _rewardData)),
Arg.Is<BlockExecutionContext>(blkCtx => blkCtx.Header.Equals(_block.Header)),
Arg.Is<ITxTracer>(t => t is CallOutputTracer)))
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -27,7 +29,7 @@ public void calculates_rewards_correctly_for_thresholds(long blockNumber, ulong
Dictionary<long, UInt256> 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<IWorldState>());
result.Should().BeEquivalentTo(new BlockReward(_block.Beneficiary, expectedReward));
}

Expand All @@ -38,7 +40,7 @@ public void calculates_rewards_correctly_for_single_value(long blockNumber, ulon
Dictionary<long, UInt256> blockReward = new() { { 0, 200 } };
_block.Header.Number = blockNumber;
StaticRewardCalculator calculator = new(blockReward);
BlockReward[] result = calculator.CalculateRewards(_block);
BlockReward[] result = calculator.CalculateRewards(_block, Substitute.For<IWorldState>());
result.Should().BeEquivalentTo(new BlockReward(_block.Beneficiary, expectedReward));
}

Expand All @@ -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<IWorldState>());
result.Should().BeEquivalentTo(new BlockReward(_block.Beneficiary, expectedReward));
}

Expand All @@ -59,7 +61,7 @@ public void calculates_rewards_correctly_for_not_supported_value(long blockNumbe
Dictionary<long, UInt256> blockReward = new() { { 10, 200 } };
_block.Header.Number = blockNumber;
StaticRewardCalculator calculator = new(blockReward);
BlockReward[] result = calculator.CalculateRewards(_block);
BlockReward[] result = calculator.CalculateRewards(_block, Substitute.For<IWorldState>());
result.Should().BeEquivalentTo(new BlockReward(_block.Beneficiary, expectedReward));
}

Expand All @@ -69,7 +71,7 @@ public void calculates_rewards_correctly_for_empty_dictionary(long blockNumber,
Dictionary<long, UInt256> blockReward = new() { };
_block.Header.Number = blockNumber;
StaticRewardCalculator calculator = new(blockReward);
BlockReward[] result = calculator.CalculateRewards(_block);
BlockReward[] result = calculator.CalculateRewards(_block, Substitute.For<IWorldState>());
result.Should().BeEquivalentTo(new BlockReward(_block.Beneficiary, expectedReward));
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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);
Expand Down Expand Up @@ -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<IWorldState>(),
Arg.Is<Transaction>(t => CheckTransaction(t, _getValidatorsData)),
Arg.Is<BlockExecutionContext>(blkCtx => blkCtx.Header.Equals(_parentHeader)),
Arg.Is<ITxTracer>(t => t is CallOutputTracer));

// finalizeChange should be called
_transactionProcessor.Received(finalizeChangeCalled ? 1 : 0)
.Execute(Arg.Is<Transaction>(t => CheckTransaction(t, _finalizeChangeData)),
.Execute(Arg.Any<IWorldState>(),Arg.Is<Transaction>(t => CheckTransaction(t, _finalizeChangeData)),
Arg.Is<BlockExecutionContext>(blkCtx => blkCtx.Header.Equals(block.Header)),
Arg.Is<ITxTracer>(t => t is CallOutputTracer));

Expand Down Expand Up @@ -521,7 +522,7 @@ public void consecutive_initiate_change_gets_finalized_and_switch_validators(Con

_blockTree.FindBlock(_block.Header.Hash, Arg.Any<BlockTreeLookupOptions>()).Returns(new Block(_block.Header.Clone()));

Action preProcess = () => validator.OnBlockProcessingStart(_block);
Action preProcess = () => validator.OnBlockProcessingStart(_block, _stateProvider);
preProcess.Should().NotThrow<InvalidOperationException>(test.TestName);
validator.OnBlockProcessingEnd(_block, txReceipts);
int finalizedNumber = blockNumber - validator.Validators.MinSealersForFinalization() + 1;
Expand Down Expand Up @@ -587,7 +588,7 @@ IEnumerable<Block> 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)
Expand All @@ -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<Transaction>(t => CheckTransaction(t, _finalizeChangeData)),
.Execute(Arg.Any<IWorldState>(), Arg.Is<Transaction>(t => CheckTransaction(t, _finalizeChangeData)),
Arg.Is<BlockExecutionContext>(blkCtx => blkCtx.Header.Equals(_block.Header)),
Arg.Is<ITxTracer>(t => t is CallOutputTracer));

Expand Down Expand Up @@ -635,6 +636,7 @@ private void SetupInitialValidators(BlockHeader header, BlockHeader parentHeader
}

_transactionProcessor.When(x => x.CallAndRestore(
Arg.Any<IWorldState>(),
Arg.Is<Transaction>(t => CheckTransaction(t, _getValidatorsData)),
Arg.Any<BlockExecutionContext>(),
Arg.Is<ITxTracer>(t => t is CallOutputTracer)))
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@
using Nethermind.Core.Test.Builders;
using Nethermind.Specs.ChainSpecStyle;
using Nethermind.Logging;
using Nethermind.State;
using NSubstitute;
using NUnit.Framework;

Expand Down Expand Up @@ -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<IWorldState>(), ProcessingOptions.ProducingBlock);
_innerValidators.Count.Should().Be(2);
return _innerValidators.Keys.Last();
}
Expand All @@ -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<long, AuRaParameters.Validator> validatorInfo);
_finalizationManager.GetFinalizationLevel(validatorInfo.Key).Returns(finalizedLastValidatorBlockLevel ? blockNumber - 2 : (long?)null);
_block.Header.Number = blockNumber;
validator.OnBlockProcessingStart(_block);
validator.OnBlockProcessingStart(_block, Substitute.For<IWorldState>());
return _innerValidators.Keys.Last();
}

Expand All @@ -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<IWorldState>());
validator.OnBlockProcessingEnd(_block, Array.Empty<TxReceipt>());

int finalizedBlock = i - blocksToFinalization;
Expand All @@ -206,7 +207,7 @@ private void EnsureInnerValidatorsCalled(Func<int, (IAuRaValidator Validator, in
{
(IAuRaValidator innerValidator, int calls) = getValidatorWithCallCount(i);

innerValidator.Received(calls).OnBlockProcessingStart(Arg.Any<Block>());
innerValidator.Received(calls).OnBlockProcessingStart(Arg.Any<Block>(), Arg.Any<IWorldState>());
innerValidator.Received(calls).OnBlockProcessingEnd(Arg.Any<Block>(),
Array.Empty<TxReceipt>());
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -65,7 +65,7 @@ private Block GetGenesisBlock(string chainspecPath)
specProvider.GetSpec(Arg.Any<ForkActivation>()).Returns(Berlin.Instance);
ITransactionProcessor transactionProcessor = Substitute.For<ITransactionProcessor>();
GenesisLoader genesisLoader = new(chainSpec, specProvider, stateProvider, transactionProcessor);
return genesisLoader.Load();
return genesisLoader.Load(stateProvider);
}


Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -66,7 +66,6 @@ public void Test()
LimboLogs.Instance);
TransactionProcessor txProcessor = new(
specProvider,
stateProvider,
virtualMachine,
codeInfoRepository,
LimboLogs.Instance);
Expand Down
1 change: 0 additions & 1 deletion src/Nethermind/Nethermind.Blockchain.Test/ReorgTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -65,7 +65,6 @@ public void Setup()
LimboLogs.Instance);
TransactionProcessor transactionProcessor = new(
specProvider,
stateProvider,
virtualMachine,
codeInfoRepository,
LimboLogs.Instance);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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<IWorldState>());
Assert.IsEmpty(rewards);
}
}
Expand Down
Loading

0 comments on commit d81ce27

Please sign in to comment.