Skip to content

Commit

Permalink
refactor tests
Browse files Browse the repository at this point in the history
  • Loading branch information
rjnrohit committed Feb 17, 2025
1 parent ef29584 commit 42e1af3
Show file tree
Hide file tree
Showing 3 changed files with 28 additions and 187 deletions.
185 changes: 19 additions & 166 deletions src/Nethermind/Nethermind.Flashbots.Test/FlashbotsModuleTests.Setup.cs
Original file line number Diff line number Diff line change
@@ -1,36 +1,19 @@
// SPDX-FileCopyrightText: 2024 Demerzel Solutions Limited
// SPDX-License-Identifier: LGPL-3.0-only

using System;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
using Nethermind.Blockchain.BeaconBlockRoot;
using Nethermind.Blockchain.Blocks;
using Nethermind.Blockchain.Synchronization;
using Nethermind.Consensus;
using Nethermind.Consensus.Processing;
using Nethermind.Consensus.Rewards;
using Nethermind.Consensus.Validators;
using Nethermind.Consensus.Withdrawals;
using Nethermind.Core;
using Nethermind.Core.Crypto;
using Nethermind.Core.Extensions;
using Nethermind.Core.Specs;
using Nethermind.Core.Test.Blockchain;
using Nethermind.Crypto;
using Nethermind.Db;
using Nethermind.Evm.Tracing;
using Nethermind.Flashbots;
using Nethermind.Flashbots.Handlers;
using Nethermind.Flashbots.Modules.Flashbots;
using Nethermind.Int256;
using Nethermind.Logging;
using Nethermind.Merge.Plugin;
using Nethermind.Specs;
using Nethermind.Specs.ChainSpecStyle;
using Nethermind.Specs.Forks;
using NUnit.Framework;
using Nethermind.Merge.Plugin.Test;
using Nethermind.Specs.Forks;
using Nethermind.Specs;
using Nethermind.Consensus.Processing;
using Nethermind.Core.Specs;
using Nethermind.Core.Extensions;

namespace Nethermind.Flashbots.Test;

Expand Down Expand Up @@ -67,20 +50,22 @@ public TestKeyAndAddress()
}
}

protected virtual MergeTestBlockChain CreateBaseBlockChain(
IFlashbotsConfig flashbotsConfig,
ILogManager? logManager = null)
public ReadOnlyTxProcessingEnvFactory CreateReadOnlyTxProcessingEnvFactory(EngineModuleTests.MergeTestBlockchain chain)
{
return new MergeTestBlockChain(flashbotsConfig, logManager);
ReadOnlyTxProcessingEnvFactory readOnlyTxProcessingEnvFactory = new(
chain.WorldStateManager,
chain.BlockTree,
chain.SpecProvider,
chain.LogManager
);
return readOnlyTxProcessingEnvFactory;
}

protected async Task<MergeTestBlockChain> CreateBlockChain(
IReleaseSpec? releaseSpec = null,
IFlashbotsConfig? flashbotsConfig = null,
ILogManager? logManager = null)
=> await CreateBaseBlockChain(flashbotsConfig ?? new FlashbotsConfig(), logManager).Build(new TestSingleReleaseSpecProvider(releaseSpec ?? London.Instance));
protected static async Task<EngineModuleTests.MergeTestBlockchain> CreateBlockChain(
IReleaseSpec? releaseSpec = null)
=> await new EngineModuleTests.MergeTestBlockchain().Build(new TestSingleReleaseSpecProvider(releaseSpec ?? London.Instance));

private IFlashbotsRpcModule CreateFlashbotsModule(MergeTestBlockChain chain, ReadOnlyTxProcessingEnvFactory readOnlyTxProcessingEnvFactory)
private IFlashbotsRpcModule CreateFlashbotsModule(EngineModuleTests.MergeTestBlockchain chain, ReadOnlyTxProcessingEnvFactory readOnlyTxProcessingEnvFactory)
{
return new FlashbotsRpcModule(
new ValidateSubmissionHandler(
Expand All @@ -90,140 +75,8 @@ private IFlashbotsRpcModule CreateFlashbotsModule(MergeTestBlockChain chain, Rea
readOnlyTxProcessingEnvFactory,
chain.LogManager,
chain.SpecProvider,
chain.FlashbotsConfig
new FlashbotsConfig()
)
);
}

public class MergeTestBlockChain : TestBlockchain
{
public IFlashbotsConfig FlashbotsConfig;

public IMergeConfig MergeConfig;

public IWithdrawalProcessor? WithdrawalProcessor { get; set; }

public ReadOnlyTxProcessingEnvFactory ReadOnlyTxProcessingEnvFactory { get; set; }

public MergeTestBlockChain(IFlashbotsConfig flashbotsConfig, ILogManager? logManager = null)
{
FlashbotsConfig = flashbotsConfig;
MergeConfig = new MergeConfig() { TerminalTotalDifficulty = "0" };
LogManager = logManager ?? LogManager;
}

public sealed override ILogManager LogManager { get; set; } = LimboLogs.Instance;

public ReadOnlyTxProcessingEnvFactory CreateReadOnlyTxProcessingEnvFactory()
{
ReadOnlyTxProcessingEnvFactory = new ReadOnlyTxProcessingEnvFactory(
WorldStateManager,
BlockTree,
SpecProvider,
LogManager
);
return ReadOnlyTxProcessingEnvFactory;
}

protected override IBlockProcessor CreateBlockProcessor()
{
BlockValidator = CreateBlockValidator();
WithdrawalProcessor = new WithdrawalProcessor(State, LogManager);
IBlockProcessor processor = new BlockProcessor(
SpecProvider,
BlockValidator,
NoBlockRewards.Instance,
new BlockProcessor.BlockValidationTransactionsExecutor(TxProcessor, State),
State,
ReceiptStorage,
TxProcessor,
new BeaconBlockRootHandler(TxProcessor, State),
new BlockhashStore(SpecProvider, State),
LogManager,
WithdrawalProcessor,
preWarmer: CreateBlockCachePreWarmer()
);

return new TestBlockProcessorInterceptor(processor);
}

protected IBlockValidator CreateBlockValidator()
{
PoSSwitcher = new PoSSwitcher(MergeConfig, SyncConfig.Default, new MemDb(), BlockTree, SpecProvider, new ChainSpec() { Genesis = Core.Test.Builders.Build.A.Block.WithDifficulty(0).TestObject }, LogManager);
ISealValidator SealValidator = new MergeSealValidator(PoSSwitcher, Always.Valid);
HeaderValidator = new MergeHeaderValidator(
PoSSwitcher,
new HeaderValidator(BlockTree, SealValidator, SpecProvider, LogManager),
BlockTree,
SpecProvider,
SealValidator,
LogManager
);

return new BlockValidator(
new TxValidator(SpecProvider.ChainId),
HeaderValidator,
Always.Valid,
SpecProvider,
LogManager
);
}

protected override async Task<TestBlockchain> Build(ISpecProvider? specProvider = null, UInt256? initialValues = null, bool addBlockOnStart = true)
{
TestBlockchain chain = await base.Build(specProvider, initialValues, false);
return chain;
}

public async Task<MergeTestBlockChain> Build(ISpecProvider? specProvider = null) =>
(MergeTestBlockChain)await Build(specProvider, null);

}
}

public class TestBlockProcessorInterceptor : IBlockProcessor
{
private readonly IBlockProcessor _blockProcessorImplementation;
public Exception? ExceptionToThrow { get; set; }

public TestBlockProcessorInterceptor(IBlockProcessor baseBlockProcessor)
{
_blockProcessorImplementation = baseBlockProcessor;
}

public Block[] Process(Hash256 newBranchStateRoot, List<Block> suggestedBlocks, ProcessingOptions processingOptions,
IBlockTracer blockTracer)
{

if (ExceptionToThrow is not null)
{
throw ExceptionToThrow;
}

return _blockProcessorImplementation.Process(newBranchStateRoot, suggestedBlocks, processingOptions, blockTracer);
}

public event EventHandler<BlocksProcessingEventArgs>? BlocksProcessing
{
add => _blockProcessorImplementation.BlocksProcessing += value;
remove => _blockProcessorImplementation.BlocksProcessing -= value;
}

public event EventHandler<BlockEventArgs>? BlockProcessing
{
add => _blockProcessorImplementation.BlockProcessing += value;
remove => _blockProcessorImplementation.BlockProcessing -= value;
}

public event EventHandler<BlockProcessedEventArgs>? BlockProcessed
{
add => _blockProcessorImplementation.BlockProcessed += value;
remove => _blockProcessorImplementation.BlockProcessed -= value;
}

public event EventHandler<TxProcessedEventArgs>? TransactionProcessed
{
add => _blockProcessorImplementation.TransactionProcessed += value;
remove => _blockProcessorImplementation.TransactionProcessed -= value;
}
}
27 changes: 8 additions & 19 deletions src/Nethermind/Nethermind.Flashbots.Test/FlashbotsModuleTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@
using Nethermind.JsonRpc;
using Nethermind.JsonRpc.Test;
using Nethermind.Merge.Plugin.Data;
using Nethermind.Merge.Plugin.Test;
using Nethermind.Specs.Forks;
using Nethermind.State;
using NUnit.Framework;
Expand All @@ -30,8 +31,8 @@ public partial class FlashbotsModuleTests
[Test]
public virtual async Task TestValidateBuilderSubmissionV3()
{
using MergeTestBlockChain chain = await CreateBlockChain(releaseSpec: Cancun.Instance);
ReadOnlyTxProcessingEnvFactory readOnlyTxProcessingEnvFactory = chain.CreateReadOnlyTxProcessingEnvFactory();
using EngineModuleTests.MergeTestBlockchain chain = await CreateBlockChain(releaseSpec: Cancun.Instance);
ReadOnlyTxProcessingEnvFactory readOnlyTxProcessingEnvFactory = CreateReadOnlyTxProcessingEnvFactory(chain);
IFlashbotsRpcModule rpc = CreateFlashbotsModule(chain, readOnlyTxProcessingEnvFactory);

Block block = CreateBlock(chain);
Expand Down Expand Up @@ -59,41 +60,29 @@ public virtual async Task TestValidateBuilderSubmissionV3()
ResultWrapper<FlashbotsResult> result = await rpc.flashbots_validateBuilderSubmissionV3(BlockRequest);
result.Should().NotBeNull();

// Assert.That(result.Result, Is.EqualTo(Result.Success));
// Assert.That(result.Data.Status, Is.EqualTo(FlashbotsStatus.Valid));
Assert.That(result.Result.Error, Is.EqualTo("No proposer payment receipt"));
Assert.That(result.Data.Status, Is.EqualTo(FlashbotsStatus.Invalid));

string response = await RpcTest.TestSerializedRequest(rpc, "flashbots_validateBuilderSubmissionV3", BlockRequest);
JsonRpcSuccessResponse? jsonResponse = chain.JsonSerializer.Deserialize<JsonRpcSuccessResponse>(response);
jsonResponse.Should().NotBeNull();
}

private Block CreateBlock(MergeTestBlockChain chain)
private Block CreateBlock(EngineModuleTests.MergeTestBlockchain chain)
{
BlockHeader currentHeader = chain.BlockTree.Head.Header;
IWorldState State = chain.State;
State.CreateAccount(TestKeysAndAddress.TestAddr, TestKeysAndAddress.TestBalance);
UInt256 nonce = State.GetNonce(TestKeysAndAddress.TestAddr);

Transaction tx1 = Build.A.Transaction.WithNonce(nonce).WithTo(TestKeysAndAddress.TestBuilderAddr).WithValue(10).WithGasLimit(21000).WithGasPrice(TestKeysAndAddress.BaseInitialFee).Signed(TestKeysAndAddress.PrivateKey).TestObject;
chain.TxPool.SubmitTx(tx1, TxPool.TxHandlingOptions.None);

Transaction tx2 = Build.A.Transaction.WithNonce(nonce + 1).WithValue(0).WithGasLimit(1000000).WithGasPrice(2 * TestKeysAndAddress.BaseInitialFee).Signed(TestKeysAndAddress.PrivateKey).TestObject;
chain.TxPool.SubmitTx(tx2, TxPool.TxHandlingOptions.None);

UInt256 baseFee = BaseFeeCalculator.Calculate(currentHeader, chain.SpecProvider.GetFinalSpec());

Transaction tx3 = Build.A.Transaction.WithNonce(nonce + 2).WithValue(10).WithGasLimit(21000).WithValue(baseFee).Signed(TestKeysAndAddress.PrivateKey).TestObject;
chain.TxPool.SubmitTx(tx3, TxPool.TxHandlingOptions.None);

Withdrawal[] withdrawals = [
Build.A.Withdrawal.WithIndex(0).WithValidatorIndex(1).WithAmount(100).WithRecipient(TestKeysAndAddress.TestAddr).TestObject,
Build.A.Withdrawal.WithIndex(1).WithValidatorIndex(1).WithAmount(100).WithRecipient(TestKeysAndAddress.TestAddr).TestObject
];

ulong timestamp = Timestamper.UnixTime.Seconds;
Hash256 prevRandao = Keccak.Zero;

Hash256 expectedBlockHash = new("0xd8f631517e9f336a3c13997786e874e17e7859fc95eddc1359226c0b8d71a307");
Hash256 expectedBlockHash = new("0x479f7c9b7389e9ff3f443b99c3cd4b90f9b7feef5f41d714edb59de6b3e7ac02");
string stateRoot = "0xa272b2f949e4a0e411c9b45542bd5d0ef3c311b5f26c4ed6b7a8d4f605a91154";

return new(
Expand All @@ -119,7 +108,7 @@ private Block CreateBlock(MergeTestBlockChain chain)
ReceiptsRoot = chain.BlockTree.Head!.ReceiptsRoot!,
StateRoot = new(stateRoot),
},
[tx1, tx2, tx3],
[],
Array.Empty<BlockHeader>(),
withdrawals
);
Expand Down
3 changes: 1 addition & 2 deletions src/Nethermind/Nethermind.Flashbots/Flashbots.cs
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,7 @@ public class Flashbots : INethermindPlugin
public string Author => "Nethermind";
public Task InitRpcModules()
{
ArgumentNullException.ThrowIfNull(_api.RpcModuleProvider);
ReadOnlyTxProcessingEnvFactory readOnlyTxProcessingEnvFactory = new ReadOnlyTxProcessingEnvFactory(
_api.WorldStateManager ?? throw new ArgumentNullException(nameof(_api.WorldStateManager)),
_api.BlockTree ?? throw new ArgumentNullException(nameof(_api.BlockTree)),
Expand All @@ -45,8 +46,6 @@ public Task InitRpcModules()
);

ModuleFactoryBase<IFlashbotsRpcModule> flashbotsRpcModule = new FlashbotsRpcModuleFactory(validateSubmissionHandler);

ArgumentNullException.ThrowIfNull(_api.RpcModuleProvider);
_api.RpcModuleProvider.RegisterBounded(flashbotsRpcModule,
_flashbotsConfig.FlashbotsModuleConcurrentInstances ?? Environment.ProcessorCount, _jsonRpcConfig.Timeout);

Expand Down

0 comments on commit 42e1af3

Please sign in to comment.