diff --git a/src/Nethermind/Ethereum.Test.Base/GeneralStateTest.cs b/src/Nethermind/Ethereum.Test.Base/GeneralStateTest.cs index 09158536941..0fe03d362bc 100644 --- a/src/Nethermind/Ethereum.Test.Base/GeneralStateTest.cs +++ b/src/Nethermind/Ethereum.Test.Base/GeneralStateTest.cs @@ -37,7 +37,7 @@ public class GeneralStateTest : IEthereumTest public UInt256? ParentBlobGasUsed { get; set; } public UInt256? ParentExcessBlobGas { get; set; } - public Hash256? RequestsRoot { get; set; } + public Hash256? RequestsHash { get; set; } public override string ToString() { diff --git a/src/Nethermind/Ethereum.Test.Base/GeneralTestBase.cs b/src/Nethermind/Ethereum.Test.Base/GeneralTestBase.cs index 9cbb8e54947..d3cec557a09 100644 --- a/src/Nethermind/Ethereum.Test.Base/GeneralTestBase.cs +++ b/src/Nethermind/Ethereum.Test.Base/GeneralTestBase.cs @@ -106,7 +106,7 @@ protected EthereumTestResult RunTest(GeneralStateTest test, ITxTracer txTracer) header.ParentBeaconBlockRoot = test.CurrentBeaconRoot; header.ExcessBlobGas = test.CurrentExcessBlobGas ?? (test.Fork is Cancun ? 0ul : null); header.BlobGasUsed = BlobGasCalculator.CalculateBlobGas(test.Transaction); - header.RequestsRoot = test.RequestsRoot; + header.RequestsHash = test.RequestsHash; Stopwatch stopwatch = Stopwatch.StartNew(); IReleaseSpec? spec = specProvider.GetSpec((ForkActivation)test.CurrentNumber); diff --git a/src/Nethermind/Nethermind.Blockchain.Test/Validators/BlockValidatorTests.cs b/src/Nethermind/Nethermind.Blockchain.Test/Validators/BlockValidatorTests.cs index 0ee1de5ced9..69c4bad6fa7 100644 --- a/src/Nethermind/Nethermind.Blockchain.Test/Validators/BlockValidatorTests.cs +++ b/src/Nethermind/Nethermind.Blockchain.Test/Validators/BlockValidatorTests.cs @@ -2,7 +2,6 @@ // SPDX-License-Identifier: LGPL-3.0-only using Nethermind.Consensus.Validators; -using Nethermind.Core.ConsensusRequests; using Nethermind.Core; using Nethermind.Core.Crypto; using Nethermind.Core.Specs; @@ -199,51 +198,4 @@ public void ValidateSuggestedBlock_SuggestedBlockIsInvalid_CorrectErrorIsSet(Blo Assert.That(error, Does.StartWith(expectedError)); } - - [Test] - public void ValidateBodyAgainstHeader_BlockHasInvalidRequestRoot_ReturnsFalse() - { - Block block = Build.A.Block - .WithConsensusRequests(new ConsensusRequest[] { - Build.A.Deposit.WithIndex(0).TestObject, - Build.A.WithdrawalRequest.TestObject - }) - .TestObject; - block.Header.RequestsRoot = Keccak.OfAnEmptyString; - - Assert.That( - BlockValidator.ValidateBodyAgainstHeader(block.Header, block.Body), - Is.False); - } - - [Test] - public void ValidateBodyRequests_BlockHasReuests_InOrder_ReturnsTrue() - { - Block block = Build.A.Block - .WithConsensusRequests(new ConsensusRequest[] { - Build.A.Deposit.WithIndex(0).TestObject, - Build.A.WithdrawalRequest.TestObject - }) - .TestObject; - - Assert.That( - BlockValidator.ValidateRequestsOrder(block, out string? _), - Is.True); - } - - [Test] - public void ValidateBodyRequests_BlockHasReuests_OutOfOrder_ReturnsFalse() - { - Block block = Build.A.Block - .WithConsensusRequests(new ConsensusRequest[] { - Build.A.WithdrawalRequest.TestObject, - Build.A.Deposit.WithIndex(0).TestObject - }) - .TestObject; - - Assert.That( - BlockValidator.ValidateRequestsOrder(block, out string? _), - Is.False); - } - } diff --git a/src/Nethermind/Nethermind.Consensus.AuRa/AuRaBlockProcessor.cs b/src/Nethermind/Nethermind.Consensus.AuRa/AuRaBlockProcessor.cs index 6cc123917ed..1fccf8e681e 100644 --- a/src/Nethermind/Nethermind.Consensus.AuRa/AuRaBlockProcessor.cs +++ b/src/Nethermind/Nethermind.Consensus.AuRa/AuRaBlockProcessor.cs @@ -8,8 +8,8 @@ using Nethermind.Blockchain.Find; using Nethermind.Blockchain.Receipts; using Nethermind.Consensus.AuRa.Validators; +using Nethermind.Consensus.ExecutionRequests; using Nethermind.Consensus.Processing; -using Nethermind.Consensus.Requests; using Nethermind.Consensus.Rewards; using Nethermind.Consensus.Transactions; using Nethermind.Consensus.Validators; @@ -51,7 +51,7 @@ public AuRaBlockProcessor( AuRaContractGasLimitOverride? gasLimitOverride = null, ContractRewriter? contractRewriter = null, IBlockCachePreWarmer? preWarmer = null, - IConsensusRequestsProcessor? consensusRequestsProcessor = null) + IExecutionRequestsProcessor? executionRequestsProcessor = null) : base( specProvider, blockValidator, @@ -65,7 +65,7 @@ public AuRaBlockProcessor( logManager, withdrawalProcessor, preWarmer: preWarmer, - consensusRequestsProcessor: consensusRequestsProcessor) + executionRequestsProcessor: executionRequestsProcessor) { _specProvider = specProvider; _blockTree = blockTree ?? throw new ArgumentNullException(nameof(blockTree)); diff --git a/src/Nethermind/Nethermind.Consensus.Clique/CliqueBlockProducer.cs b/src/Nethermind/Nethermind.Consensus.Clique/CliqueBlockProducer.cs index f85842a83ca..4f255ceca5e 100644 --- a/src/Nethermind/Nethermind.Consensus.Clique/CliqueBlockProducer.cs +++ b/src/Nethermind/Nethermind.Consensus.Clique/CliqueBlockProducer.cs @@ -15,7 +15,6 @@ using Nethermind.Consensus.Producers; using Nethermind.Consensus.Transactions; using Nethermind.Core; -using Nethermind.Core.ConsensusRequests; using Nethermind.Core.Crypto; using Nethermind.Core.Specs; using Nethermind.Crypto; @@ -500,8 +499,7 @@ ILogManager logManager header, selectedTxs, Array.Empty(), - spec.WithdrawalsEnabled ? Enumerable.Empty() : null, - spec.RequestsEnabled ? Enumerable.Empty() : null + spec.WithdrawalsEnabled ? Enumerable.Empty() : null ); header.TxRoot = TxTrie.CalculateRoot(block.Transactions); block.Header.Author = _sealer.Address; diff --git a/src/Nethermind/Nethermind.Consensus.Test/DepositProcessorTests.cs b/src/Nethermind/Nethermind.Consensus.Test/DepositProcessorTests.cs deleted file mode 100644 index 0ab384c1db4..00000000000 --- a/src/Nethermind/Nethermind.Consensus.Test/DepositProcessorTests.cs +++ /dev/null @@ -1,70 +0,0 @@ -// SPDX-FileCopyrightText: 2024 Demerzel Solutions Limited -// SPDX-License-Identifier: LGPL-3.0-only - -using System; -using System.Linq; -using FluentAssertions; -using Nethermind.Abi; -using Nethermind.Consensus.Requests; -using Nethermind.Core; -using Nethermind.Core.ConsensusRequests; -using Nethermind.Core.Extensions; -using Nethermind.Core.Specs; -using Nethermind.Core.Test.Builders; -using NSubstitute; -using NUnit.Framework; - - -namespace Nethermind.Consensus.Test; - -public class DepositProcessorTests -{ - [Test] - public void ShouldProcessDeposit() - { - Block block = Build.A.Block.TestObject; - DepositsProcessor depositsProcessor = new(); - - var deposit = new Deposit() - { - Amount = 32000000000, - Index = 0, - Pubkey = Bytes.FromHexString( - "000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000001"), - Signature = Bytes.FromHexString( - "000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000003"), - WithdrawalCredentials = - Bytes.FromHexString("0000000000000000000000000000000000000000000000000000000000000002") - }; - - TxReceipt txReceipt = Build.A.Receipt.WithLogs( - Build.A.LogEntry.WithData( - Bytes.FromHexString( - "00000000000000000000000000000000000000000000000000000000000000a000000000000000000000000000000000000000000000000000000000000001000000000000000000000000000000000000000000000000000000000000000140000000000000000000000000000000000000000000000000000000000000018000000000000000000000000000000000000000000000000000000000000002000000000000000000000000000000000000000000000000000000000000000030000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000001000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000020000000000000000000000000000000000000000000000000000000000000000200000000000000000000000000000000000000000000000000000000000000080040597307000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000006000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000300000000000000000000000000000000000000000000000000000000000000080000000000000000000000000000000000000000000000000000000000000000" - ) - ) - .WithAddress( - new Core.Address(Bytes.FromHexString("0x00000000219ab540356cbb839cbe05303d7705fa")) - ).TestObject - ).TestObject; - - IReleaseSpec spec = Substitute.For(); - - spec.DepositsEnabled.Returns(true); - spec.DepositContractAddress.Returns( - new Core.Address(Bytes.FromHexString("0x00000000219ab540356cbb839cbe05303d7705fa")) - ); - - var processedDeposits = depositsProcessor.ProcessDeposits(block, new[] { txReceipt }, spec).ToList(); - - Assert.That(processedDeposits, Has.Count.EqualTo(1)); - - Deposit processedDeposit = processedDeposits[0]; - - processedDeposit.Amount.Should().Be(deposit.Amount); - processedDeposit.Index.Should().Be(deposit.Index); - processedDeposit.Pubkey?.Span.SequenceEqual(deposit.Pubkey.Value.Span).Should().BeTrue(); - processedDeposit.Signature?.SequenceEqual(deposit.Signature).Should().BeTrue(); - processedDeposit.WithdrawalCredentials?.SequenceEqual(deposit.WithdrawalCredentials).Should().BeTrue(); - } -} diff --git a/src/Nethermind/Nethermind.Consensus.Test/ExecutionRequestProcessorTests.cs b/src/Nethermind/Nethermind.Consensus.Test/ExecutionRequestProcessorTests.cs new file mode 100644 index 00000000000..08047236ac3 --- /dev/null +++ b/src/Nethermind/Nethermind.Consensus.Test/ExecutionRequestProcessorTests.cs @@ -0,0 +1,151 @@ +// SPDX-FileCopyrightText: 2024 Demerzel Solutions Limited +// SPDX-License-Identifier: LGPL-3.0-only + +using System; +using System.Linq; +using Nethermind.Abi; +using Nethermind.Consensus.ExecutionRequests; +using Nethermind.Core; +using Nethermind.Core.Collections; +using Nethermind.Core.Crypto; +using Nethermind.Core.ExecutionRequest; +using Nethermind.Core.Extensions; +using Nethermind.Core.Specs; +using Nethermind.Core.Test.Builders; +using Nethermind.Db; +using Nethermind.Evm; +using Nethermind.Evm.Tracing; +using Nethermind.Evm.TransactionProcessing; +using Nethermind.Int256; +using Nethermind.Logging; +using Nethermind.Specs; +using Nethermind.State; +using Nethermind.Trie.Pruning; +using NSubstitute; +using NUnit.Framework; + +namespace Nethermind.Consensus.Test; + +public class ExecutionProcessorTests +{ + private ISpecProvider _specProvider; + private ITransactionProcessor _transactionProcessor; + private WorldState _stateProvider; + private IReleaseSpec _spec; + private static readonly UInt256 AccountBalance = 1.Ether(); + private static readonly Address DepositContractAddress = Eip6110Constants.MainnetDepositContractAddress; + private static readonly Address eip7002Account = Eip7002Constants.WithdrawalRequestPredeployAddress; + private static readonly Address eip7251Account = Eip7251Constants.ConsolidationRequestPredeployAddress; + private static readonly AbiSignature _depositEventABI = new("DepositEvent", AbiType.DynamicBytes, AbiType.DynamicBytes, AbiType.DynamicBytes, AbiType.DynamicBytes, AbiType.DynamicBytes); + private static readonly AbiEncoder _abiEncoder = AbiEncoder.Instance; + + private static readonly TestExecutionRequest[] _executionDepositRequests = [TestItem.ExecutionRequestA, TestItem.ExecutionRequestB, TestItem.ExecutionRequestC]; + private static readonly TestExecutionRequest[] _executionWithdrawalRequests = [TestItem.ExecutionRequestD, TestItem.ExecutionRequestE, TestItem.ExecutionRequestF]; + private static readonly TestExecutionRequest[] _executionConsolidationRequests = [TestItem.ExecutionRequestG, TestItem.ExecutionRequestH, TestItem.ExecutionRequestI]; + + private void FlatEncodeWithoutType(ExecutionRequest[] requests, Span buffer) + { + int currentPosition = 0; + + foreach (ExecutionRequest request in requests) + { + // Ensure the buffer has enough space to accommodate the new data + if (currentPosition + request.RequestData!.Length > buffer.Length) + { + throw new InvalidOperationException("Buffer is not large enough to hold all data of requests"); + } + + // Copy the RequestData to the buffer at the current position + request.RequestData.CopyTo(buffer.Slice(currentPosition, request.RequestData.Length)); + currentPosition += request.RequestData.Length; + } + } + + [SetUp] + public void Setup() + { + _specProvider = MainnetSpecProvider.Instance; + MemDb stateDb = new(); + TrieStore trieStore = new(stateDb, LimboLogs.Instance); + + _stateProvider = new WorldState(trieStore, new MemDb(), LimboLogs.Instance); + _stateProvider.CreateAccount(eip7002Account, AccountBalance); + _stateProvider.CreateAccount(eip7251Account, AccountBalance); + _stateProvider.Commit(_specProvider.GenesisSpec); + _stateProvider.CommitTree(0); + + _spec = Substitute.For(); + + _spec.RequestsEnabled.Returns(true); + _spec.DepositsEnabled.Returns(true); + _spec.WithdrawalRequestsEnabled.Returns(true); + _spec.ConsolidationRequestsEnabled.Returns(true); + + _spec.DepositContractAddress.Returns(DepositContractAddress); + _spec.Eip7002ContractAddress.Returns(eip7002Account); + _spec.Eip7251ContractAddress.Returns(eip7251Account); + + _transactionProcessor = Substitute.For(); + + _transactionProcessor.Execute(Arg.Any(), Arg.Any(), Arg.Any()) + .Returns(ci => + { + Transaction transaction = ci.Arg(); + CallOutputTracer tracer = ci.Arg(); + if (transaction.To == eip7002Account) + { + Span buffer = new byte[_executionWithdrawalRequests.GetRequestsByteSize()]; + FlatEncodeWithoutType(_executionWithdrawalRequests, buffer); + tracer.ReturnValue = buffer.ToArray(); + } + else if (transaction.To == eip7251Account) + { + Span buffer = new byte[_executionConsolidationRequests.GetRequestsByteSize()]; + FlatEncodeWithoutType(_executionConsolidationRequests, buffer); + tracer.ReturnValue = buffer.ToArray(); + } + else + { + tracer.ReturnValue = Array.Empty(); + } + return new TransactionResult(); + }); + } + + + public static Hash256 CalculateHash( + TestExecutionRequest[] depositRequests, + TestExecutionRequest[] withdrawalRequests, + TestExecutionRequest[] consolidationRequests + ) + { + using ArrayPoolList requests = TestExecutionRequestExtensions.GetFlatEncodedRequests(depositRequests, withdrawalRequests, consolidationRequests); + return ExecutionRequestExtensions.CalculateHashFromFlatEncodedRequests(requests.ToArray()); + } + + [Test] + public void ShouldProcessExecutionRequests() + { + Block block = Build.A.Block.TestObject; + ExecutionRequestsProcessor executionRequestsProcessor = new(_transactionProcessor); + + TxReceipt[] txReceipts = [ + Build.A.Receipt.WithLogs( + CreateLogEntry(TestItem.ExecutionRequestA.RequestDataParts), + CreateLogEntry(TestItem.ExecutionRequestB.RequestDataParts), + CreateLogEntry(TestItem.ExecutionRequestC.RequestDataParts) + ).TestObject + ]; + executionRequestsProcessor.ProcessExecutionRequests(block, _stateProvider, txReceipts, _spec); + + Assert.That(block.Header.RequestsHash, Is.EqualTo( + CalculateHash(_executionDepositRequests, _executionWithdrawalRequests, _executionConsolidationRequests) + )); + + + static LogEntry CreateLogEntry(byte[][] requestDataParts) => + Build.A.LogEntry + .WithData(_abiEncoder.Encode(AbiEncodingStyle.None, _depositEventABI, requestDataParts!)) + .WithAddress(DepositContractAddress).TestObject; + } +} diff --git a/src/Nethermind/Nethermind.Consensus/ExecutionRequests/ExecutionRequestProcessor.cs b/src/Nethermind/Nethermind.Consensus/ExecutionRequests/ExecutionRequestProcessor.cs new file mode 100644 index 00000000000..46199e498da --- /dev/null +++ b/src/Nethermind/Nethermind.Consensus/ExecutionRequests/ExecutionRequestProcessor.cs @@ -0,0 +1,140 @@ +// SPDX-FileCopyrightText: 2024 Demerzel Solutions Limited +// SPDX-License-Identifier: LGPL-3.0-only + +using System; +using System.Collections.Generic; +using System.Linq; +using Nethermind.Abi; +using Nethermind.Core; +using Nethermind.Core.Collections; +using Nethermind.Core.ExecutionRequest; +using Nethermind.Core.Specs; +using Nethermind.Crypto; +using Nethermind.Evm; +using Nethermind.Evm.Tracing; +using Nethermind.Evm.TransactionProcessing; +using Nethermind.Int256; +using Nethermind.State; + +namespace Nethermind.Consensus.ExecutionRequests; + +public class ExecutionRequestsProcessor : IExecutionRequestsProcessor +{ + private readonly AbiSignature _depositEventABI = new("DepositEvent", AbiType.DynamicBytes, AbiType.DynamicBytes, AbiType.DynamicBytes, AbiType.DynamicBytes, AbiType.DynamicBytes); + private readonly AbiEncoder _abiEncoder = AbiEncoder.Instance; + + private const long GasLimit = 30_000_000L; + + private readonly ITransactionProcessor _transactionProcessor; + + private readonly Transaction _withdrawalTransaction = new() + { + Value = UInt256.Zero, + Data = Array.Empty(), + To = Eip7002Constants.WithdrawalRequestPredeployAddress, + SenderAddress = Address.SystemUser, + GasLimit = GasLimit, + GasPrice = UInt256.Zero, + }; + + private readonly Transaction _consolidationTransaction = new() + { + Value = UInt256.Zero, + Data = Array.Empty(), + To = Eip7251Constants.ConsolidationRequestPredeployAddress, + SenderAddress = Address.SystemUser, + GasLimit = GasLimit, + GasPrice = UInt256.Zero, + }; + + public ExecutionRequestsProcessor(ITransactionProcessor transactionProcessor) + { + _transactionProcessor = transactionProcessor; + _withdrawalTransaction.Hash = _withdrawalTransaction.CalculateHash(); + _consolidationTransaction.Hash = _consolidationTransaction.CalculateHash(); + } + + public byte[] ProcessDeposits(TxReceipt[] receipts, IReleaseSpec spec) + { + if (!spec.DepositsEnabled) + return Array.Empty(); + + using ArrayPoolList depositRequests = new(receipts.Length * 2); + + for (int i = 0; i < receipts.Length; i++) + { + LogEntry[]? logEntries = receipts[i].Logs; + if (logEntries is not null) + { + for (var j = 0; j < logEntries.Length; j++) + { + LogEntry log = logEntries[j]; + if (log.Address == spec.DepositContractAddress) + { + Span depositRequestBuffer = new byte[ExecutionRequestExtensions.DepositRequestsBytesSize]; + DecodeDepositRequest(log, depositRequestBuffer); + depositRequests.AddRange(depositRequestBuffer.ToArray()); + } + } + } + } + + return depositRequests.ToArray(); + } + + private void DecodeDepositRequest(LogEntry log, Span buffer) + { + object[] result = _abiEncoder.Decode(AbiEncodingStyle.None, _depositEventABI, log.Data); + int offset = 0; + + foreach (var item in result) + { + if (item is byte[] byteArray) + { + byteArray.CopyTo(buffer.Slice(offset, byteArray.Length)); + offset += byteArray.Length; + } + else + { + throw new InvalidOperationException("Decoded ABI result contains non-byte array elements."); + } + } + + // make sure the flattened result is of the correct size + if (offset != ExecutionRequestExtensions.DepositRequestsBytesSize) + { + throw new InvalidOperationException($"Decoded ABI result has incorrect size. Expected {ExecutionRequestExtensions.DepositRequestsBytesSize} bytes, got {offset} bytes."); + } + } + + + private byte[] ReadRequests(Block block, IWorldState state, IReleaseSpec spec, Address contractAddress) + { + bool isWithdrawalRequests = contractAddress == spec.Eip7002ContractAddress; + + int requestsByteSize = isWithdrawalRequests ? ExecutionRequestExtensions.WithdrawalRequestsBytesSize : ExecutionRequestExtensions.ConsolidationRequestsBytesSize; + + if (!(isWithdrawalRequests ? spec.WithdrawalRequestsEnabled : spec.ConsolidationRequestsEnabled) || !state.AccountExists(contractAddress)) + return Array.Empty(); + + CallOutputTracer tracer = new(); + + _transactionProcessor.Execute(isWithdrawalRequests ? _withdrawalTransaction : _consolidationTransaction, new BlockExecutionContext(block.Header), tracer); + + if (tracer.ReturnValue is null || tracer.ReturnValue.Length == 0) + { + return Array.Empty(); + } + + int validLength = tracer.ReturnValue.Length - (tracer.ReturnValue.Length % requestsByteSize); + return tracer.ReturnValue.AsSpan(0, validLength).ToArray(); + } + + public void ProcessExecutionRequests(Block block, IWorldState state, TxReceipt[] receipts, IReleaseSpec spec) + { + if (!spec.RequestsEnabled) + return; + block.ExecutionRequests = new byte[][] { ProcessDeposits(receipts, spec), ReadRequests(block, state, spec, spec.Eip7002ContractAddress), ReadRequests(block, state, spec, spec.Eip7251ContractAddress) }; + block.Header.RequestsHash = ExecutionRequestExtensions.CalculateHashFromFlatEncodedRequests(block.ExecutionRequests); + } +} diff --git a/src/Nethermind/Nethermind.Consensus/ExecutionRequests/IExecutionRequestProcessor.cs b/src/Nethermind/Nethermind.Consensus/ExecutionRequests/IExecutionRequestProcessor.cs new file mode 100644 index 00000000000..f0461e3a8b1 --- /dev/null +++ b/src/Nethermind/Nethermind.Consensus/ExecutionRequests/IExecutionRequestProcessor.cs @@ -0,0 +1,15 @@ +// SPDX-FileCopyrightText: 2024 Demerzel Solutions Limited +// SPDX-License-Identifier: LGPL-3.0-only + +using System.Collections.Generic; +using Nethermind.Core; +using Nethermind.Core.ExecutionRequest; +using Nethermind.Core.Specs; +using Nethermind.State; + +namespace Nethermind.Consensus.ExecutionRequests; + +public interface IExecutionRequestsProcessor +{ + public void ProcessExecutionRequests(Block block, IWorldState state, TxReceipt[] receipts, IReleaseSpec spec); +} diff --git a/src/Nethermind/Nethermind.Consensus/Messages/BlockErrorMessages.cs b/src/Nethermind/Nethermind.Consensus/Messages/BlockErrorMessages.cs index b40be7bc3aa..2c3f10a5a17 100644 --- a/src/Nethermind/Nethermind.Consensus/Messages/BlockErrorMessages.cs +++ b/src/Nethermind/Nethermind.Consensus/Messages/BlockErrorMessages.cs @@ -120,6 +120,6 @@ public static string InvalidTxInBlock(int i) => public static string MissingRequests => "MissingRequests: Requests cannot be null in block when EIP-6110 or EIP-7002 are activated."; public static string RequestsNotEnabled => "RequestsNotEnabled: Requests must be null in block when EIP-6110 and EIP-7002 are not activated."; - public static string InvalidRequestsRoot(Hash256? expected, Hash256? actual) => $"InvalidRequestsRoot: Requests root hash mismatch in block: expected {expected}, got {actual}"; + public static string InvalidRequestsHash(Hash256? expected, Hash256? actual) => $"InvalidRequestsHash: Requests hash hash mismatch in block: expected {expected}, got {actual}"; public static string InvalidRequestsOrder => "InvalidRequestsOrder: Requests are not in the correct order in block."; } diff --git a/src/Nethermind/Nethermind.Consensus/Processing/BlockProcessor.cs b/src/Nethermind/Nethermind.Consensus/Processing/BlockProcessor.cs index 8f6e94f4f01..ce1bfd2f8da 100644 --- a/src/Nethermind/Nethermind.Consensus/Processing/BlockProcessor.cs +++ b/src/Nethermind/Nethermind.Consensus/Processing/BlockProcessor.cs @@ -12,13 +12,14 @@ using Nethermind.Blockchain.BeaconBlockRoot; using Nethermind.Blockchain.Blocks; using Nethermind.Blockchain.Receipts; -using Nethermind.Consensus.Requests; +using Nethermind.Consensus.ExecutionRequests; using Nethermind.Consensus.Rewards; using Nethermind.Consensus.Validators; using Nethermind.Consensus.Withdrawals; using Nethermind.Core; using Nethermind.Core.Crypto; using Nethermind.Core.Eip2930; +using Nethermind.Core.ExecutionRequest; using Nethermind.Core.Specs; using Nethermind.Crypto; using Nethermind.Evm; @@ -46,7 +47,7 @@ public partial class BlockProcessor( IWithdrawalProcessor? withdrawalProcessor = null, IReceiptsRootCalculator? receiptsRootCalculator = null, IBlockCachePreWarmer? preWarmer = null, - IConsensusRequestsProcessor? consensusRequestsProcessor = null) + IExecutionRequestsProcessor? executionRequestsProcessor = null) : IBlockProcessor { private readonly ILogger _logger = logManager?.GetClassLogger() ?? throw new ArgumentNullException(nameof(logManager)); @@ -60,8 +61,7 @@ public partial class BlockProcessor( private readonly IRewardCalculator _rewardCalculator = rewardCalculator ?? throw new ArgumentNullException(nameof(rewardCalculator)); private readonly IBlockProcessor.IBlockTransactionsExecutor _blockTransactionsExecutor = blockTransactionsExecutor ?? throw new ArgumentNullException(nameof(blockTransactionsExecutor)); private readonly IBlockhashStore _blockhashStore = blockHashStore ?? throw new ArgumentNullException(nameof(blockHashStore)); - - private readonly IConsensusRequestsProcessor _consensusRequestsProcessor = consensusRequestsProcessor ?? new ConsensusRequestsProcessor(transactionProcessor); + private readonly IExecutionRequestsProcessor _executionRequestsProcessor = executionRequestsProcessor ?? new ExecutionRequestsProcessor(transactionProcessor); private Task _clearTask = Task.CompletedTask; private const int MaxUncommittedBlocks = 64; @@ -275,6 +275,7 @@ private void ValidateProcessedBlock(Block suggestedBlock, ProcessingOptions opti // Block is valid, copy the account changes as we use the suggested block not the processed one suggestedBlock.AccountChanges = block.AccountChanges; + suggestedBlock.ExecutionRequests = block.ExecutionRequests; } private bool ShouldComputeStateRoot(BlockHeader header) => @@ -307,7 +308,8 @@ protected virtual TxReceipt[] ProcessBlock( header.ReceiptsRoot = _receiptsRootCalculator.GetReceiptsRoot(receipts, spec, block.ReceiptsRoot); ApplyMinerRewards(block, blockTracer, spec); _withdrawalProcessor.ProcessWithdrawals(block, spec); - _consensusRequestsProcessor.ProcessRequests(block, _stateProvider, receipts, spec); + + _executionRequestsProcessor.ProcessExecutionRequests(block, _stateProvider, receipts, spec); ReceiptsTracer.EndBlockTrace(); @@ -389,7 +391,7 @@ private Block PrepareBlockForProcessing(Block suggestedBlock) ReceiptsRoot = bh.ReceiptsRoot, BaseFeePerGas = bh.BaseFeePerGas, WithdrawalsRoot = bh.WithdrawalsRoot, - RequestsRoot = bh.RequestsRoot, + RequestsHash = bh.RequestsHash, IsPostMerge = bh.IsPostMerge, ParentBeaconBlockRoot = bh.ParentBeaconBlockRoot }; diff --git a/src/Nethermind/Nethermind.Consensus/Producers/BlockProducerEnvFactory.cs b/src/Nethermind/Nethermind.Consensus/Producers/BlockProducerEnvFactory.cs index 85e5697a8be..ca92569ed11 100644 --- a/src/Nethermind/Nethermind.Consensus/Producers/BlockProducerEnvFactory.cs +++ b/src/Nethermind/Nethermind.Consensus/Producers/BlockProducerEnvFactory.cs @@ -7,8 +7,8 @@ using Nethermind.Blockchain.Receipts; using Nethermind.Config; using Nethermind.Consensus.Comparers; +using Nethermind.Consensus.ExecutionRequests; using Nethermind.Consensus.Processing; -using Nethermind.Consensus.Requests; using Nethermind.Consensus.Rewards; using Nethermind.Consensus.Transactions; using Nethermind.Consensus.Validators; @@ -35,7 +35,7 @@ public class BlockProducerEnvFactory : IBlockProducerEnvFactory protected readonly ITransactionComparerProvider _transactionComparerProvider; protected readonly IBlocksConfig _blocksConfig; protected readonly ILogManager _logManager; - private readonly IConsensusRequestsProcessor? _consensusRequestsProcessor; + private readonly IExecutionRequestsProcessor? _executionRequestsProcessor; public IBlockTransactionsExecutorFactory TransactionsExecutorFactory { get; set; } @@ -51,7 +51,7 @@ public BlockProducerEnvFactory( ITransactionComparerProvider transactionComparerProvider, IBlocksConfig blocksConfig, ILogManager logManager, - IConsensusRequestsProcessor? consensusRequestsProcessor = null) + IExecutionRequestsProcessor? executionRequestsProcessor = null) { _worldStateManager = worldStateManager; _blockTree = blockTree; @@ -64,7 +64,7 @@ public BlockProducerEnvFactory( _transactionComparerProvider = transactionComparerProvider; _blocksConfig = blocksConfig; _logManager = logManager; - _consensusRequestsProcessor = consensusRequestsProcessor; + _executionRequestsProcessor = executionRequestsProcessor; TransactionsExecutorFactory = new BlockProducerTransactionsExecutorFactory(specProvider, logManager); } @@ -159,7 +159,7 @@ protected virtual BlockProcessor CreateBlockProcessor( new BlockhashStore(_specProvider, readOnlyTxProcessingEnv.WorldState), logManager, new BlockProductionWithdrawalProcessor(new WithdrawalProcessor(readOnlyTxProcessingEnv.WorldState, logManager)), - consensusRequestsProcessor: _consensusRequestsProcessor + executionRequestsProcessor: _executionRequestsProcessor ); } } diff --git a/src/Nethermind/Nethermind.Consensus/Producers/BlockToProduce.cs b/src/Nethermind/Nethermind.Consensus/Producers/BlockToProduce.cs index 193452b87db..d52e2abdd1f 100644 --- a/src/Nethermind/Nethermind.Consensus/Producers/BlockToProduce.cs +++ b/src/Nethermind/Nethermind.Consensus/Producers/BlockToProduce.cs @@ -5,7 +5,6 @@ using System.Collections.Generic; using System.Runtime.CompilerServices; using Nethermind.Core; -using Nethermind.Core.ConsensusRequests; //TODO: Redo clique block producer [assembly: InternalsVisibleTo("Nethermind.Consensus.Clique")] @@ -33,13 +32,12 @@ internal class BlockToProduce : Block public BlockToProduce(BlockHeader blockHeader, IEnumerable transactions, IEnumerable uncles, - IEnumerable? withdrawals = null, - IEnumerable? requests = null) - : base(blockHeader, Array.Empty(), uncles, withdrawals, requests) + IEnumerable? withdrawals = null) + : base(blockHeader, Array.Empty(), uncles, withdrawals) { Transactions = transactions; } - public override Block WithReplacedHeader(BlockHeader newHeader) => new BlockToProduce(newHeader, Transactions, Uncles, Withdrawals, Requests); + public override Block WithReplacedHeader(BlockHeader newHeader) => new BlockToProduce(newHeader, Transactions, Uncles, Withdrawals); } } diff --git a/src/Nethermind/Nethermind.Consensus/Requests/ConsensusRequestsProcessor.cs b/src/Nethermind/Nethermind.Consensus/Requests/ConsensusRequestsProcessor.cs deleted file mode 100644 index cbc155d1d9c..00000000000 --- a/src/Nethermind/Nethermind.Consensus/Requests/ConsensusRequestsProcessor.cs +++ /dev/null @@ -1,39 +0,0 @@ -// SPDX-FileCopyrightText: 2024 Demerzel Solutions Limited -// SPDX-License-Identifier: LGPL-3.0-only - -using System.Collections.Generic; -using System.Linq; -using Nethermind.Core; -using Nethermind.Core.Collections; -using Nethermind.Core.ConsensusRequests; -using Nethermind.Core.Crypto; -using Nethermind.Core.Specs; -using Nethermind.Evm.TransactionProcessing; -using Nethermind.State; -using Nethermind.State.Proofs; - -namespace Nethermind.Consensus.Requests; - -public class ConsensusRequestsProcessor(ITransactionProcessor transactionProcessor) : IConsensusRequestsProcessor -{ - private readonly ConsolidationRequestsProcessor _consolidationRequestsProcessor = new(transactionProcessor); - private readonly WithdrawalRequestsProcessor _withdrawalRequestsProcessor = new(transactionProcessor); - private readonly IDepositsProcessor _depositsProcessor = new DepositsProcessor(); - - public void ProcessRequests(Block block, IWorldState state, TxReceipt[] receipts, IReleaseSpec spec) - { - if (!spec.RequestsEnabled) - return; - - using ArrayPoolList requestsList = new(receipts.Length * 2); - - requestsList.AddRange(_depositsProcessor.ProcessDeposits(block, receipts, spec)); - requestsList.AddRange(_withdrawalRequestsProcessor.ReadRequests(block, state, spec)); - requestsList.AddRange(_consolidationRequestsProcessor.ReadRequests(block, state, spec)); - - ConsensusRequest[] requests = requestsList.ToArray(); - Hash256 root = new RequestsTrie(requests).RootHash; - block.Body.Requests = requests; - block.Header.RequestsRoot = root; - } -} diff --git a/src/Nethermind/Nethermind.Consensus/Requests/ConsolidationRequestProcessor.cs b/src/Nethermind/Nethermind.Consensus/Requests/ConsolidationRequestProcessor.cs deleted file mode 100644 index 9d18024b080..00000000000 --- a/src/Nethermind/Nethermind.Consensus/Requests/ConsolidationRequestProcessor.cs +++ /dev/null @@ -1,44 +0,0 @@ -// SPDX-FileCopyrightText: 2024 Demerzel Solutions Limited -// SPDX-License-Identifier: LGPL-3.0-only - -using System; -using System.Collections.Generic; -using Nethermind.Core; -using Nethermind.Core.ConsensusRequests; -using Nethermind.Core.Specs; -using Nethermind.Evm.TransactionProcessing; -using Nethermind.State; - -namespace Nethermind.Consensus.Requests; - -// https://eips.ethereum.org/EIPS/eip-7251#block-processing -public class ConsolidationRequestsProcessor(ITransactionProcessor transactionProcessor) : RequestProcessor(transactionProcessor), IRequestProcessor -{ - private const int SizeOfClass = 20 + 48 + 48; - - public IEnumerable ReadRequests(Block block, IWorldState state, IReleaseSpec spec) - { - return base.ReadRequests(block, state, spec, spec.Eip7251ContractAddress); - } - protected override bool IsEnabledInSpec(IReleaseSpec spec) - { - return spec.ConsolidationRequestsEnabled; - } - protected override IEnumerable ParseResult(Memory result) - { - int count = result.Length / SizeOfClass; - - for (int i = 0; i < count; ++i) - { - int offset = i * SizeOfClass; - ConsolidationRequest request = new() - { - SourceAddress = new Address(result.Slice(offset, 20).ToArray()), - SourcePubkey = result.Slice(offset + 20, 48), - TargetPubkey = result.Slice(offset + 68, 48) - }; - - yield return request; - } - } -} diff --git a/src/Nethermind/Nethermind.Consensus/Requests/DepositsProcessor.cs b/src/Nethermind/Nethermind.Consensus/Requests/DepositsProcessor.cs deleted file mode 100644 index a9619bba946..00000000000 --- a/src/Nethermind/Nethermind.Consensus/Requests/DepositsProcessor.cs +++ /dev/null @@ -1,55 +0,0 @@ -// SPDX-FileCopyrightText: 2022 Demerzel Solutions Limited -// SPDX-License-Identifier: LGPL-3.0-only - -using System; -using System.Collections.Generic; -using Nethermind.Abi; -using Nethermind.Core; -using Nethermind.Core.ConsensusRequests; -using Nethermind.Core.Specs; - -namespace Nethermind.Consensus.Requests; - -public class DepositsProcessor : IDepositsProcessor -{ - private readonly AbiSignature _depositEventABI = new("DepositEvent", AbiType.DynamicBytes, AbiType.DynamicBytes, AbiType.DynamicBytes, AbiType.DynamicBytes, AbiType.DynamicBytes); - private readonly AbiEncoder _abiEncoder = AbiEncoder.Instance; - - public IEnumerable ProcessDeposits(Block block, TxReceipt[] receipts, IReleaseSpec spec) - { - if (!spec.DepositsEnabled) - { - yield break; - } - - for (int i = 0; i < receipts.Length; i++) - { - LogEntry[]? logEntries = receipts[i].Logs; - if (logEntries is not null) - { - for (var j = 0; j < logEntries.Length; j++) - { - LogEntry log = logEntries[j]; - if (log.Address == spec.DepositContractAddress) - { - yield return DecodeDeposit(log); - } - } - } - } - - Deposit DecodeDeposit(LogEntry log) - { - object[] result = _abiEncoder.Decode(AbiEncodingStyle.None, _depositEventABI, log.Data); - - return new Deposit - { - Pubkey = (byte[])result[0], - WithdrawalCredentials = (byte[])result[1], - Amount = BitConverter.ToUInt64((byte[])result[2], 0), - Signature = (byte[])result[3], - Index = BitConverter.ToUInt64((byte[])result[4], 0) - }; - } - } -} diff --git a/src/Nethermind/Nethermind.Consensus/Requests/IConsensusRequestsProcessor.cs b/src/Nethermind/Nethermind.Consensus/Requests/IConsensusRequestsProcessor.cs deleted file mode 100644 index 00ead1e8647..00000000000 --- a/src/Nethermind/Nethermind.Consensus/Requests/IConsensusRequestsProcessor.cs +++ /dev/null @@ -1,13 +0,0 @@ -// SPDX-FileCopyrightText: 2024 Demerzel Solutions Limited -// SPDX-License-Identifier: LGPL-3.0-only - -using Nethermind.Core; -using Nethermind.Core.Specs; -using Nethermind.State; - -namespace Nethermind.Consensus.Requests; - -public interface IConsensusRequestsProcessor -{ - void ProcessRequests(Block block, IWorldState state, TxReceipt[] receipts, IReleaseSpec spec); -} diff --git a/src/Nethermind/Nethermind.Consensus/Requests/IDepositsProcessor.cs b/src/Nethermind/Nethermind.Consensus/Requests/IDepositsProcessor.cs deleted file mode 100644 index f73cdaa4556..00000000000 --- a/src/Nethermind/Nethermind.Consensus/Requests/IDepositsProcessor.cs +++ /dev/null @@ -1,14 +0,0 @@ -// SPDX-FileCopyrightText: 2022 Demerzel Solutions Limited -// SPDX-License-Identifier: LGPL-3.0-only - -using System.Collections.Generic; -using Nethermind.Core; -using Nethermind.Core.ConsensusRequests; -using Nethermind.Core.Specs; - -namespace Nethermind.Consensus.Requests; - -public interface IDepositsProcessor -{ - IEnumerable ProcessDeposits(Block block, TxReceipt[] receipts, IReleaseSpec spec); -} diff --git a/src/Nethermind/Nethermind.Consensus/Requests/IRequestProcessor.cs b/src/Nethermind/Nethermind.Consensus/Requests/IRequestProcessor.cs deleted file mode 100644 index 6f33453fdfb..00000000000 --- a/src/Nethermind/Nethermind.Consensus/Requests/IRequestProcessor.cs +++ /dev/null @@ -1,14 +0,0 @@ -// SPDX-FileCopyrightText: 2024 Demerzel Solutions Limited -// SPDX-License-Identifier: LGPL-3.0-only - -using Nethermind.Core; -using Nethermind.Core.Specs; -using Nethermind.State; -using System.Collections.Generic; - -namespace Nethermind.Consensus.Requests; - -public interface IRequestProcessor -{ - IEnumerable ReadRequests(Block block, IWorldState state, IReleaseSpec spec); -} diff --git a/src/Nethermind/Nethermind.Consensus/Requests/RequestProcessor.cs b/src/Nethermind/Nethermind.Consensus/Requests/RequestProcessor.cs deleted file mode 100644 index c9c40c8dcd1..00000000000 --- a/src/Nethermind/Nethermind.Consensus/Requests/RequestProcessor.cs +++ /dev/null @@ -1,53 +0,0 @@ -// SPDX-FileCopyrightText: 2024 Demerzel Solutions Limited -// SPDX-License-Identifier: LGPL-3.0-only - -using System; -using System.Collections.Generic; -using System.Linq; -using Nethermind.Core; -using Nethermind.Core.Specs; -using Nethermind.Crypto; -using Nethermind.Evm; -using Nethermind.Evm.Tracing; -using Nethermind.Evm.TransactionProcessing; -using Nethermind.Int256; -using Nethermind.State; - -namespace Nethermind.Consensus.Requests; - -public abstract class RequestProcessor(ITransactionProcessor transactionProcessor) -{ - private const long GasLimit = 30_000_000L; - - public IEnumerable ReadRequests(Block block, IWorldState state, IReleaseSpec spec, Address contractAddress) - { - if (!IsEnabledInSpec(spec)) - return Array.Empty(); - - if (!state.AccountExists(contractAddress)) - return Array.Empty(); - - CallOutputTracer tracer = new(); - - Transaction? transaction = new() - { - Value = UInt256.Zero, - Data = Array.Empty(), - To = contractAddress, - SenderAddress = Address.SystemUser, - GasLimit = GasLimit, - GasPrice = UInt256.Zero, - }; - transaction.Hash = transaction.CalculateHash(); - - transactionProcessor.Execute(transaction, new BlockExecutionContext(block.Header), tracer); - var result = tracer.ReturnValue; - if (result == null || result.Length == 0) - return Enumerable.Empty(); - return ParseResult(tracer.ReturnValue); - } - - - protected abstract bool IsEnabledInSpec(IReleaseSpec spec); - protected abstract IEnumerable ParseResult(Memory result); -} diff --git a/src/Nethermind/Nethermind.Consensus/Requests/WithdrawalRequestsProcessor.cs b/src/Nethermind/Nethermind.Consensus/Requests/WithdrawalRequestsProcessor.cs deleted file mode 100644 index 86483add1a0..00000000000 --- a/src/Nethermind/Nethermind.Consensus/Requests/WithdrawalRequestsProcessor.cs +++ /dev/null @@ -1,46 +0,0 @@ -// SPDX-FileCopyrightText: 2024 Demerzel Solutions Limited -// SPDX-License-Identifier: LGPL-3.0-only - -using System; -using System.Buffers.Binary; -using System.Collections.Generic; -using Nethermind.Core; -using Nethermind.Core.ConsensusRequests; -using Nethermind.Core.Extensions; -using Nethermind.Core.Specs; -using Nethermind.Evm.TransactionProcessing; -using Nethermind.State; - -namespace Nethermind.Consensus.Requests; - -// https://eips.ethereum.org/EIPS/eip-7002#block-processing -public class WithdrawalRequestsProcessor(ITransactionProcessor transactionProcessor) : RequestProcessor(transactionProcessor), IRequestProcessor -{ - private const int SizeOfClass = 20 + 48 + 8; - - public IEnumerable ReadRequests(Block block, IWorldState state, IReleaseSpec spec) - { - return ReadRequests(block, state, spec, spec.Eip7002ContractAddress); - } - - protected override bool IsEnabledInSpec(IReleaseSpec spec) - { - return spec.WithdrawalRequestsEnabled; - } - - protected override IEnumerable ParseResult(Memory result) - { - int count = result.Length / SizeOfClass; - for (int i = 0; i < count; ++i) - { - int offset = i * SizeOfClass; - WithdrawalRequest request = new() - { - SourceAddress = new Address(result.Slice(offset, 20).AsArray()), - ValidatorPubkey = result.Slice(offset + 20, 48), - Amount = BinaryPrimitives.ReadUInt64BigEndian(result.Slice(offset + 68, 8).Span) - }; - yield return request; - } - } -} diff --git a/src/Nethermind/Nethermind.Consensus/Validators/BlockValidator.cs b/src/Nethermind/Nethermind.Consensus/Validators/BlockValidator.cs index 8c1edb4db43..62f5c756cdf 100644 --- a/src/Nethermind/Nethermind.Consensus/Validators/BlockValidator.cs +++ b/src/Nethermind/Nethermind.Consensus/Validators/BlockValidator.cs @@ -2,9 +2,6 @@ // SPDX-License-Identifier: LGPL-3.0-only using System; -using System.Collections.Generic; -using System.Data; -using System.Linq; using System.Text; using Nethermind.Blockchain; using Nethermind.Consensus.Messages; @@ -15,7 +12,6 @@ using Nethermind.Evm; using Nethermind.Int256; using Nethermind.Logging; -using Nethermind.Serialization.Rlp; using Nethermind.State.Proofs; using Nethermind.TxPool; @@ -138,11 +134,6 @@ public bool ValidateSuggestedBlock(Block block, out string? errorMessage, bool v { return false; } - - if (!ValidateRequests(block, spec, out errorMessage)) - { - return false; - } } return true; @@ -221,10 +212,10 @@ public bool ValidateProcessedBlock(Block processedBlock, TxReceipt[] receipts, B error ??= BlockErrorMessages.InvalidParentBeaconBlockRoot; } - if (processedBlock.Header.RequestsRoot != suggestedBlock.Header.RequestsRoot) + if (processedBlock.Header.RequestsHash != suggestedBlock.Header.RequestsHash) { - if (_logger.IsWarn) _logger.Warn($"- requests root : expected {suggestedBlock.Header.RequestsRoot}, got {processedBlock.Header.RequestsRoot}"); - error ??= BlockErrorMessages.InvalidRequestsRoot(suggestedBlock.Header.RequestsRoot, processedBlock.Header.RequestsRoot); + if (_logger.IsWarn) _logger.Warn($"- requests root : expected {suggestedBlock.Header.RequestsHash}, got {processedBlock.Header.RequestsHash}"); + error ??= BlockErrorMessages.InvalidRequestsHash(suggestedBlock.Header.RequestsHash, processedBlock.Header.RequestsHash); } for (int i = 0; i < processedBlock.Transactions.Length; i++) @@ -283,65 +274,6 @@ private bool ValidateWithdrawals(Block block, IReleaseSpec spec, out string? err return true; } - public bool ValidateRequests(Block block, out string? error) => - ValidateRequests(block, _specProvider.GetSpec(block.Header), out error); - - private bool ValidateRequests(Block block, IReleaseSpec spec, out string? error) - { - if (spec.RequestsEnabled && block.Requests is null) - { - error = BlockErrorMessages.MissingRequests; - - if (_logger.IsWarn) _logger.Warn(error); - - return false; - } - - if (!spec.RequestsEnabled && block.Requests is not null) - { - error = BlockErrorMessages.RequestsNotEnabled; - - if (_logger.IsWarn) _logger.Warn(error); - - return false; - } - - if (!ValidateRequestsHashMatches(block, out Hash256 requestsRoot)) - { - error = BlockErrorMessages.InvalidRequestsRoot(block.Header.RequestsRoot, requestsRoot); - if (_logger.IsWarn) _logger.Warn($"DepositsRoot root hash mismatch in block {block.ToString(Block.Format.FullHashAndNumber)}: expected {block.Header.RequestsRoot}, got {requestsRoot}"); - - return false; - } - - // validate that the requests types are in ascending order - if (!ValidateRequestsOrder(block, out error)) - { - if (_logger.IsWarn) _logger.Warn(error); - return false; - } - - error = null; - return true; - } - - public static bool ValidateRequestsOrder(Block block, out string? error) - { - if (block.Requests is not null) - { - for (int i = 1; i < block.Requests.Length; i++) - { - if (block.Requests[i].Type < block.Requests[i - 1].Type) - { - error = BlockErrorMessages.InvalidRequestsOrder; - return false; - } - } - } - error = null; - return true; - } - protected virtual bool ValidateTransactions(Block block, IReleaseSpec spec, out string? errorMessage) { Transaction[] transactions = block.Transactions; @@ -426,8 +358,7 @@ protected virtual bool ValidateEip4844Fields(Block block, IReleaseSpec spec, out public static bool ValidateBodyAgainstHeader(BlockHeader header, BlockBody toBeValidated) => ValidateTxRootMatchesTxs(header, toBeValidated, out _) && ValidateUnclesHashMatches(header, toBeValidated, out _) - && ValidateWithdrawalsHashMatches(header, toBeValidated, out _) - && ValidateRequestsHashMatches(header, toBeValidated, out _); + && ValidateWithdrawalsHashMatches(header, toBeValidated, out _); public static bool ValidateTxRootMatchesTxs(Block block, out Hash256 txRoot) => ValidateTxRootMatchesTxs(block.Header, block.Body, out txRoot); @@ -455,20 +386,6 @@ public static bool ValidateWithdrawalsHashMatches(BlockHeader header, BlockBody return (withdrawalsRoot = new WithdrawalTrie(body.Withdrawals).RootHash) == header.WithdrawalsRoot; } - public static bool ValidateRequestsHashMatches(Block block, out Hash256? requestsRoot) => - ValidateRequestsHashMatches(block.Header, block.Body, out requestsRoot); - - private static bool ValidateRequestsHashMatches(BlockHeader header, BlockBody body, out Hash256? requestsRoot) - { - if (body.Requests == null) - { - requestsRoot = null; - return header.RequestsRoot is null; - } - - return (requestsRoot = new RequestsTrie(body.Requests).RootHash) == header.RequestsRoot; - } - private static string Invalid(Block block) => $"Invalid block {block.ToString(Block.Format.FullHashAndNumber)}:"; } diff --git a/src/Nethermind/Nethermind.Consensus/Validators/HeaderValidator.cs b/src/Nethermind/Nethermind.Consensus/Validators/HeaderValidator.cs index 2605b291631..58ae2a709b3 100644 --- a/src/Nethermind/Nethermind.Consensus/Validators/HeaderValidator.cs +++ b/src/Nethermind/Nethermind.Consensus/Validators/HeaderValidator.cs @@ -91,7 +91,31 @@ public virtual bool Validate(BlockHeader header, BlockHeader? parent, bool isUnc && ValidateTimestamp(header, parent, ref error) && ValidateBlockNumber(header, parent, ref error) && Validate1559(header, parent, spec, ref error) - && ValidateBlobGasFields(header, parent, spec, ref error); + && ValidateBlobGasFields(header, parent, spec, ref error) + && ValidateRequestsHash(header, spec, ref error); + } + + private bool ValidateRequestsHash(BlockHeader header, IReleaseSpec spec, ref string? error) + { + if (spec.RequestsEnabled) + { + if (header.RequestsHash is null) + { + if (_logger.IsWarn) _logger.Warn("RequestsHash field is not set."); + error = BlockErrorMessages.MissingRequests; + return false; + } + } + else + { + if (header.RequestsHash is not null) + { + if (_logger.IsWarn) _logger.Warn("RequestsHash field should not have value."); + error = BlockErrorMessages.RequestsNotEnabled; + return false; + } + } + return true; } protected virtual bool Validate1559(BlockHeader header, BlockHeader parent, IReleaseSpec spec, ref string? error) diff --git a/src/Nethermind/Nethermind.Core.Test/Blockchain/TestBlockchain.cs b/src/Nethermind/Nethermind.Core.Test/Blockchain/TestBlockchain.cs index 982c9190a8c..379a163ad88 100644 --- a/src/Nethermind/Nethermind.Core.Test/Blockchain/TestBlockchain.cs +++ b/src/Nethermind/Nethermind.Core.Test/Blockchain/TestBlockchain.cs @@ -15,13 +15,14 @@ using Nethermind.Config; using Nethermind.Consensus; using Nethermind.Consensus.Comparers; +using Nethermind.Consensus.ExecutionRequests; using Nethermind.Consensus.Processing; using Nethermind.Consensus.Producers; -using Nethermind.Consensus.Requests; using Nethermind.Consensus.Rewards; using Nethermind.Consensus.Transactions; using Nethermind.Consensus.Validators; using Nethermind.Core.Crypto; +using Nethermind.Core.ExecutionRequest; using Nethermind.Core.Extensions; using Nethermind.Core.Specs; using Nethermind.Core.Test.Builders; @@ -121,7 +122,7 @@ protected TestBlockchain() public ProducedBlockSuggester Suggester { get; protected set; } = null!; - public IConsensusRequestsProcessor? ConsensusRequestsProcessor { get; protected set; } = null!; + public IExecutionRequestsProcessor? ExecutionRequestsProcessor { get; protected set; } = null!; public ChainLevelInfoRepository ChainLevelInfoRepository { get; protected set; } = null!; public static TransactionBuilder BuildSimpleTransaction => Builders.Build.A.Transaction.SignedAndResolved(TestItem.PrivateKeyA).To(AccountB); @@ -366,10 +367,9 @@ protected virtual Block GetGenesisBlock() if (SpecProvider.GenesisSpec.RequestsEnabled) { - genesisBlockBuilder.WithConsensusRequests(0); + genesisBlockBuilder.WithEmptyRequestsHash(); } - genesisBlockBuilder.WithStateRoot(State.StateRoot); return genesisBlockBuilder.TestObject; } @@ -394,7 +394,7 @@ protected virtual IBlockProcessor CreateBlockProcessor() => new BlockhashStore(SpecProvider, State), LogManager, preWarmer: CreateBlockCachePreWarmer(), - consensusRequestsProcessor: ConsensusRequestsProcessor); + executionRequestsProcessor: ExecutionRequestsProcessor); protected virtual IBlockCachePreWarmer CreateBlockCachePreWarmer() => diff --git a/src/Nethermind/Nethermind.Core.Test/Builders/BlockBuilder.cs b/src/Nethermind/Nethermind.Core.Test/Builders/BlockBuilder.cs index 4b5e591949b..e2de33c5a8c 100644 --- a/src/Nethermind/Nethermind.Core.Test/Builders/BlockBuilder.cs +++ b/src/Nethermind/Nethermind.Core.Test/Builders/BlockBuilder.cs @@ -3,8 +3,10 @@ using System; using System.Linq; -using Nethermind.Core.ConsensusRequests; +using DotNetty.Common.Utilities; +using Nethermind.Core.Collections; using Nethermind.Core.Crypto; +using Nethermind.Core.ExecutionRequest; using Nethermind.Core.Specs; using Nethermind.Crypto; using Nethermind.Int256; @@ -248,6 +250,13 @@ public BlockBuilder WithReceiptsRoot(Hash256 keccak) return this; } + public BlockBuilder WithEmptyRequestsHash() + { + TestObjectInternal.Header.RequestsHash = ExecutionRequestExtensions.EmptyRequestsHash; + TestObjectInternal.ExecutionRequests = ExecutionRequestExtensions.EmptyRequests; + return this; + } + public BlockBuilder WithGasUsed(long gasUsed) { TestObjectInternal.Header.GasUsed = gasUsed; @@ -276,28 +285,6 @@ public BlockBuilder WithWithdrawals(params Withdrawal[]? withdrawals) return this; } - public BlockBuilder WithConsensusRequests(int count) - { - var consensusRequests = new ConsensusRequest[count]; - - for (var i = 0; i < count; i++) - consensusRequests[i] = new Deposit(); - - return WithConsensusRequests(consensusRequests); - } - - public BlockBuilder WithConsensusRequests(params ConsensusRequest[]? requests) - { - TestObjectInternal = TestObjectInternal - .WithReplacedBody(TestObjectInternal.Body.WithChangedConsensusRequests(requests)); - - TestObjectInternal.Header.RequestsRoot = requests is null - ? null - : new RequestsTrie(requests).RootHash; - - return this; - } - public BlockBuilder WithParentBeaconBlockRoot(Hash256? parentBeaconBlockRoot) { TestObjectInternal.Header.ParentBeaconBlockRoot = parentBeaconBlockRoot; diff --git a/src/Nethermind/Nethermind.Core.Test/Builders/BlockHeaderBuilder.cs b/src/Nethermind/Nethermind.Core.Test/Builders/BlockHeaderBuilder.cs index 81d12c7a463..f36678b4087 100644 --- a/src/Nethermind/Nethermind.Core.Test/Builders/BlockHeaderBuilder.cs +++ b/src/Nethermind/Nethermind.Core.Test/Builders/BlockHeaderBuilder.cs @@ -196,9 +196,9 @@ public BlockHeaderBuilder WithParentBeaconBlockRoot(Hash256? parentBeaconBlockRo return this; } - public BlockHeaderBuilder WithRequestsRoot(Hash256? requestsRoot) + public BlockHeaderBuilder WithRequestsHash(Hash256? requestsHash) { - TestObjectInternal.RequestsRoot = requestsRoot; + TestObjectInternal.RequestsHash = requestsHash; return this; } } diff --git a/src/Nethermind/Nethermind.Core.Test/Builders/Build.Deposit.cs b/src/Nethermind/Nethermind.Core.Test/Builders/Build.Deposit.cs deleted file mode 100644 index f8eda2c30dd..00000000000 --- a/src/Nethermind/Nethermind.Core.Test/Builders/Build.Deposit.cs +++ /dev/null @@ -1,9 +0,0 @@ -// SPDX-FileCopyrightText: 2022 Demerzel Solutions Limited -// SPDX-License-Identifier: LGPL-3.0-only - -namespace Nethermind.Core.Test.Builders; - -public partial class Build -{ - public DepositBuilder Deposit => new(); -} diff --git a/src/Nethermind/Nethermind.Core.Test/Builders/Build.WithdrawalRequest.cs b/src/Nethermind/Nethermind.Core.Test/Builders/Build.WithdrawalRequest.cs deleted file mode 100644 index a6ac89905d4..00000000000 --- a/src/Nethermind/Nethermind.Core.Test/Builders/Build.WithdrawalRequest.cs +++ /dev/null @@ -1,9 +0,0 @@ -// SPDX-FileCopyrightText: 2022 Demerzel Solutions Limited -// SPDX-License-Identifier: LGPL-3.0-only - -namespace Nethermind.Core.Test.Builders; - -public partial class Build -{ - public WithdrawalRequestBuilder WithdrawalRequest => new(); -} diff --git a/src/Nethermind/Nethermind.Core.Test/Builders/ConsolidationRequestBuilder.cs b/src/Nethermind/Nethermind.Core.Test/Builders/ConsolidationRequestBuilder.cs deleted file mode 100644 index 63628ef305b..00000000000 --- a/src/Nethermind/Nethermind.Core.Test/Builders/ConsolidationRequestBuilder.cs +++ /dev/null @@ -1,32 +0,0 @@ -// SPDX-FileCopyrightText: 2022 Demerzel Solutions Limited -// SPDX-License-Identifier: LGPL-3.0-only - -namespace Nethermind.Core.Test.Builders; -using Nethermind.Core.ConsensusRequests; - -public class ConsolidationRequestBuilder : BuilderBase -{ - public ConsolidationRequestBuilder() => TestObject = new(); - - public ConsolidationRequestBuilder WithSourceAddress(Address sourceAddress) - { - TestObject.SourceAddress = sourceAddress; - - return this; - } - - public ConsolidationRequestBuilder WithSourcePubkey(byte[] SourcePubkey) - { - TestObject.SourcePubkey = SourcePubkey; - - return this; - } - - public ConsolidationRequestBuilder WithTargetPubkey(byte[] TargetPubkey) - { - TestObject.TargetPubkey = TargetPubkey; - - return this; - } - -} diff --git a/src/Nethermind/Nethermind.Core.Test/Builders/DepositBuilder.cs b/src/Nethermind/Nethermind.Core.Test/Builders/DepositBuilder.cs deleted file mode 100644 index 48a06b77f8e..00000000000 --- a/src/Nethermind/Nethermind.Core.Test/Builders/DepositBuilder.cs +++ /dev/null @@ -1,45 +0,0 @@ -// SPDX-FileCopyrightText: 2022 Demerzel Solutions Limited -// SPDX-License-Identifier: LGPL-3.0-only - -using Nethermind.Core.ConsensusRequests; - -namespace Nethermind.Core.Test.Builders; - -public class DepositBuilder : BuilderBase -{ - public DepositBuilder() => TestObject = new(); - - public DepositBuilder WithAmount(ulong amount) - { - TestObject.Amount = amount; - - return this; - } - - public DepositBuilder WithIndex(ulong index) - { - TestObject.Index = index; - - return this; - } - - public DepositBuilder WithWithdrawalCredentials(byte[] withdrawalCredentials) - { - TestObject.WithdrawalCredentials = withdrawalCredentials; - - return this; - } - - public DepositBuilder WithSignature(byte[] signature) - { - TestObject.Signature = signature; - - return this; - } - public DepositBuilder WithPublicKey(byte[] pubKey) - { - TestObject.Pubkey = pubKey; - - return this; - } -} diff --git a/src/Nethermind/Nethermind.Core.Test/Builders/TestExecutionRequest.cs b/src/Nethermind/Nethermind.Core.Test/Builders/TestExecutionRequest.cs new file mode 100644 index 00000000000..532c78d1b7e --- /dev/null +++ b/src/Nethermind/Nethermind.Core.Test/Builders/TestExecutionRequest.cs @@ -0,0 +1,54 @@ +// SPDX-FileCopyrightText: 2024 Demerzel Solutions Limited +// SPDX-License-Identifier: LGPL-3.0-only + +using System; +using System.Linq; +using Nethermind.Core.Collections; +using Nethermind.Core.ExecutionRequest; +using Nethermind.Core.Extensions; + +namespace Nethermind.Core.Test.Builders; + +public class TestExecutionRequest : ExecutionRequest.ExecutionRequest +{ + private byte[][]? _requestDataParts; + + public byte[][]? RequestDataParts + { + get => _requestDataParts; + set + { + _requestDataParts = value; + RequestData = value is null ? null : Bytes.Concat(value.AsSpan()); + } + } +} + +public static class TestExecutionRequestExtensions +{ + public static ArrayPoolList GetFlatEncodedRequests( + TestExecutionRequest[] depositRequests, + TestExecutionRequest[] withdrawalRequests, + TestExecutionRequest[] consolidationRequests + ) + { + return new(ExecutionRequestExtensions.RequestPartsCount) + { + FlatEncodeRequests(depositRequests, depositRequests.Length * ExecutionRequestExtensions.DepositRequestsBytesSize), + FlatEncodeRequests(withdrawalRequests, withdrawalRequests.Length * ExecutionRequestExtensions.WithdrawalRequestsBytesSize), + FlatEncodeRequests(consolidationRequests, consolidationRequests.Length * ExecutionRequestExtensions.ConsolidationRequestsBytesSize) + }; + + static byte[] FlatEncodeRequests(TestExecutionRequest[] requests, int bufferSize) + { + using ArrayPoolList buffer = new(bufferSize); + + foreach (TestExecutionRequest request in requests) + { + buffer.AddRange(request.RequestData!); + } + + return buffer.ToArray(); + } + } +} diff --git a/src/Nethermind/Nethermind.Core.Test/Builders/TestItem.cs b/src/Nethermind/Nethermind.Core.Test/Builders/TestItem.cs index 65cd94de826..e922f4971d1 100644 --- a/src/Nethermind/Nethermind.Core.Test/Builders/TestItem.cs +++ b/src/Nethermind/Nethermind.Core.Test/Builders/TestItem.cs @@ -2,12 +2,12 @@ // SPDX-License-Identifier: LGPL-3.0-only using System; -using System.IO; +using System.Linq; using System.Net; -using System.Text.Json; -using Nethermind.Core.ConsensusRequests; +using DotNetty.Common.Utilities; using Nethermind.Core.Crypto; using Nethermind.Crypto; +using Nethermind.Evm.Precompiles.Bls; using Nethermind.Int256; using Nethermind.Serialization.Rlp; @@ -110,27 +110,17 @@ public static Hash256 KeccakFromNumber(int i) public static Withdrawal WithdrawalE_5Eth = new() { Address = AddressE, Index = 5, ValidatorIndex = 2005, AmountInGwei = 5_000_000_000 }; public static Withdrawal WithdrawalF_6Eth = new() { Address = AddressF, Index = 6, ValidatorIndex = 2006, AmountInGwei = 6_000_000_000 }; - public static Deposit DepositA_1Eth = new() { Index = 1, Pubkey = PublicKeyA.Bytes, Amount = 1_000_000_000, WithdrawalCredentials = AddressA.Bytes, Signature = KeccakA.Bytes.ToArray() }; - public static Deposit DepositB_2Eth = new() { Index = 2, Pubkey = PublicKeyB.Bytes, Amount = 2_000_000_000, WithdrawalCredentials = AddressB.Bytes, Signature = KeccakB.Bytes.ToArray() }; - public static Deposit DepositC_3Eth = new() { Index = 3, Pubkey = PublicKeyC.Bytes, Amount = 3_000_000_000, WithdrawalCredentials = AddressC.Bytes, Signature = KeccakC.Bytes.ToArray() }; - public static Deposit DepositD_4Eth = new() { Index = 4, Pubkey = PublicKeyD.Bytes, Amount = 4_000_000_000, WithdrawalCredentials = AddressD.Bytes, Signature = KeccakD.Bytes.ToArray() }; - public static Deposit DepositE_5Eth = new() { Index = 5, Pubkey = PublicKeyE.Bytes, Amount = 5_000_000_000, WithdrawalCredentials = AddressE.Bytes, Signature = KeccakE.Bytes.ToArray() }; - public static Deposit DepositF_6Eth = new() { Index = 6, Pubkey = PublicKeyF.Bytes, Amount = 6_000_000_000, WithdrawalCredentials = AddressF.Bytes, Signature = KeccakF.Bytes.ToArray() }; - - - public static WithdrawalRequest WithdrawalRequestA = new() { SourceAddress = AddressA, ValidatorPubkey = PublicKeyA.Bytes }; - public static WithdrawalRequest WithdrawalRequestB = new() { SourceAddress = AddressB, ValidatorPubkey = PublicKeyB.Bytes }; - public static WithdrawalRequest WithdrawalRequestC = new() { SourceAddress = AddressC, ValidatorPubkey = PublicKeyC.Bytes }; - public static WithdrawalRequest WithdrawalRequestD = new() { SourceAddress = AddressD, ValidatorPubkey = PublicKeyD.Bytes }; - public static WithdrawalRequest WithdrawalRequestE = new() { SourceAddress = AddressE, ValidatorPubkey = PublicKeyE.Bytes }; - public static WithdrawalRequest WithdrawalRequestF = new() { SourceAddress = AddressF, ValidatorPubkey = PublicKeyF.Bytes }; - - public static ConsolidationRequest ConsolidationRequestA = new() { SourceAddress = AddressA, SourcePubkey = PublicKeyA.Bytes, TargetPubkey = PublicKeyB.Bytes }; - public static ConsolidationRequest ConsolidationRequestB = new() { SourceAddress = AddressB, SourcePubkey = PublicKeyB.Bytes, TargetPubkey = PublicKeyC.Bytes }; - public static ConsolidationRequest ConsolidationRequestC = new() { SourceAddress = AddressC, SourcePubkey = PublicKeyC.Bytes, TargetPubkey = PublicKeyD.Bytes }; - public static ConsolidationRequest ConsolidationRequestD = new() { SourceAddress = AddressD, SourcePubkey = PublicKeyD.Bytes, TargetPubkey = PublicKeyE.Bytes }; - public static ConsolidationRequest ConsolidationRequestE = new() { SourceAddress = AddressE, SourcePubkey = PublicKeyE.Bytes, TargetPubkey = PublicKeyF.Bytes }; - public static ConsolidationRequest ConsolidationRequestF = new() { SourceAddress = AddressF, SourcePubkey = PublicKeyF.Bytes, TargetPubkey = PublicKeyA.Bytes }; + public static byte[] SignatureBytes = [.. new Signature("0x9242685bf161793cc25603c231bc2f568eb630ea16aa137d2664ac80388256084f8ae3bd7535248d0bd448298cc2e2071e56992d0774dc340c368ae950852ada1c").Bytes, .. KeccakA.Bytes]; + + public static TestExecutionRequest ExecutionRequestA = new() { RequestType = 0, RequestDataParts = [PublicKeyA.Bytes.Slice(0, 48), KeccakA.Bytes.ToArray(), BitConverter.GetBytes((ulong)1_000_000_000), SignatureBytes, BitConverter.GetBytes((ulong)1)] }; + public static TestExecutionRequest ExecutionRequestB = new() { RequestType = 0, RequestDataParts = [PublicKeyB.Bytes.Slice(0, 48), KeccakB.Bytes.ToArray(), BitConverter.GetBytes((ulong)2_000_000_000), SignatureBytes, BitConverter.GetBytes((ulong)2)] }; + public static TestExecutionRequest ExecutionRequestC = new() { RequestType = 0, RequestDataParts = [PublicKeyC.Bytes.Slice(0, 48), KeccakC.Bytes.ToArray(), BitConverter.GetBytes((ulong)3_000_000_000), SignatureBytes, BitConverter.GetBytes((ulong)3)] }; + public static TestExecutionRequest ExecutionRequestD = new() { RequestType = 1, RequestDataParts = [AddressA.Bytes, PublicKeyA.Bytes.Slice(0, 48), BitConverter.GetBytes((ulong)1_000_000_000)] }; + public static TestExecutionRequest ExecutionRequestE = new() { RequestType = 1, RequestDataParts = [AddressB.Bytes, PublicKeyB.Bytes.Slice(0, 48), BitConverter.GetBytes((ulong)2_000_000_000)] }; + public static TestExecutionRequest ExecutionRequestF = new() { RequestType = 1, RequestDataParts = [AddressC.Bytes, PublicKeyC.Bytes.Slice(0, 48), BitConverter.GetBytes((ulong)3_000_000_000)] }; + public static TestExecutionRequest ExecutionRequestG = new() { RequestType = 2, RequestDataParts = [AddressA.Bytes, PublicKeyA.Bytes.Slice(0, 48), PublicKeyB.Bytes.Slice(0, 48)] }; + public static TestExecutionRequest ExecutionRequestH = new() { RequestType = 2, RequestDataParts = [AddressB.Bytes, PublicKeyB.Bytes.Slice(0, 48), PublicKeyC.Bytes.Slice(0, 48)] }; + public static TestExecutionRequest ExecutionRequestI = new() { RequestType = 2, RequestDataParts = [AddressC.Bytes, PublicKeyC.Bytes.Slice(0, 48), PublicKeyA.Bytes.Slice(0, 48)] }; public static IPEndPoint IPEndPointA = IPEndPoint.Parse("10.0.0.1"); public static IPEndPoint IPEndPointB = IPEndPoint.Parse("10.0.0.2"); diff --git a/src/Nethermind/Nethermind.Core.Test/Builders/WithdrawalRequestBuilder.cs b/src/Nethermind/Nethermind.Core.Test/Builders/WithdrawalRequestBuilder.cs deleted file mode 100644 index 4a80e64beca..00000000000 --- a/src/Nethermind/Nethermind.Core.Test/Builders/WithdrawalRequestBuilder.cs +++ /dev/null @@ -1,33 +0,0 @@ -// SPDX-FileCopyrightText: 2022 Demerzel Solutions Limited -// SPDX-License-Identifier: LGPL-3.0-only - -namespace Nethermind.Core.Test.Builders; -using Nethermind.Core.ConsensusRequests; - -public class WithdrawalRequestBuilder : BuilderBase -{ - public WithdrawalRequestBuilder() => TestObject = new(); - - - public WithdrawalRequestBuilder WithAmount(ulong amount) - { - TestObject.Amount = amount; - - return this; - } - - public WithdrawalRequestBuilder WithSourceAddress(Address sourceAddress) - { - TestObject.SourceAddress = sourceAddress; - - return this; - } - - public WithdrawalRequestBuilder WithValidatorPubkey(byte[] ValidatorPubkey) - { - TestObject.ValidatorPubkey = ValidatorPubkey; - - return this; - } - -} diff --git a/src/Nethermind/Nethermind.Core.Test/Encoding/BlockDecoderTests.cs b/src/Nethermind/Nethermind.Core.Test/Encoding/BlockDecoderTests.cs index e4ced1ba301..47335ed1726 100644 --- a/src/Nethermind/Nethermind.Core.Test/Encoding/BlockDecoderTests.cs +++ b/src/Nethermind/Nethermind.Core.Test/Encoding/BlockDecoderTests.cs @@ -3,7 +3,6 @@ using System; using System.IO; -using Nethermind.Core.ConsensusRequests; using Nethermind.Core.Crypto; using Nethermind.Core.Extensions; using Nethermind.Core.Test.Builders; @@ -40,32 +39,6 @@ public BlockDecoderTests() .TestObject; } - var requests = new ConsensusRequest[8]; - - for (var i = 0; i < requests.Length; i++) - { - if (i % 2 == 0) - { - requests[i] = Build.A.Deposit - .WithIndex(long.MaxValue) - .WithPublicKey(new byte[] { (byte)i }) - .WithSignature(new byte[] { (byte)i }) - .WithWithdrawalCredentials(new byte[] { (byte)i }) - .WithAmount(int.MaxValue) - .TestObject; - } - else - { - byte[] ValidatorPubkey = new byte[48]; - ValidatorPubkey[11] = 11; - requests[i] = Build.A.WithdrawalRequest - .WithSourceAddress(TestItem.AddressA) - .WithValidatorPubkey(ValidatorPubkey) - .WithAmount(int.MaxValue) - .TestObject; - } - } - _scenarios = new[] { Build.A.Block.WithNumber(1).TestObject, @@ -120,7 +93,6 @@ public BlockDecoderTests() .WithBlobGasUsed(ulong.MaxValue) .WithExcessBlobGas(ulong.MaxValue) .WithMixHash(Keccak.EmptyTreeHash) - .WithConsensusRequests(requests) .TestObject }; } diff --git a/src/Nethermind/Nethermind.Core.Test/Encoding/ConsensusRequestDecoderTests.cs b/src/Nethermind/Nethermind.Core.Test/Encoding/ConsensusRequestDecoderTests.cs deleted file mode 100644 index c311fb36a7f..00000000000 --- a/src/Nethermind/Nethermind.Core.Test/Encoding/ConsensusRequestDecoderTests.cs +++ /dev/null @@ -1,214 +0,0 @@ -// SPDX-FileCopyrightText: 2022 Demerzel Solutions Limited -// SPDX-License-Identifier: LGPL-3.0-only - -using System; -using FluentAssertions; -using Nethermind.Core.ConsensusRequests; -using Nethermind.Core.Extensions; -using Nethermind.Evm.Tracing.GethStyle.Custom.JavaScript; -using Nethermind.Serialization.Rlp; -using NUnit.Framework; -using Nethermind.Core.Test.Builders; - -namespace Nethermind.Core.Test.Encoding; - -public class ConsensusRequestDecoderTests -{ - [Test] - public void Roundtrip_deposit() - { - ConsensusRequest deposit = new Deposit() - { - Index = long.MaxValue, - Pubkey = KeccakTests.KeccakOfAnEmptyString.ToBytes(), - Signature = KeccakTests.KeccakOfAnEmptyString.ToBytes(), - WithdrawalCredentials = KeccakTests.KeccakOfAnEmptyString.ToBytes(), - Amount = int.MaxValue - }; - - byte[] rlp = Rlp.Encode(deposit).Bytes; - ConsensusRequest decoded = Rlp.Decode(rlp); - - decoded.Should().BeEquivalentTo(deposit); - } - - [Test] - public void Roundtrip_withdrawalRequest() - { - byte[] ValidatorPubkey = new byte[48]; - ValidatorPubkey[11] = 11; - ConsensusRequest withdrawalRequest = new WithdrawalRequest() - { - SourceAddress = TestItem.AddressA, - ValidatorPubkey = ValidatorPubkey, - Amount = int.MaxValue - }; - - byte[] rlp = Rlp.Encode(withdrawalRequest).Bytes; - ConsensusRequest decoded = Rlp.Decode(rlp); - - decoded.Should().BeEquivalentTo(withdrawalRequest); - } - - [Test] - public void Roundtrip_consolidationRequest() - { - byte[] SourcePubkey = new byte[48]; - SourcePubkey[11] = 11; - byte[] TargetPubkey = new byte[48]; - TargetPubkey[22] = 22; - ConsensusRequest consolidationRequest = new ConsolidationRequest() - { - SourceAddress = TestItem.AddressA, - SourcePubkey = SourcePubkey, - TargetPubkey = TargetPubkey - }; - - byte[] rlp = Rlp.Encode(consolidationRequest).Bytes; - ConsensusRequest decoded = Rlp.Decode(rlp); - - decoded.Should().BeEquivalentTo(consolidationRequest); - } - - [Test] - public void Should_decode_deposit_with_ValueDecoderContext() - { - ConsensusRequest deposit = new Deposit() - { - Index = long.MaxValue, - Pubkey = KeccakTests.KeccakOfAnEmptyString.ToBytes(), - Signature = KeccakTests.KeccakOfAnEmptyString.ToBytes(), - WithdrawalCredentials = KeccakTests.KeccakOfAnEmptyString.ToBytes(), - Amount = int.MaxValue - }; - RlpStream stream = new(1024); - ConsensusRequestDecoder codec = ConsensusRequestDecoder.Instance; - - codec.Encode(stream, deposit); - - Rlp.ValueDecoderContext decoderContext = new(stream.Data.AsSpan()); - Deposit? decoded = (Deposit?)codec.Decode(ref decoderContext); - - decoded.Should().BeEquivalentTo(deposit); - } - - [Test] - public void Should_decode_withdrawalRequest_with_ValueDecoderContext() - { - ConsensusRequest withdrawalRequest = new WithdrawalRequest() - { - SourceAddress = TestItem.AddressA, - ValidatorPubkey = KeccakTests.KeccakOfAnEmptyString.ToBytes(), - Amount = int.MaxValue - }; - RlpStream stream = new(1024); - ConsensusRequestDecoder codec = ConsensusRequestDecoder.Instance; - - codec.Encode(stream, withdrawalRequest); - - Rlp.ValueDecoderContext decoderContext = new(stream.Data.AsSpan()); - WithdrawalRequest? decoded = (WithdrawalRequest?)codec.Decode(ref decoderContext); - - decoded.Should().BeEquivalentTo(withdrawalRequest); - } - - [Test] - public void Should_decode_consolidationRequest_with_ValueDecoderContext() - { - ConsensusRequest consolidationRequest = new ConsolidationRequest() - { - SourceAddress = TestItem.AddressA, - SourcePubkey = KeccakTests.KeccakOfAnEmptyString.ToBytes(), - TargetPubkey = KeccakTests.KeccakOfAnEmptyString.ToBytes() - }; - RlpStream stream = new(1024); - ConsensusRequestDecoder codec = ConsensusRequestDecoder.Instance; - - codec.Encode(stream, consolidationRequest); - - Rlp.ValueDecoderContext decoderContext = new(stream.Data.AsSpan()); - ConsolidationRequest? decoded = (ConsolidationRequest?)codec.Decode(ref decoderContext); - - decoded.Should().BeEquivalentTo(consolidationRequest); - } - - [Test] - public void Should_encode_deposit_same_for_Rlp_Encode_and_ConsensusRequestDecoder_Encode() - { - ConsensusRequest deposit = new Deposit() - { - Index = long.MaxValue, - Pubkey = KeccakTests.KeccakOfAnEmptyString.ToBytes(), - Signature = KeccakTests.KeccakOfAnEmptyString.ToBytes(), - WithdrawalCredentials = KeccakTests.KeccakOfAnEmptyString.ToBytes(), - Amount = int.MaxValue - }; - byte[] rlp1 = ConsensusRequestDecoder.Instance.Encode(deposit).Bytes; - byte[] rlp2 = Rlp.Encode(deposit).Bytes; - - rlp1.Should().BeEquivalentTo(rlp2); - } - - [Test] - public void Should_encode_withdrawalRequest_same_for_Rlp_Encode_and_ConsensusRequestDecoder_Encode() - { - ConsensusRequest withdrawalRequest = new WithdrawalRequest() - { - SourceAddress = TestItem.AddressA, - ValidatorPubkey = KeccakTests.KeccakOfAnEmptyString.ToBytes(), - Amount = int.MaxValue - }; - byte[] rlp1 = ConsensusRequestDecoder.Instance.Encode(withdrawalRequest).Bytes; - byte[] rlp2 = Rlp.Encode(withdrawalRequest).Bytes; - - rlp1.Should().BeEquivalentTo(rlp2); - } - - [Test] - public void Should_encode_consolidationRequest_same_for_Rlp_Encode_and_ConsensusRequestDecoder_Encode() - { - ConsensusRequest consolidationRequest = new ConsolidationRequest() - { - SourceAddress = TestItem.AddressA, - SourcePubkey = KeccakTests.KeccakOfAnEmptyString.ToBytes(), - TargetPubkey = KeccakTests.KeccakOfAnEmptyString.ToBytes() - }; - byte[] rlp1 = ConsensusRequestDecoder.Instance.Encode(consolidationRequest).Bytes; - byte[] rlp2 = Rlp.Encode(consolidationRequest).Bytes; - - rlp1.Should().BeEquivalentTo(rlp2); - } - - [Test] - public void Should_encode_ConsensusRequests_Array() - { - ConsensusRequest[] requests = new ConsensusRequest[] - { - new Deposit() - { - Index = long.MaxValue, - Pubkey = KeccakTests.KeccakOfAnEmptyString.ToBytes(), - Signature = KeccakTests.KeccakOfAnEmptyString.ToBytes(), - WithdrawalCredentials = KeccakTests.KeccakOfAnEmptyString.ToBytes(), - Amount = int.MaxValue - }, - new WithdrawalRequest() - { - SourceAddress = TestItem.AddressA, - ValidatorPubkey = KeccakTests.KeccakOfAnEmptyString.ToBytes(), - Amount = int.MaxValue - }, - new ConsolidationRequest() - { - SourceAddress = TestItem.AddressA, - SourcePubkey = KeccakTests.KeccakOfAnEmptyString.ToBytes(), - TargetPubkey = KeccakTests.KeccakOfAnEmptyString.ToBytes() - } - }; - - byte[] rlp = Rlp.Encode(requests).Bytes; - RlpStream rlpStream = new(rlp); - ConsensusRequest[] decoded = Rlp.DecodeArray(rlpStream, ConsensusRequestDecoder.Instance); - decoded.Should().BeEquivalentTo(requests); - } -} diff --git a/src/Nethermind/Nethermind.Core.Test/Encoding/HeaderDecoderTests.cs b/src/Nethermind/Nethermind.Core.Test/Encoding/HeaderDecoderTests.cs index 71d51a66333..26859ba2874 100644 --- a/src/Nethermind/Nethermind.Core.Test/Encoding/HeaderDecoderTests.cs +++ b/src/Nethermind/Nethermind.Core.Test/Encoding/HeaderDecoderTests.cs @@ -164,7 +164,7 @@ public void Can_encode_decode_with_WithdrawalRequestRoot() .WithBlobGasUsed(0) .WithExcessBlobGas(0) .WithParentBeaconBlockRoot(TestItem.KeccakB) - .WithRequestsRoot(Keccak.Zero).TestObject; + .WithRequestsHash(Keccak.Zero).TestObject; Rlp rlp = Rlp.Encode(header); BlockHeader blockHeader = Rlp.Decode(rlp.Bytes.AsSpan()); @@ -182,12 +182,12 @@ public void Can_encode_decode_with_ValidatorExitRoot_equals_to_null() .WithBlobGasUsed(0) .WithExcessBlobGas(0) .WithParentBeaconBlockRoot(TestItem.KeccakB) - .WithRequestsRoot(Keccak.Zero).TestObject; + .WithRequestsHash(Keccak.Zero).TestObject; Rlp rlp = Rlp.Encode(header); BlockHeader blockHeader = Rlp.Decode(rlp.Bytes.AsSpan()); - blockHeader.ParentBeaconBlockRoot.Should().Be(TestItem.KeccakB); + blockHeader.Should().BeEquivalentTo(header); } public static IEnumerable CancunFieldsSource() diff --git a/src/Nethermind/Nethermind.Core/Block.cs b/src/Nethermind/Nethermind.Core/Block.cs index c863555ecd2..1f3424f8760 100644 --- a/src/Nethermind/Nethermind.Core/Block.cs +++ b/src/Nethermind/Nethermind.Core/Block.cs @@ -6,7 +6,6 @@ using System.Diagnostics; using System.Linq; using System.Text; -using Nethermind.Core.ConsensusRequests; using System.Text.Json.Serialization; using Nethermind.Core.Collections; using System.Text.Unicode; @@ -28,11 +27,10 @@ public Block(BlockHeader header, BlockBody body) public Block(BlockHeader header, IEnumerable transactions, IEnumerable uncles, - IEnumerable? withdrawals = null, - IEnumerable? requests = null) + IEnumerable? withdrawals = null) { Header = header ?? throw new ArgumentNullException(nameof(header)); - Body = new(transactions.ToArray(), uncles.ToArray(), withdrawals?.ToArray(), requests?.ToArray()); + Body = new(transactions.ToArray(), uncles.ToArray(), withdrawals?.ToArray()); } public Block(BlockHeader header) : this( @@ -40,8 +38,7 @@ public Block(BlockHeader header) : this( new( null, null, - header.WithdrawalsRoot is null ? null : Array.Empty(), - header.RequestsRoot is null ? null : Array.Empty()) + header.WithdrawalsRoot is null ? null : Array.Empty()) ) { } @@ -66,7 +63,6 @@ public Transaction[] Transactions public BlockHeader[] Uncles => Body.Uncles; // do not add setter here public Withdrawal[]? Withdrawals => Body.Withdrawals; // do not add setter here - public ConsensusRequest[]? Requests => Body.Requests; // do not add setter here public Hash256? Hash => Header.Hash; // do not add setter here @@ -119,7 +115,10 @@ public Transaction[] Transactions public Hash256? WithdrawalsRoot => Header.WithdrawalsRoot; // do not add setter here public Hash256? ParentBeaconBlockRoot => Header.ParentBeaconBlockRoot; // do not add setter here - public Hash256? RequestsRoot => Header.RequestsRoot; // do not add setter here + public Hash256? RequestsHash => Header.RequestsHash; // do not add setter here + + [JsonIgnore] + public byte[][]? ExecutionRequests { get; set; } [JsonIgnore] public ArrayPoolList? AccountChanges { get; set; } diff --git a/src/Nethermind/Nethermind.Core/BlockBody.cs b/src/Nethermind/Nethermind.Core/BlockBody.cs index 26b918ef28f..76658c6ab8a 100644 --- a/src/Nethermind/Nethermind.Core/BlockBody.cs +++ b/src/Nethermind/Nethermind.Core/BlockBody.cs @@ -2,28 +2,25 @@ // SPDX-License-Identifier: LGPL-3.0-only using System; -using Nethermind.Core.ConsensusRequests; namespace Nethermind.Core { public class BlockBody { - public BlockBody(Transaction[]? transactions, BlockHeader[]? uncles, Withdrawal[]? withdrawals = null, ConsensusRequest[]? requests = null) + public BlockBody(Transaction[]? transactions, BlockHeader[]? uncles, Withdrawal[]? withdrawals = null) { Transactions = transactions ?? Array.Empty(); Uncles = uncles ?? Array.Empty(); Withdrawals = withdrawals; - Requests = requests; } public BlockBody() : this(null, null, null) { } - public BlockBody WithChangedTransactions(Transaction[] transactions) => new(transactions, Uncles, Withdrawals, Requests); + public BlockBody WithChangedTransactions(Transaction[] transactions) => new(transactions, Uncles, Withdrawals); - public BlockBody WithChangedUncles(BlockHeader[] uncles) => new(Transactions, uncles, Withdrawals, Requests); + public BlockBody WithChangedUncles(BlockHeader[] uncles) => new(Transactions, uncles, Withdrawals); - public BlockBody WithChangedWithdrawals(Withdrawal[]? withdrawals) => new(Transactions, Uncles, withdrawals, Requests); - public BlockBody WithChangedConsensusRequests(ConsensusRequest[]? consensusRequests) => new(Transactions, Uncles, Withdrawals, consensusRequests); + public BlockBody WithChangedWithdrawals(Withdrawal[]? withdrawals) => new(Transactions, Uncles, withdrawals); public static BlockBody WithOneTransactionOnly(Transaction tx) => new(new[] { tx }, null, null); @@ -32,8 +29,7 @@ public BlockBody() : this(null, null, null) { } public BlockHeader[] Uncles { get; } public Withdrawal[]? Withdrawals { get; } - public ConsensusRequest[]? Requests { get; set; } - public bool IsEmpty => Transactions.Length == 0 && Uncles.Length == 0 && (Withdrawals?.Length ?? 0) == 0 && (Requests?.Length ?? 0) == 0; + public bool IsEmpty => Transactions.Length == 0 && Uncles.Length == 0 && (Withdrawals?.Length ?? 0) == 0; } } diff --git a/src/Nethermind/Nethermind.Core/BlockHeader.cs b/src/Nethermind/Nethermind.Core/BlockHeader.cs index 1ddd19503b9..637258ff65e 100644 --- a/src/Nethermind/Nethermind.Core/BlockHeader.cs +++ b/src/Nethermind/Nethermind.Core/BlockHeader.cs @@ -28,7 +28,7 @@ public BlockHeader( ulong? blobGasUsed = null, ulong? excessBlobGas = null, Hash256? parentBeaconBlockRoot = null, - Hash256? requestsRoot = null) + Hash256? requestsHash = null) { ParentHash = parentHash; UnclesHash = unclesHash; @@ -39,7 +39,7 @@ public BlockHeader( Timestamp = timestamp; ExtraData = extraData; ParentBeaconBlockRoot = parentBeaconBlockRoot; - RequestsRoot = requestsRoot; + RequestsHash = requestsHash; BlobGasUsed = blobGasUsed; ExcessBlobGas = excessBlobGas; } @@ -72,13 +72,12 @@ public BlockHeader( public UInt256 BaseFeePerGas { get; set; } public Hash256? WithdrawalsRoot { get; set; } public Hash256? ParentBeaconBlockRoot { get; set; } - public Hash256? RequestsRoot { get; set; } + public Hash256? RequestsHash { get; set; } public ulong? BlobGasUsed { get; set; } public ulong? ExcessBlobGas { get; set; } public bool HasBody => (TxRoot is not null && TxRoot != Keccak.EmptyTreeHash) || (UnclesHash is not null && UnclesHash != Keccak.OfAnEmptySequenceRlp) - || (WithdrawalsRoot is not null && WithdrawalsRoot != Keccak.EmptyTreeHash) - || (RequestsRoot is not null && RequestsRoot != Keccak.EmptyTreeHash); + || (WithdrawalsRoot is not null && WithdrawalsRoot != Keccak.EmptyTreeHash); public bool HasTransactions => (TxRoot is not null && TxRoot != Keccak.EmptyTreeHash); @@ -119,9 +118,9 @@ public string ToString(string indent) } builder.AppendLine($"{indent}IsPostMerge: {IsPostMerge}"); builder.AppendLine($"{indent}TotalDifficulty: {TotalDifficulty}"); - if (RequestsRoot is not null) + if (RequestsHash is not null) { - builder.AppendLine($"{indent}RequestsRoot: {RequestsRoot}"); + builder.AppendLine($"{indent}RequestsHash: {RequestsHash}"); } return builder.ToString(); diff --git a/src/Nethermind/Nethermind.Core/ConsensusRequests/ConsensusRequest.cs b/src/Nethermind/Nethermind.Core/ConsensusRequests/ConsensusRequest.cs deleted file mode 100644 index e9e5f6d38e1..00000000000 --- a/src/Nethermind/Nethermind.Core/ConsensusRequests/ConsensusRequest.cs +++ /dev/null @@ -1,78 +0,0 @@ -// SPDX-FileCopyrightText: 2024 Demerzel Solutions Limited -// SPDX-License-Identifier: LGPL-3.0-only - - -using System; -using System.Text.Json.Serialization; - -namespace Nethermind.Core.ConsensusRequests; - -public enum ConsensusRequestsType : byte -{ - Deposit = 0, - WithdrawalRequest = 1, - ConsolidationRequest = 2 -} - -public abstract class ConsensusRequest -{ - [JsonIgnore] - public ConsensusRequestsType Type { get; protected set; } -} - -public static class ConsensusRequestExtensions -{ - public static (int depositCount, int withdrawalRequestCount, int consolidationRequestCount) GetTypeCounts(this ConsensusRequest[]? requests) - { - int depositCount = 0; - int withdrawalRequestCount = 0; - int consolidationRequestCount = 0; - int length = requests?.Length ?? 0; - for (int i = 0; i < length; i++) - { - if (requests![i].Type == ConsensusRequestsType.Deposit) - { - depositCount++; - } - else if (requests[i].Type == ConsensusRequestsType.WithdrawalRequest) - { - withdrawalRequestCount++; - } - else - { - consolidationRequestCount++; - } - } - - return (depositCount, withdrawalRequestCount, consolidationRequestCount); - } - - public static (Deposit[]? deposits, WithdrawalRequest[]? withdrawalRequests, ConsolidationRequest[]? consolidationRequests) SplitRequests(this ConsensusRequest[]? requests) - { - if (requests is null) return (null, null, null); - (int depositCount, int withdrawalRequestCount, int consolidationRequestCount) = requests.GetTypeCounts(); - Deposit[] deposits = new Deposit[depositCount]; - WithdrawalRequest[] withdrawalRequests = new WithdrawalRequest[withdrawalRequestCount]; - ConsolidationRequest[] consolidationRequests = new ConsolidationRequest[consolidationRequestCount]; - int depositIndex = 0; - int withdrawalRequestIndex = 0; - int consolidationRequestIndex = 0; - for (int i = 0; i < requests.Length; i++) - { - if (requests[i].Type == ConsensusRequestsType.Deposit) - { - deposits[depositIndex++] = (Deposit)requests[i]; - } - else if (requests[i].Type == ConsensusRequestsType.WithdrawalRequest) - { - withdrawalRequests[withdrawalRequestIndex++] = (WithdrawalRequest)requests[i]; - } - else - { - consolidationRequests[consolidationRequestIndex++] = (ConsolidationRequest)requests[i]; - } - } - - return (deposits, withdrawalRequests, consolidationRequests); - } -} diff --git a/src/Nethermind/Nethermind.Core/ConsensusRequests/ConsolidationRequest.cs b/src/Nethermind/Nethermind.Core/ConsensusRequests/ConsolidationRequest.cs deleted file mode 100644 index abf79b924a1..00000000000 --- a/src/Nethermind/Nethermind.Core/ConsensusRequests/ConsolidationRequest.cs +++ /dev/null @@ -1,31 +0,0 @@ -// SPDX-FileCopyrightText: 2022 Demerzel Solutions Limited -// SPDX-License-Identifier: LGPL-3.0-only -using System; -using Nethermind.Core.Extensions; - -namespace Nethermind.Core.ConsensusRequests; - -/// -/// Represents a Deposit that has been validated at the consensus layer. -/// -public class ConsolidationRequest : ConsensusRequest -{ - public ConsolidationRequest() - { - Type = ConsensusRequestsType.ConsolidationRequest; - } - public Address? SourceAddress { get; set; } - public Memory? SourcePubkey { get; set; } - - public Memory? TargetPubkey { get; set; } - - public override string ToString() => ToString(string.Empty); - - public string ToString(string indentation) => @$"{indentation}{nameof(ConsolidationRequest)} - {{ {nameof(SourceAddress)}: {SourceAddress}, - {nameof(SourcePubkey)}: {SourcePubkey?.Span.ToHexString()}, - {nameof(TargetPubkey)}: {TargetPubkey?.Span.ToHexString()}, - }}"; - - -} diff --git a/src/Nethermind/Nethermind.Core/ConsensusRequests/Deposit.cs b/src/Nethermind/Nethermind.Core/ConsensusRequests/Deposit.cs deleted file mode 100644 index 50b46fc27c2..00000000000 --- a/src/Nethermind/Nethermind.Core/ConsensusRequests/Deposit.cs +++ /dev/null @@ -1,36 +0,0 @@ -// SPDX-FileCopyrightText: 2022 Demerzel Solutions Limited -// SPDX-License-Identifier: LGPL-3.0-only - -using System; -using Nethermind.Core.Extensions; - -namespace Nethermind.Core.ConsensusRequests; - -/// -/// Represents a Deposit that has been validated at the consensus layer. -/// -public class Deposit : ConsensusRequest -{ - public Deposit() - { - Type = ConsensusRequestsType.Deposit; - Amount = 0; - } - public Memory? Pubkey { get; set; } - public byte[]? WithdrawalCredentials { get; set; } - - public ulong Amount { get; set; } - - public byte[]? Signature { get; set; } - public ulong? Index { get; set; } - public override string ToString() => ToString(string.Empty); - - public string ToString(string indentation) => @$"{indentation}{nameof(Deposit)} - {{{nameof(Index)}: {Index}, - {nameof(WithdrawalCredentials)}: {WithdrawalCredentials?.ToHexString()}, - {nameof(Amount)}: {Amount}, - {nameof(Signature)}: {Signature?.ToHexString()}, - {nameof(Pubkey)}: {Pubkey?.Span.ToHexString()}}}"; - - -} diff --git a/src/Nethermind/Nethermind.Core/ConsensusRequests/WithdrawalRequest.cs b/src/Nethermind/Nethermind.Core/ConsensusRequests/WithdrawalRequest.cs deleted file mode 100644 index f9d79f127c7..00000000000 --- a/src/Nethermind/Nethermind.Core/ConsensusRequests/WithdrawalRequest.cs +++ /dev/null @@ -1,33 +0,0 @@ -// SPDX-FileCopyrightText: 2022 Demerzel Solutions Limited -// SPDX-License-Identifier: LGPL-3.0-only - -using System; -using Nethermind.Core.Extensions; -using System.Text; - -namespace Nethermind.Core.ConsensusRequests; - -/// -/// Represents a Deposit that has been validated at the consensus layer. -/// -public class WithdrawalRequest : ConsensusRequest -{ - public WithdrawalRequest() - { - Type = ConsensusRequestsType.WithdrawalRequest; - Amount = 0; - } - public Address? SourceAddress { get; set; } - - public Memory? ValidatorPubkey { get; set; } - - public ulong Amount { get; set; } - public override string ToString() => ToString(string.Empty); - - public string ToString(string indentation) => @$"{indentation}{nameof(WithdrawalRequest)} - {{{nameof(SourceAddress)}: {SourceAddress}, - {nameof(ValidatorPubkey)}: {ValidatorPubkey?.Span.ToHexString()}, - {nameof(Amount)}: {Amount}}}"; - - -} diff --git a/src/Nethermind/Nethermind.Core/Eip7002Constants.cs b/src/Nethermind/Nethermind.Core/Eip7002Constants.cs index b7f1ec1e36f..fd826e87683 100644 --- a/src/Nethermind/Nethermind.Core/Eip7002Constants.cs +++ b/src/Nethermind/Nethermind.Core/Eip7002Constants.cs @@ -5,5 +5,5 @@ namespace Nethermind.Core; public static class Eip7002Constants { - public static readonly Address WithdrawalRequestPredeployAddress = new("0x00A3ca265EBcb825B45F985A16CEFB49958cE017"); + public static readonly Address WithdrawalRequestPredeployAddress = new("0x09Fc772D0857550724b07B850a4323f39112aAaA"); } diff --git a/src/Nethermind/Nethermind.Core/Eip7251Constants.cs b/src/Nethermind/Nethermind.Core/Eip7251Constants.cs index 4fc30bd2601..7ae7e5eece1 100644 --- a/src/Nethermind/Nethermind.Core/Eip7251Constants.cs +++ b/src/Nethermind/Nethermind.Core/Eip7251Constants.cs @@ -5,5 +5,5 @@ namespace Nethermind.Core; public static class Eip7251Constants { - public static readonly Address ConsolidationRequestPredeployAddress = new("0x00b42dbF2194e931E80326D950320f7d9Dbeac02"); + public static readonly Address ConsolidationRequestPredeployAddress = new("0x01aBEa29659e5e97C95107F20bb753cD3e09bBBb"); } diff --git a/src/Nethermind/Nethermind.Core/ExecutionRequest/ExecutionRequest.cs b/src/Nethermind/Nethermind.Core/ExecutionRequest/ExecutionRequest.cs new file mode 100644 index 00000000000..38c002f5c5a --- /dev/null +++ b/src/Nethermind/Nethermind.Core/ExecutionRequest/ExecutionRequest.cs @@ -0,0 +1,26 @@ +// SPDX-FileCopyrightText: 2024 Demerzel Solutions Limited +// SPDX-License-Identifier: LGPL-3.0-only + + +using Nethermind.Core.Extensions; + +namespace Nethermind.Core.ExecutionRequest; + +public enum ExecutionRequestType : byte +{ + Deposit = 0, + WithdrawalRequest = 1, + ConsolidationRequest = 2 +} + +public class ExecutionRequest +{ + public byte RequestType { get; set; } + public byte[]? RequestData { get; set; } + + public override string ToString() => ToString(string.Empty); + + public string ToString(string indentation) => @$"{indentation}{nameof(ExecutionRequest)} + {{{nameof(RequestType)}: {RequestType}, + {nameof(RequestData)}: {RequestData!.ToHexString()}}}"; +} diff --git a/src/Nethermind/Nethermind.Core/ExecutionRequest/ExecutionRequestExtensions.cs b/src/Nethermind/Nethermind.Core/ExecutionRequest/ExecutionRequestExtensions.cs new file mode 100644 index 00000000000..a6aeb5b9a03 --- /dev/null +++ b/src/Nethermind/Nethermind.Core/ExecutionRequest/ExecutionRequestExtensions.cs @@ -0,0 +1,93 @@ +// SPDX-FileCopyrightText: 2024 Demerzel Solutions Limited +// SPDX-License-Identifier: LGPL-3.0-only + + +using System; +using System.Buffers; +using System.Collections.Generic; +using System.Linq; +using System.Runtime.CompilerServices; +using System.Security.Cryptography; +using Nethermind.Core.Collections; +using Nethermind.Core.Crypto; + +namespace Nethermind.Core.ExecutionRequest; + +public static class ExecutionRequestExtensions +{ + public const int DepositRequestsBytesSize = PublicKeySize /*pubkey: Bytes48 */ + Hash256.Size /*withdrawal_credentials: Bytes32 */ + sizeof(ulong) /*amount: uint64*/ + 96 /*signature: Bytes96*/ + sizeof(ulong) /*index: uint64*/; + public const int WithdrawalRequestsBytesSize = Address.Size + PublicKeySize /*validator_pubkey: Bytes48*/ + sizeof(ulong) /*amount: uint64*/; + public const int ConsolidationRequestsBytesSize = Address.Size + PublicKeySize /*source_pubkey: Bytes48*/ + PublicKeySize /*target_pubkey: Bytes48*/; + public const int RequestPartsCount = 3; + private const int PublicKeySize = 48; + + public static readonly byte[][] EmptyRequests = [[], [], []]; + public static readonly Hash256 EmptyRequestsHash = CalculateHashFromFlatEncodedRequests(EmptyRequests); + + public static int GetRequestsByteSize(this IEnumerable requests) + { + int size = 0; + foreach (ExecutionRequest request in requests) + { + size += request.RequestData!.Length + 1; + } + return size; + } + + [SkipLocalsInit] + public static Hash256 CalculateHashFromFlatEncodedRequests(byte[][]? flatEncodedRequests) + { + // make sure that length is exactly 3 + if (flatEncodedRequests is null || flatEncodedRequests.Length != RequestPartsCount) + { + throw new ArgumentException("Flat encoded requests must be an array of 3 elements"); + } + + using SHA256 sha256 = SHA256.Create(); + byte[] concatenatedHashes = new byte[Hash256.Size * RequestPartsCount]; + int currentPosition = 0; + byte type = 0; + // Allocate the buffer once outside the loop + Span requestBuffer = stackalloc byte[Math.Max(Math.Max(flatEncodedRequests[0].Length, flatEncodedRequests[1].Length), flatEncodedRequests[2].Length) + 1]; + // Compute sha256 for each request and concatenate them + foreach (byte[] requests in flatEncodedRequests) + { + requestBuffer[0] = type; + requests.CopyTo(requestBuffer.Slice(1, requests.Length)); + sha256.ComputeHash(requestBuffer.Slice(0, requests.Length + 1).ToArray()).CopyTo(concatenatedHashes.AsSpan(currentPosition, Hash256.Size)); + currentPosition += Hash256.Size; + type++; + } + + // Compute sha256 of the concatenated hashes + return new Hash256(sha256.ComputeHash(concatenatedHashes.ToArray())); + } + + + // the following functions are only used in tests + public static ArrayPoolList GetFlatEncodedRequests( + ExecutionRequest[] depositRequests, + ExecutionRequest[] withdrawalRequests, + ExecutionRequest[] consolidationRequests + ) + { + return new(RequestPartsCount) + { + FlatEncodeRequests(depositRequests, depositRequests.Length * DepositRequestsBytesSize), + FlatEncodeRequests(withdrawalRequests, withdrawalRequests.Length * WithdrawalRequestsBytesSize), + FlatEncodeRequests(consolidationRequests, consolidationRequests.Length * ConsolidationRequestsBytesSize) + }; + + static byte[] FlatEncodeRequests(ExecutionRequest[] requests, int bufferSize) + { + using ArrayPoolList buffer = new(bufferSize); + + foreach (ExecutionRequest request in requests) + { + buffer.AddRange(request.RequestData!); + } + + return buffer.ToArray(); + } + } +} diff --git a/src/Nethermind/Nethermind.Core/Extensions/Bytes.cs b/src/Nethermind/Nethermind.Core/Extensions/Bytes.cs index bbcb28b73a3..628b3ebf37a 100644 --- a/src/Nethermind/Nethermind.Core/Extensions/Bytes.cs +++ b/src/Nethermind/Nethermind.Core/Extensions/Bytes.cs @@ -281,19 +281,25 @@ public static byte[] Concat(byte[] part1, byte[] part2) } public static byte[] Concat(params byte[][] parts) + { + return Concat(parts.AsSpan()); + } + + public static byte[] Concat(ReadOnlySpan bytes) { int totalLength = 0; - for (int i = 0; i < parts.Length; i++) + foreach (byte[] byteArray in bytes) { - totalLength += parts[i].Length; + totalLength += byteArray.Length; } byte[] result = new byte[totalLength]; - int position = 0; - for (int i = 0; i < parts.Length; i++) + int offset = 0; + + foreach (byte[] byteArray in bytes) { - Buffer.BlockCopy(parts[i], 0, result, position, parts[i].Length); - position += parts[i].Length; + Array.Copy(byteArray, 0, result, offset, byteArray.Length); + offset += byteArray.Length; } return result; diff --git a/src/Nethermind/Nethermind.Evm.Test/ConsolidationRequestProcessorTest.cs b/src/Nethermind/Nethermind.Evm.Test/ConsolidationRequestProcessorTest.cs deleted file mode 100644 index 99973b8bc23..00000000000 --- a/src/Nethermind/Nethermind.Evm.Test/ConsolidationRequestProcessorTest.cs +++ /dev/null @@ -1,96 +0,0 @@ -// SPDX-FileCopyrightText: 2024 Demerzel Solutions Limited -// SPDX-License-Identifier: LGPL-3.0-only - -using System; -using System.Linq; -using FluentAssertions; -using Nethermind.Consensus.Requests; -using Nethermind.Core; -using Nethermind.Core.ConsensusRequests; -using Nethermind.Core.Extensions; -using Nethermind.Core.Specs; -using Nethermind.Core.Test.Builders; -using Nethermind.Crypto; -using Nethermind.Db; -using Nethermind.Evm.Tracing; -using Nethermind.Evm.TransactionProcessing; -using Nethermind.Int256; -using Nethermind.Logging; -using Nethermind.Specs; -using Nethermind.State; -using Nethermind.Trie.Pruning; -using NSubstitute; -using NUnit.Framework; - - -namespace Nethermind.Evm.Test; - -public class ConsolidationRequestProcessorTests -{ - - private ISpecProvider _specProvider; - private ITransactionProcessor _transactionProcessor; - private IWorldState _stateProvider; - - private ICodeInfoRepository _codeInfoRepository; - - private static readonly UInt256 AccountBalance = 1.Ether(); - - private readonly Address eip7251Account = Eip7251Constants.ConsolidationRequestPredeployAddress; - - [SetUp] - public void Setup() - { - _specProvider = MainnetSpecProvider.Instance; - MemDb stateDb = new(); - TrieStore trieStore = new(stateDb, LimboLogs.Instance); - _stateProvider = new WorldState(trieStore, new MemDb(), LimboLogs.Instance); - _stateProvider.CreateAccount(eip7251Account, AccountBalance); - _stateProvider.Commit(_specProvider.GenesisSpec); - _stateProvider.CommitTree(0); - - _codeInfoRepository = new CodeInfoRepository(); - - VirtualMachine virtualMachine = new(new TestBlockhashProvider(_specProvider), _specProvider, _codeInfoRepository, LimboLogs.Instance); - - _transactionProcessor = Substitute.For(); - - _transactionProcessor.Execute(Arg.Any(), Arg.Any(), Arg.Any()) - .Returns(ci => - { - CallOutputTracer tracer = ci.Arg(); - tracer.ReturnValue = Bytes.FromHexString("a94f5374fce5edbc8e2a8697c15331677e6ebf0b0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000010000000000000000a94f5374fce5edbc8e2a8697c15331677e6ebf0b000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000002ffffffffffffffffa94f5374fce5edbc8e2a8697c15331677e6ebf0b0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000030000000000000000a94f5374fce5edbc8e2a8697c15331677e6ebf0b000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000004ffffffffffffffffa94f5374fce5edbc8e2a8697c15331677e6ebf0b0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000050000000000000000a94f5374fce5edbc8e2a8697c15331677e6ebf0b000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000006ffffffffffffffffa94f5374fce5edbc8e2a8697c15331677e6ebf0b0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000070000000000000000a94f5374fce5edbc8e2a8697c15331677e6ebf0b000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000008ffffffffffffffffa94f5374fce5edbc8e2a8697c15331677e6ebf0b0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000090000000000000000a94f5374fce5edbc8e2a8697c15331677e6ebf0b00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000affffffffffffffffa94f5374fce5edbc8e2a8697c15331677e6ebf0b00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000b0000000000000000a94f5374fce5edbc8e2a8697c15331677e6ebf0b00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000cffffffffffffffffa94f5374fce5edbc8e2a8697c15331677e6ebf0b00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000d0000000000000000a94f5374fce5edbc8e2a8697c15331677e6ebf0b00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000effffffffffffffffa94f5374fce5edbc8e2a8697c15331677e6ebf0b00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000f0000000000000000a94f5374fce5edbc8e2a8697c15331677e6ebf0b000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000010ffffffffffffffff"); - return new TransactionResult(); - }); - } - - - [Test] - public void ShouldProcessConsolidationRequest() - { - - IReleaseSpec spec = Substitute.For(); - spec.ConsolidationRequestsEnabled.Returns(true); - spec.Eip7251ContractAddress.Returns(eip7251Account); - - Block block = Build.A.Block.TestObject; - - ConsolidationRequestsProcessor ConsolidationRequestsProcessor = new(transactionProcessor: _transactionProcessor); - - var ConsolidationRequest = new ConsolidationRequest() - { - SourceAddress = new Address(Bytes.FromHexString("0xa94f5374fce5edbc8e2a8697c15331677e6ebf0b")), - SourcePubkey = Bytes.FromHexString("000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000001"), - TargetPubkey = Bytes.FromHexString("0000000000000000a94f5374fce5edbc8e2a8697c15331677e6ebf0b0000000000000000000000000000000000000000") - }; - - var ConsolidationRequests = ConsolidationRequestsProcessor.ReadRequests(block, _stateProvider, spec).ToList(); - - Assert.That(ConsolidationRequests, Has.Count.EqualTo(10)); - ConsolidationRequest ConsolidationRequestResult = ConsolidationRequests[0]; - - ConsolidationRequestResult.Should().BeEquivalentTo(ConsolidationRequest, options => options - .Using>(ctx => ctx.Subject.Span.SequenceEqual(ctx.Expectation.Span).Should().BeTrue()) - .WhenTypeIs>()); - } -} diff --git a/src/Nethermind/Nethermind.Evm.Test/WithdrawalRequestsProcessorTests.cs b/src/Nethermind/Nethermind.Evm.Test/WithdrawalRequestsProcessorTests.cs deleted file mode 100644 index 279b668e424..00000000000 --- a/src/Nethermind/Nethermind.Evm.Test/WithdrawalRequestsProcessorTests.cs +++ /dev/null @@ -1,96 +0,0 @@ -// SPDX-FileCopyrightText: 2024 Demerzel Solutions Limited -// SPDX-License-Identifier: LGPL-3.0-only - -using System; -using System.Linq; -using FluentAssertions; -using Nethermind.Consensus.Requests; -using Nethermind.Core; -using Nethermind.Core.ConsensusRequests; -using Nethermind.Core.Extensions; -using Nethermind.Core.Specs; -using Nethermind.Core.Test.Builders; -using Nethermind.Crypto; -using Nethermind.Db; -using Nethermind.Evm.Tracing; -using Nethermind.Evm.TransactionProcessing; -using Nethermind.Int256; -using Nethermind.Logging; -using Nethermind.Specs; -using Nethermind.State; -using Nethermind.Trie.Pruning; -using NSubstitute; -using NUnit.Framework; - - -namespace Nethermind.Evm.Test; - -public class WithdrawalRequestProcessorTests -{ - - private ISpecProvider _specProvider; - private IEthereumEcdsa _ethereumEcdsa; - private ITransactionProcessor _transactionProcessor; - private IWorldState _stateProvider; - private ICodeInfoRepository _codeInfoRepository; - private static readonly UInt256 AccountBalance = 1.Ether(); - private readonly Address eip7002Account = Eip7002Constants.WithdrawalRequestPredeployAddress; - - [SetUp] - public void Setup() - { - _specProvider = MainnetSpecProvider.Instance; - MemDb stateDb = new(); - TrieStore trieStore = new(stateDb, LimboLogs.Instance); - _stateProvider = new WorldState(trieStore, new MemDb(), LimboLogs.Instance); - _stateProvider.CreateAccount(eip7002Account, AccountBalance); - _stateProvider.Commit(_specProvider.GenesisSpec); - _stateProvider.CommitTree(0); - - _codeInfoRepository = new CodeInfoRepository(); - - VirtualMachine virtualMachine = new(new TestBlockhashProvider(_specProvider), _specProvider, _codeInfoRepository, LimboLogs.Instance); - - _transactionProcessor = Substitute.For(); - - _transactionProcessor.Execute(Arg.Any(), Arg.Any(), Arg.Any()) - .Returns(ci => - { - CallOutputTracer tracer = ci.Arg(); - tracer.ReturnValue = Bytes.FromHexString("a94f5374fce5edbc8e2a8697c15331677e6ebf0b0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000010000000000000000a94f5374fce5edbc8e2a8697c15331677e6ebf0b000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000002ffffffffffffffffa94f5374fce5edbc8e2a8697c15331677e6ebf0b0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000030000000000000000a94f5374fce5edbc8e2a8697c15331677e6ebf0b000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000004ffffffffffffffffa94f5374fce5edbc8e2a8697c15331677e6ebf0b0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000050000000000000000a94f5374fce5edbc8e2a8697c15331677e6ebf0b000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000006ffffffffffffffffa94f5374fce5edbc8e2a8697c15331677e6ebf0b0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000070000000000000000a94f5374fce5edbc8e2a8697c15331677e6ebf0b000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000008ffffffffffffffffa94f5374fce5edbc8e2a8697c15331677e6ebf0b0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000090000000000000000a94f5374fce5edbc8e2a8697c15331677e6ebf0b00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000affffffffffffffffa94f5374fce5edbc8e2a8697c15331677e6ebf0b00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000b0000000000000000a94f5374fce5edbc8e2a8697c15331677e6ebf0b00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000cffffffffffffffffa94f5374fce5edbc8e2a8697c15331677e6ebf0b00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000d0000000000000000a94f5374fce5edbc8e2a8697c15331677e6ebf0b00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000effffffffffffffffa94f5374fce5edbc8e2a8697c15331677e6ebf0b00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000f0000000000000000a94f5374fce5edbc8e2a8697c15331677e6ebf0b000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000010ffffffffffffffff"); - return new TransactionResult(); - }); - - _ethereumEcdsa = new EthereumEcdsa(_specProvider.ChainId); - } - - - [Test] - public void ShouldProcessWithdrawalRequest() - { - IReleaseSpec spec = Substitute.For(); - spec.WithdrawalRequestsEnabled.Returns(true); - spec.Eip7002ContractAddress.Returns(eip7002Account); - - Block block = Build.A.Block.TestObject; - - WithdrawalRequestsProcessor withdrawalRequestsProcessor = new(transactionProcessor: _transactionProcessor); - - var withdrawalRequest = new WithdrawalRequest() - { - SourceAddress = new Address(Bytes.FromHexString("0xa94f5374fce5edbc8e2a8697c15331677e6ebf0b")), - ValidatorPubkey = Bytes.FromHexString("000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000001"), - Amount = 0 - }; - - var withdrawalRequests = withdrawalRequestsProcessor.ReadRequests(block, _stateProvider, spec).ToList(); - - Assert.That(withdrawalRequests, Has.Count.EqualTo(16)); - - WithdrawalRequest withdrawalRequestResult = withdrawalRequests[0]; - - withdrawalRequestResult.Should().BeEquivalentTo(withdrawalRequest, options => options - .Using>(ctx => ctx.Subject.Span.SequenceEqual(ctx.Expectation.Span).Should().BeTrue()) - .WhenTypeIs>()); - } -} diff --git a/src/Nethermind/Nethermind.Facade/Eth/BlockForRpc.cs b/src/Nethermind/Nethermind.Facade/Eth/BlockForRpc.cs index c194e214615..bc707f06fa4 100644 --- a/src/Nethermind/Nethermind.Facade/Eth/BlockForRpc.cs +++ b/src/Nethermind/Nethermind.Facade/Eth/BlockForRpc.cs @@ -13,7 +13,6 @@ using System.Text.Json.Serialization; using System.Runtime.CompilerServices; using Nethermind.Facade.Eth.RpcTransaction; -using Nethermind.Core.ConsensusRequests; namespace Nethermind.Facade.Eth; @@ -87,8 +86,7 @@ public BlockForRpc(Block block, bool includeFullTransactionData, ISpecProvider s Uncles = block.Uncles.Select(o => o.Hash); Withdrawals = block.Withdrawals; WithdrawalsRoot = block.Header.WithdrawalsRoot; - Requests = block.Requests; - RequestsRoot = block.Header.RequestsRoot; + RequestsHash = block.Header.RequestsHash; } [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] @@ -147,8 +145,7 @@ public BlockForRpc(Block block, bool includeFullTransactionData, ISpecProvider s [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] public Hash256? ParentBeaconBlockRoot { get; set; } - public IEnumerable? Requests { get; set; } [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] - public Hash256? RequestsRoot { get; set; } + public Hash256? RequestsHash { get; set; } } diff --git a/src/Nethermind/Nethermind.Merge.AuRa.Test/AuRaMergeEngineModuleTests.cs b/src/Nethermind/Nethermind.Merge.AuRa.Test/AuRaMergeEngineModuleTests.cs index f1e2ace6075..3064491f896 100644 --- a/src/Nethermind/Nethermind.Merge.AuRa.Test/AuRaMergeEngineModuleTests.cs +++ b/src/Nethermind/Nethermind.Merge.AuRa.Test/AuRaMergeEngineModuleTests.cs @@ -13,9 +13,9 @@ using Nethermind.Consensus.AuRa.InitializationSteps; using Nethermind.Consensus.AuRa.Validators; using Nethermind.Consensus.Comparers; +using Nethermind.Consensus.ExecutionRequests; using Nethermind.Consensus.Processing; using Nethermind.Consensus.Producers; -using Nethermind.Consensus.Requests; using Nethermind.Consensus.Rewards; using Nethermind.Consensus.Transactions; using Nethermind.Core; @@ -47,8 +47,8 @@ protected override MergeTestBlockchain CreateBaseBlockchain( IMergeConfig? mergeConfig = null, IPayloadPreparationService? mockedPayloadService = null, ILogManager? logManager = null, - IConsensusRequestsProcessor? mockedConsensusRequestsProcessor = null) - => new MergeAuRaTestBlockchain(mergeConfig, mockedPayloadService, null, logManager, mockedConsensusRequestsProcessor); + IExecutionRequestsProcessor? mockedExecutionRequestsProcessor = null) + => new MergeAuRaTestBlockchain(mergeConfig, mockedPayloadService, null, logManager, mockedExecutionRequestsProcessor); protected override Hash256 ExpectedBlockHash => new("0x990d377b67dbffee4a60db6f189ae479ffb406e8abea16af55e0469b8524cf46"); @@ -62,10 +62,10 @@ int ErrorCode => base.forkchoiceUpdatedV2_should_validate_withdrawals(input); [TestCase( - "0xe97d919a17fa5011ff3a08ffb07657ed9e1aaf5ff649888e5d7f605006caf598", - "0xdd9be69fe6ed616f44d53576f430c1c7720ed0e7bff59478539a4a43dbb3bf1f", + "0xd25128557a58fe7bb6346d779cfc86a1f5bd9bff4786a118097aebdf3128f46d", + "0xcbf0d15de352e744aba609aca74846ede5fc3ffd00ca506914b498b00470cbf8", "0xd75d320c3a98a02ec7fe2abdcb1769bd063fec04d73f1735810f365ac12bc4ba", - "0x3c6a8926870bdeff")] + "0xc9763e9904d3fe5b")] public override Task Should_process_block_as_expected_V4(string latestValidHash, string blockHash, string stateRoot, string payloadId) => base.Should_process_block_as_expected_V4(latestValidHash, blockHash, stateRoot, payloadId); @@ -105,10 +105,10 @@ public class MergeAuRaTestBlockchain : MergeTestBlockchain private AuRaNethermindApi? _api; protected ITxSource? _additionalTxSource; - public MergeAuRaTestBlockchain(IMergeConfig? mergeConfig = null, IPayloadPreparationService? mockedPayloadPreparationService = null, ITxSource? additionalTxSource = null, ILogManager? logManager = null, IConsensusRequestsProcessor? mockedConsensusRequestsProcessor = null) - : base(mergeConfig, mockedPayloadPreparationService, logManager, mockedConsensusRequestsProcessor) + public MergeAuRaTestBlockchain(IMergeConfig? mergeConfig = null, IPayloadPreparationService? mockedPayloadPreparationService = null, ITxSource? additionalTxSource = null, ILogManager? logManager = null, IExecutionRequestsProcessor? mockedExecutionRequestsProcessor = null) + : base(mergeConfig, mockedPayloadPreparationService, logManager, mockedExecutionRequestsProcessor) { - ConsensusRequestsProcessor = mockedConsensusRequestsProcessor; + ExecutionRequestsProcessor = mockedExecutionRequestsProcessor; SealEngineType = Core.SealEngineType.AuRa; _additionalTxSource = additionalTxSource; } @@ -160,7 +160,7 @@ protected override IBlockProcessor CreateBlockProcessor() new BlockhashStore(SpecProvider, State), LogManager, WithdrawalProcessor, - consensusRequestsProcessor: ConsensusRequestsProcessor, + executionRequestsProcessor: ExecutionRequestsProcessor, preWarmer: CreateBlockCachePreWarmer()); return new TestBlockProcessorInterceptor(processor, _blockProcessingThrottle); @@ -196,7 +196,7 @@ protected override IBlockProducer CreateTestBlockProducer(TxPoolTxSource txPoolT transactionComparerProvider, blocksConfig, LogManager, - ConsensusRequestsProcessor); + ExecutionRequestsProcessor); BlockProducerEnv blockProducerEnv = blockProducerEnvFactory.Create(_additionalTxSource); diff --git a/src/Nethermind/Nethermind.Merge.AuRa/AuRaMergeBlockProcessor.cs b/src/Nethermind/Nethermind.Merge.AuRa/AuRaMergeBlockProcessor.cs index 8054855b51f..62a4cedd69c 100644 --- a/src/Nethermind/Nethermind.Merge.AuRa/AuRaMergeBlockProcessor.cs +++ b/src/Nethermind/Nethermind.Merge.AuRa/AuRaMergeBlockProcessor.cs @@ -6,7 +6,6 @@ using Nethermind.Blockchain.Receipts; using Nethermind.Consensus.AuRa; using Nethermind.Consensus.AuRa.Validators; -using Nethermind.Consensus.Requests; using Nethermind.Consensus.Processing; using Nethermind.Consensus.Rewards; using Nethermind.Consensus.Transactions; @@ -18,6 +17,7 @@ using Nethermind.Evm.TransactionProcessing; using Nethermind.Logging; using Nethermind.State; +using Nethermind.Consensus.ExecutionRequests; namespace Nethermind.Merge.AuRa; @@ -38,7 +38,7 @@ public class AuRaMergeBlockProcessor( AuRaContractGasLimitOverride? gasLimitOverride = null, ContractRewriter? contractRewriter = null, IBlockCachePreWarmer? preWarmer = null, - IConsensusRequestsProcessor? consensusRequestsProcessor = null) + IExecutionRequestsProcessor? executionRequestsProcessor = null) : AuRaBlockProcessor(specProvider, blockValidator, rewardCalculator, @@ -55,7 +55,7 @@ public class AuRaMergeBlockProcessor( gasLimitOverride, contractRewriter, preWarmer, - consensusRequestsProcessor) + executionRequestsProcessor) { protected override TxReceipt[] ProcessBlock(Block block, IBlockTracer blockTracer, ProcessingOptions options) => block.IsPostMerge diff --git a/src/Nethermind/Nethermind.Merge.AuRa/AuRaMergeBlockProducerEnvFactory.cs b/src/Nethermind/Nethermind.Merge.AuRa/AuRaMergeBlockProducerEnvFactory.cs index 9dd11bc4de6..c8529a338d2 100644 --- a/src/Nethermind/Nethermind.Merge.AuRa/AuRaMergeBlockProducerEnvFactory.cs +++ b/src/Nethermind/Nethermind.Merge.AuRa/AuRaMergeBlockProducerEnvFactory.cs @@ -8,9 +8,9 @@ using Nethermind.Consensus.AuRa.Config; using Nethermind.Consensus.AuRa.InitializationSteps; using Nethermind.Consensus.Comparers; +using Nethermind.Consensus.ExecutionRequests; using Nethermind.Consensus.Processing; using Nethermind.Consensus.Producers; -using Nethermind.Consensus.Requests; using Nethermind.Consensus.Rewards; using Nethermind.Consensus.Validators; using Nethermind.Core.Specs; @@ -26,8 +26,7 @@ namespace Nethermind.Merge.AuRa; public class AuRaMergeBlockProducerEnvFactory : BlockProducerEnvFactory { private readonly AuRaNethermindApi _auraApi; - private readonly IConsensusRequestsProcessor? _consensusRequestsProcessor; - + private readonly IExecutionRequestsProcessor? _executionRequestsProcessor; public AuRaMergeBlockProducerEnvFactory( AuRaNethermindApi auraApi, IWorldStateManager worldStateManager, @@ -41,7 +40,7 @@ public AuRaMergeBlockProducerEnvFactory( ITransactionComparerProvider transactionComparerProvider, IBlocksConfig blocksConfig, ILogManager logManager, - IConsensusRequestsProcessor? consensusRequestsProcessor = null) : base( + IExecutionRequestsProcessor? executionRequestsProcessor = null) : base( worldStateManager, blockTree, specProvider, @@ -53,10 +52,10 @@ public AuRaMergeBlockProducerEnvFactory( transactionComparerProvider, blocksConfig, logManager, - consensusRequestsProcessor) + executionRequestsProcessor) { _auraApi = auraApi; - _consensusRequestsProcessor = consensusRequestsProcessor; + _executionRequestsProcessor = executionRequestsProcessor; } protected override BlockProcessor CreateBlockProcessor( @@ -90,7 +89,7 @@ protected override BlockProcessor CreateBlockProcessor( ), readOnlyTxProcessingEnv.TransactionProcessor, null, - consensusRequestsProcessor: _consensusRequestsProcessor); + executionRequestsProcessor: _executionRequestsProcessor); } protected override TxPoolTxSource CreateTxPoolTxSource( diff --git a/src/Nethermind/Nethermind.Merge.AuRa/InitializationSteps/InitializeBlockchainAuRaMerge.cs b/src/Nethermind/Nethermind.Merge.AuRa/InitializationSteps/InitializeBlockchainAuRaMerge.cs index 700fb7ccadd..28a7d6e3d62 100644 --- a/src/Nethermind/Nethermind.Merge.AuRa/InitializationSteps/InitializeBlockchainAuRaMerge.cs +++ b/src/Nethermind/Nethermind.Merge.AuRa/InitializationSteps/InitializeBlockchainAuRaMerge.cs @@ -6,10 +6,7 @@ using Nethermind.Consensus.AuRa; using Nethermind.Consensus.AuRa.Config; using Nethermind.Consensus.AuRa.InitializationSteps; -using Nethermind.Consensus.AuRa.Validators; -using Nethermind.Consensus.Withdrawals; using Nethermind.Consensus.Processing; -using Nethermind.Consensus.Requests; using Nethermind.Consensus.Transactions; using Nethermind.Core; using Nethermind.Evm.TransactionProcessing; diff --git a/src/Nethermind/Nethermind.Merge.Plugin.Test/ConsensusRequestsProcessorMock.cs b/src/Nethermind/Nethermind.Merge.Plugin.Test/ConsensusRequestsProcessorMock.cs deleted file mode 100644 index 14b1b8881c1..00000000000 --- a/src/Nethermind/Nethermind.Merge.Plugin.Test/ConsensusRequestsProcessorMock.cs +++ /dev/null @@ -1,37 +0,0 @@ -// SPDX-FileCopyrightText: 2024 Demerzel Solutions Limited -// SPDX-License-Identifier: LGPL-3.0-only - -using MathNet.Numerics.Distributions; -using Nethermind.Consensus.Requests; -using Nethermind.Core; -using Nethermind.Core.ConsensusRequests; -using Nethermind.Core.Crypto; -using Nethermind.Core.Specs; -using Nethermind.Core.Test.Builders; -using Nethermind.State; -using Nethermind.State.Proofs; - -namespace Nethermind.Merge.Plugin.Test; - -public class ConsensusRequestsProcessorMock : IConsensusRequestsProcessor -{ - public static ConsensusRequest[] Requests = - [ - TestItem.DepositA_1Eth, - TestItem.DepositB_2Eth, - TestItem.WithdrawalRequestA, - TestItem.WithdrawalRequestB, - TestItem.ConsolidationRequestA, - TestItem.ConsolidationRequestB - ]; - - public void ProcessRequests(Block block, IWorldState state, TxReceipt[] receipts, IReleaseSpec spec) - { - if (block.IsGenesis) - return; - - block.Body.Requests = Requests; - Hash256 root = new RequestsTrie(Requests).RootHash; - block.Header.RequestsRoot = root; - } -} diff --git a/src/Nethermind/Nethermind.Merge.Plugin.Test/EngineModuleTests.HelperFunctions.cs b/src/Nethermind/Nethermind.Merge.Plugin.Test/EngineModuleTests.HelperFunctions.cs index 878fae85bee..cf6ce64cd4a 100644 --- a/src/Nethermind/Nethermind.Merge.Plugin.Test/EngineModuleTests.HelperFunctions.cs +++ b/src/Nethermind/Nethermind.Merge.Plugin.Test/EngineModuleTests.HelperFunctions.cs @@ -20,10 +20,9 @@ using Nethermind.Specs; using Nethermind.Specs.Forks; using Nethermind.State; -using Nethermind.Core.ConsensusRequests; +using Microsoft.CodeAnalysis; using Nethermind.Blockchain.BeaconBlockRoot; using Nethermind.Core.Specs; -using Nethermind.Specs.Test.ChainSpecStyle; using Nethermind.Evm.Tracing; namespace Nethermind.Merge.Plugin.Test @@ -148,10 +147,10 @@ private static ExecutionPayloadV3 CreateBlockRequestV3( return blockRequestV3; } - private static ExecutionPayloadV4 CreateBlockRequestV4(MergeTestBlockchain chain, ExecutionPayload parent, Address miner, Withdrawal[]? withdrawals = null, - ulong? blobGasUsed = null, ulong? excessBlobGas = null, Transaction[]? transactions = null, Hash256? parentBeaconBlockRoot = null, ConsensusRequest[]? requests = null) + private static ExecutionPayloadV3 CreateBlockRequestV4(MergeTestBlockchain chain, ExecutionPayload parent, Address miner, Withdrawal[]? withdrawals = null, + ulong? blobGasUsed = null, ulong? excessBlobGas = null, Transaction[]? transactions = null, Hash256? parentBeaconBlockRoot = null) { - ExecutionPayloadV4 blockRequestV4 = CreateBlockRequestInternal(parent, miner, withdrawals, blobGasUsed, excessBlobGas, transactions: transactions, parentBeaconBlockRoot: parentBeaconBlockRoot, requests: requests); + ExecutionPayloadV3 blockRequestV4 = CreateBlockRequestInternal(parent, miner, withdrawals, blobGasUsed, excessBlobGas, transactions: transactions, parentBeaconBlockRoot: parentBeaconBlockRoot); blockRequestV4.TryGetBlock(out Block? block); var beaconBlockRootHandler = new BeaconBlockRootHandler(chain.TxProcessor, chain.WorldStateManager.GlobalWorldState); @@ -160,7 +159,7 @@ private static ExecutionPayloadV4 CreateBlockRequestV4(MergeTestBlockchain chain var blockHashStore = new BlockhashStore(chain.SpecProvider, chain.State); blockHashStore.ApplyBlockhashStateChanges(block!.Header); - chain.ConsensusRequestsProcessor?.ProcessRequests(block!, chain.State, Array.Empty(), chain.SpecProvider.GenesisSpec); + chain.ExecutionRequestsProcessor?.ProcessExecutionRequests(block!, chain.State, Array.Empty(), chain.SpecProvider.GenesisSpec); chain.State.Commit(chain.SpecProvider.GenesisSpec); chain.State.RecalculateStateRoot(); @@ -173,18 +172,9 @@ private static ExecutionPayloadV4 CreateBlockRequestV4(MergeTestBlockchain chain } private static T CreateBlockRequestInternal(ExecutionPayload parent, Address miner, Withdrawal[]? withdrawals = null, - ulong? blobGasUsed = null, ulong? excessBlobGas = null, Transaction[]? transactions = null, Hash256? parentBeaconBlockRoot = null, ConsensusRequest[]? requests = null + ulong? blobGasUsed = null, ulong? excessBlobGas = null, Transaction[]? transactions = null, Hash256? parentBeaconBlockRoot = null ) where T : ExecutionPayload, new() { - Deposit[]? deposits = null; - WithdrawalRequest[]? withdrawalRequests = null; - ConsolidationRequest[]? consolidationRequests = null; - - if (requests is not null) - { - (deposits, withdrawalRequests, consolidationRequests) = requests.SplitRequests(); - } - T blockRequest = new() { ParentHash = parent.BlockHash, @@ -199,10 +189,7 @@ private static T CreateBlockRequestInternal(ExecutionPayload parent, Address Withdrawals = withdrawals, BlobGasUsed = blobGasUsed, ExcessBlobGas = excessBlobGas, - ParentBeaconBlockRoot = parentBeaconBlockRoot, - DepositRequests = deposits, - WithdrawalRequests = withdrawalRequests, - ConsolidationRequests = consolidationRequests, + ParentBeaconBlockRoot = parentBeaconBlockRoot }; blockRequest.SetTransactions(transactions ?? Array.Empty()); diff --git a/src/Nethermind/Nethermind.Merge.Plugin.Test/EngineModuleTests.Setup.cs b/src/Nethermind/Nethermind.Merge.Plugin.Test/EngineModuleTests.Setup.cs index d10c9c0744a..7953d25e676 100644 --- a/src/Nethermind/Nethermind.Merge.Plugin.Test/EngineModuleTests.Setup.cs +++ b/src/Nethermind/Nethermind.Merge.Plugin.Test/EngineModuleTests.Setup.cs @@ -12,9 +12,9 @@ using Nethermind.Config; using Nethermind.Consensus; using Nethermind.Consensus.Comparers; +using Nethermind.Consensus.ExecutionRequests; using Nethermind.Consensus.Processing; using Nethermind.Consensus.Producers; -using Nethermind.Consensus.Requests; using Nethermind.Consensus.Rewards; using Nethermind.Consensus.Validators; using Nethermind.Consensus.Withdrawals; @@ -60,8 +60,8 @@ protected virtual MergeTestBlockchain CreateBaseBlockchain( IMergeConfig? mergeConfig = null, IPayloadPreparationService? mockedPayloadService = null, ILogManager? logManager = null, - IConsensusRequestsProcessor? mockedConsensusRequestsProcessor = null) => - new(mergeConfig, mockedPayloadService, logManager, mockedConsensusRequestsProcessor); + IExecutionRequestsProcessor? mockedExecutionRequestsProcessor = null) => + new(mergeConfig, mockedPayloadService, logManager, mockedExecutionRequestsProcessor); protected async Task CreateBlockchain( @@ -69,8 +69,8 @@ protected async Task CreateBlockchain( IMergeConfig? mergeConfig = null, IPayloadPreparationService? mockedPayloadService = null, ILogManager? logManager = null, - IConsensusRequestsProcessor? mockedConsensusRequestsProcessor = null) - => await CreateBaseBlockchain(mergeConfig, mockedPayloadService, logManager, mockedConsensusRequestsProcessor) + IExecutionRequestsProcessor? mockedExecutionRequestsProcessor = null) + => await CreateBaseBlockchain(mergeConfig, mockedPayloadService, logManager, mockedExecutionRequestsProcessor) .Build(new TestSingleReleaseSpecProvider(releaseSpec ?? London.Instance)); protected async Task CreateBlockchain(ISpecProvider specProvider, @@ -142,8 +142,6 @@ protected IEngineRpcModule CreateEngineModule(MergeTestBlockchain chain, ISyncCo new BlocksConfig().SecondsPerSlot), new GetPayloadBodiesByHashV1Handler(chain.BlockTree, chain.LogManager), new GetPayloadBodiesByRangeV1Handler(chain.BlockTree, chain.LogManager), - new GetPayloadBodiesByHashV2Handler(chain.BlockTree, chain.LogManager), - new GetPayloadBodiesByRangeV2Handler(chain.BlockTree, chain.LogManager), new ExchangeTransitionConfigurationV1Handler(chain.PoSSwitcher, chain.LogManager), new ExchangeCapabilitiesHandler(capabilitiesProvider, chain.LogManager), new GetBlobsHandler(chain.TxPool), @@ -182,14 +180,14 @@ public MergeTestBlockchain ThrottleBlockProcessor(int delayMs) return this; } - public MergeTestBlockchain(IMergeConfig? mergeConfig = null, IPayloadPreparationService? mockedPayloadPreparationService = null, ILogManager? logManager = null, IConsensusRequestsProcessor? mockedConsensusRequestsProcessor = null) + public MergeTestBlockchain(IMergeConfig? mergeConfig = null, IPayloadPreparationService? mockedPayloadPreparationService = null, ILogManager? logManager = null, IExecutionRequestsProcessor? mockedExecutionRequestsProcessor = null) { GenesisBlockBuilder = Core.Test.Builders.Build.A.Block.Genesis.Genesis.WithTimestamp(1UL); MergeConfig = mergeConfig ?? new MergeConfig() { TerminalTotalDifficulty = "0" }; PayloadPreparationService = mockedPayloadPreparationService; SyncPeerPool = Substitute.For(); LogManager = logManager ?? LogManager; - ConsensusRequestsProcessor = mockedConsensusRequestsProcessor; + ExecutionRequestsProcessor = mockedExecutionRequestsProcessor; } protected override Task AddBlocksOnStart() => Task.CompletedTask; @@ -228,7 +226,7 @@ protected override IBlockProducer CreateTestBlockProducer(TxPoolTxSource txPoolT transactionComparerProvider, blocksConfig, LogManager, - ConsensusRequestsProcessor); + ExecutionRequestsProcessor); BlockProducerEnv blockProducerEnv = blockProducerEnvFactory.Create(); PostMergeBlockProducer? postMergeBlockProducer = blockProducerFactory.Create(blockProducerEnv); @@ -241,7 +239,7 @@ protected override IBlockProducer CreateTestBlockProducer(TxPoolTxSource txPoolT TimeSpan.FromSeconds(MergeConfig.SecondsPerSlot), 50000); // by default we want to avoid cleanup payload effects in testing - ConsensusRequestsProcessor ??= new ConsensusRequestsProcessor(TxProcessor); + ExecutionRequestsProcessor ??= new ExecutionRequestsProcessor(TxProcessor); return new MergeBlockProducer(preMergeBlockProducer, postMergeBlockProducer, PoSSwitcher); } @@ -262,7 +260,7 @@ protected override IBlockProcessor CreateBlockProcessor() LogManager, WithdrawalProcessor, preWarmer: CreateBlockCachePreWarmer(), - consensusRequestsProcessor: ConsensusRequestsProcessor); + executionRequestsProcessor: ExecutionRequestsProcessor); return new TestBlockProcessorInterceptor(processor, _blockProcessingThrottle); } diff --git a/src/Nethermind/Nethermind.Merge.Plugin.Test/EngineModuleTests.V3.cs b/src/Nethermind/Nethermind.Merge.Plugin.Test/EngineModuleTests.V3.cs index 5fda932e45b..2104570b5f4 100644 --- a/src/Nethermind/Nethermind.Merge.Plugin.Test/EngineModuleTests.V3.cs +++ b/src/Nethermind/Nethermind.Merge.Plugin.Test/EngineModuleTests.V3.cs @@ -375,8 +375,6 @@ public async Task NewPayloadV3_should_verify_blob_versioned_hashes_again Substitute.For(), Substitute.For, IEnumerable>>(), Substitute.For(), - Substitute.For, IEnumerable>>(), - Substitute.For(), Substitute.For>(), Substitute.For, IEnumerable>>(), Substitute.For>>(), diff --git a/src/Nethermind/Nethermind.Merge.Plugin.Test/EngineModuleTests.V4.cs b/src/Nethermind/Nethermind.Merge.Plugin.Test/EngineModuleTests.V4.cs index 7918db73e3c..72a4a39c582 100644 --- a/src/Nethermind/Nethermind.Merge.Plugin.Test/EngineModuleTests.V4.cs +++ b/src/Nethermind/Nethermind.Merge.Plugin.Test/EngineModuleTests.V4.cs @@ -7,11 +7,10 @@ using System.Threading; using System.Threading.Tasks; using FluentAssertions; -using Nethermind.Blockchain; using Nethermind.Consensus.Producers; using Nethermind.Core; -using Nethermind.Core.ConsensusRequests; using Nethermind.Core.Crypto; +using Nethermind.Core.ExecutionRequest; using Nethermind.Core.Extensions; using Nethermind.Core.Test.Builders; using Nethermind.Int256; @@ -19,7 +18,6 @@ using Nethermind.JsonRpc.Test; using Nethermind.Merge.Plugin.Data; using Nethermind.Specs.Forks; -using NSubstitute; using NUnit.Framework; namespace Nethermind.Merge.Plugin.Test; @@ -27,10 +25,10 @@ namespace Nethermind.Merge.Plugin.Test; public partial class EngineModuleTests { [TestCase( - "0x948f67f47376af5d09cc39ec25a84c84774f14b2e80289064c2de73db33cc573", - "0xb8e06e1a99d81358edd0a581fef980aff00cc9c316da8119bec7a13a6e6fa167", + "0xd7e58364f16b4a329b959b166f9c32323cb135669335db5dadd0344568f8dc9a", + "0xfafb92e8ece12d5fcfa867df9ae6865c5bd8aaf0b277c244552bfe869f61fb26", "0xa272b2f949e4a0e411c9b45542bd5d0ef3c311b5f26c4ed6b7a8d4f605a91154", - "0x96b752d22831ad92")] + "0x774c6aff527bbc68")] public virtual async Task Should_process_block_as_expected_V4(string latestValidHash, string blockHash, string stateRoot, string payloadId) { @@ -111,7 +109,7 @@ public virtual async Task Should_process_block_as_expected_V4(string latestValid Array.Empty(), Array.Empty(), withdrawals); - GetPayloadV4Result expectedPayload = new(block, UInt256.Zero, new BlobsBundleV1(block)); + GetPayloadV4Result expectedPayload = new(block, UInt256.Zero, new BlobsBundleV1(block), executionRequests: new byte[][] { Array.Empty(), Array.Empty(), Array.Empty() }); response = await RpcTest.TestSerializedRequest(rpc, "engine_getPayloadV4", expectedPayloadId); successResponse = chain.JsonSerializer.Deserialize(response); @@ -124,7 +122,7 @@ public virtual async Task Should_process_block_as_expected_V4(string latestValid })); response = await RpcTest.TestSerializedRequest(rpc, "engine_newPayloadV4", - chain.JsonSerializer.Serialize(ExecutionPayloadV4.Create(block)), "[]", Keccak.Zero.ToString(true)); + chain.JsonSerializer.Serialize(ExecutionPayloadV3.Create(block)), "[]", Keccak.Zero.ToString(true), "[\"0x\",\"0x\",\"0x\"]"); successResponse = chain.JsonSerializer.Deserialize(response); successResponse.Should().NotBeNull(); @@ -171,10 +169,10 @@ public virtual async Task Should_process_block_as_expected_V4(string latestValid [Test] public async Task NewPayloadV4_reject_payload_with_bad_authorization_list_rlp() { - ConsensusRequestsProcessorMock consensusRequestsProcessorMock = new(); - using MergeTestBlockchain chain = await CreateBlockchain(Prague.Instance, null, null, null, consensusRequestsProcessorMock); + ExecutionRequestsProcessorMock executionRequestsProcessorMock = new(); + using MergeTestBlockchain chain = await CreateBlockchain(Prague.Instance, null, null, null, executionRequestsProcessorMock); IEngineRpcModule rpc = CreateEngineModule(chain); - Hash256 lastHash = (await ProduceBranchV4(rpc, chain, 10, CreateParentBlockRequestOnHead(chain.BlockTree), true)) + Hash256 lastHash = (await ProduceBranchV4(rpc, chain, 10, CreateParentBlockRequestOnHead(chain.BlockTree), true, withRequests: true)) .LastOrDefault()?.BlockHash ?? Keccak.Zero; Transaction invalidSetCodeTx = Build.A.Transaction @@ -196,9 +194,9 @@ public async Task NewPayloadV4_reject_payload_with_bad_authorization_list_rlp() .WithExcessBlobGas(0) .TestObject; - ExecutionPayloadV4 executionPayload = ExecutionPayloadV4.Create(invalidBlock); + ExecutionPayloadV3 executionPayload = ExecutionPayloadV3.Create(invalidBlock); - var response = await rpc.engine_newPayloadV4(executionPayload, [], invalidBlock.ParentBeaconBlockRoot); + var response = await rpc.engine_newPayloadV4(executionPayload, [], invalidBlock.ParentBeaconBlockRoot, executionRequests: ExecutionRequestsProcessorMock.Requests); Assert.That(response.Data.Status, Is.EqualTo("INVALID")); } @@ -219,10 +217,10 @@ public async Task can_progress_chain_one_by_one_v4(int count) [TestCase(30)] public async Task can_progress_chain_one_by_one_v4_with_requests(int count) { - ConsensusRequestsProcessorMock consensusRequestsProcessorMock = new(); - using MergeTestBlockchain chain = await CreateBlockchain(Prague.Instance, null, null, null, consensusRequestsProcessorMock); + ExecutionRequestsProcessorMock executionRequestsProcessorMock = new(); + using MergeTestBlockchain chain = await CreateBlockchain(Prague.Instance, null, null, null, executionRequestsProcessorMock); IEngineRpcModule rpc = CreateEngineModule(chain); - Hash256 lastHash = (await ProduceBranchV4(rpc, chain, count, CreateParentBlockRequestOnHead(chain.BlockTree), true)) + Hash256 lastHash = (await ProduceBranchV4(rpc, chain, count, CreateParentBlockRequestOnHead(chain.BlockTree), true, withRequests: true)) .LastOrDefault()?.BlockHash ?? Keccak.Zero; chain.BlockTree.HeadHash.Should().Be(lastHash); Block? last = RunForAllBlocksInBranch(chain.BlockTree, chain.BlockTree.HeadHash, b => b.IsGenesis, true); @@ -230,12 +228,12 @@ public async Task can_progress_chain_one_by_one_v4_with_requests(int count) last!.IsGenesis.Should().BeTrue(); Block? head = chain.BlockTree.Head; - head!.Requests!.Length.Should().Be(ConsensusRequestsProcessorMock.Requests.Length); + head!.ExecutionRequests!.ToArray().Length.Should().Be(ExecutionRequestsProcessorMock.Requests.Length); } private async Task> ProduceBranchV4(IEngineRpcModule rpc, MergeTestBlockchain chain, - int count, ExecutionPayload startingParentBlock, bool setHead, Hash256? random = null) + int count, ExecutionPayload startingParentBlock, bool setHead, Hash256? random = null, bool withRequests = false) { List blocks = new(); ExecutionPayload parentBlock = startingParentBlock; @@ -247,10 +245,10 @@ private async Task> ProduceBranchV4(IEngineRpcMo parentHeader.Difficulty; for (int i = 0; i < count; i++) { - ExecutionPayloadV4? getPayloadResult = await BuildAndGetPayloadOnBranchV4(rpc, chain, parentHeader, + ExecutionPayloadV3? getPayloadResult = await BuildAndGetPayloadOnBranchV4(rpc, chain, parentHeader, parentBlock.Timestamp + 12, random ?? TestItem.KeccakA, Address.Zero); - PayloadStatusV1 payloadStatusResponse = (await rpc.engine_newPayloadV4(getPayloadResult, Array.Empty(), Keccak.Zero)).Data; + PayloadStatusV1 payloadStatusResponse = (await rpc.engine_newPayloadV4(getPayloadResult, Array.Empty(), Keccak.Zero, executionRequests: withRequests ? ExecutionRequestsProcessorMock.Requests : new byte[][] { Array.Empty(), Array.Empty(), Array.Empty() })).Data; payloadStatusResponse.Status.Should().Be(PayloadStatus.Valid); if (setHead) { @@ -271,7 +269,7 @@ private async Task> ProduceBranchV4(IEngineRpcMo return blocks; } - private async Task BuildAndGetPayloadOnBranchV4( + private async Task BuildAndGetPayloadOnBranchV4( IEngineRpcModule rpc, MergeTestBlockchain chain, BlockHeader parentHeader, ulong timestamp, Hash256 random, Address feeRecipient) { @@ -286,142 +284,13 @@ private async Task BuildAndGetPayloadOnBranchV4( return getPayloadResult.Data!.ExecutionPayload!; } - [Test] - public async Task getPayloadBodiesByRangeV2_should_fail_when_too_many_payloads_requested() - { - using MergeTestBlockchain chain = await CreateBlockchain(); - IEngineRpcModule rpc = CreateEngineModule(chain); - Task>> result = - rpc.engine_getPayloadBodiesByRangeV2(1, 1025); - - result.Result.ErrorCode.Should().Be(MergeErrorCodes.TooLargeRequest); - } - - [Test] - public async Task getPayloadBodiesByHashV2_should_fail_when_too_many_payloads_requested() - { - using MergeTestBlockchain chain = await CreateBlockchain(); - IEngineRpcModule rpc = CreateEngineModule(chain); - Hash256[] hashes = Enumerable.Repeat(TestItem.KeccakA, 1025).ToArray(); - Task>> result = - rpc.engine_getPayloadBodiesByHashV2(hashes); - - result.Result.ErrorCode.Should().Be(MergeErrorCodes.TooLargeRequest); - } - - [Test] - public async Task getPayloadBodiesByRangeV2_should_fail_when_params_below_1() - { - using MergeTestBlockchain chain = await CreateBlockchain(); - IEngineRpcModule rpc = CreateEngineModule(chain); - Task>> result = - rpc.engine_getPayloadBodiesByRangeV2(0, 1); - - result.Result.ErrorCode.Should().Be(ErrorCodes.InvalidParams); - - result = await rpc.engine_getPayloadBodiesByRangeV2(1, 0); - result.Result.ErrorCode.Should().Be(ErrorCodes.InvalidParams); - } - - [Test] - public async Task getPayloadBodiesByRangeV2_should_return_up_to_best_body_number() + private static IEnumerable> GetPayloadRequestsTestCases() { - IBlockTree? blockTree = Substitute.For(); - - blockTree.FindBlock(Arg.Any()) - .Returns(i => Build.A.Block.WithNumber(i.ArgAt(0)).TestObject); - blockTree.Head.Returns(Build.A.Block.WithNumber(5).TestObject); - - using MergeTestBlockchain chain = await CreateBlockchain(Prague.Instance); - chain.BlockTree = blockTree; - - IEngineRpcModule rpc = CreateEngineModule(chain); - IEnumerable payloadBodies = - rpc.engine_getPayloadBodiesByRangeV2(1, 7).Result.Data; - - payloadBodies.Count().Should().Be(5); - } - - private static IEnumerable> GetPayloadRequestsTestCases() - { - yield return ConsensusRequestsProcessorMock.Requests; - } - - [TestCaseSource(nameof(GetPayloadRequestsTestCases))] - public virtual async Task - getPayloadBodiesByHashV2_should_return_payload_bodies_in_order_of_request_block_hashes_and_null_for_unknown_hashes( - ConsensusRequest[]? requests) - { - Deposit[]? deposits = null; - WithdrawalRequest[]? withdrawalRequests = null; - ConsolidationRequest[]? consolidationRequests = null; - - if (requests is not null) - { - (deposits, withdrawalRequests, consolidationRequests) = requests.SplitRequests(); - } - ConsensusRequestsProcessorMock consensusRequestsProcessorMock = new(); - using MergeTestBlockchain chain = await CreateBlockchain(Prague.Instance, null, null, null, consensusRequestsProcessorMock); - IEngineRpcModule rpc = CreateEngineModule(chain); - ExecutionPayloadV4 executionPayload1 = await BuildAndSendNewBlockV4(rpc, chain, true, Array.Empty()); - ExecutionPayloadV4 executionPayload2 = await BuildAndSendNewBlockV4(rpc, chain, true, Array.Empty()); - Hash256[] blockHashes = [executionPayload1.BlockHash, TestItem.KeccakA, executionPayload2.BlockHash]; - IEnumerable payloadBodies = - rpc.engine_getPayloadBodiesByHashV2(blockHashes).Data; - ExecutionPayloadBodyV2Result?[] expected = { - new (Array.Empty(), Array.Empty() , deposits, withdrawalRequests, consolidationRequests), - null, - new (Array.Empty(), Array.Empty(), deposits, withdrawalRequests,consolidationRequests), - }; - payloadBodies.Should().BeEquivalentTo(expected, o => o.WithStrictOrdering()); - } - - [TestCaseSource(nameof(GetPayloadRequestsTestCases))] - public virtual async Task - getPayloadBodiesByRangeV2_should_return_payload_bodies_in_order_of_request_range_and_null_for_unknown_indexes( - ConsensusRequest[]? requests) - { - Deposit[]? deposits = null; - WithdrawalRequest[]? withdrawalRequests = null; - ConsolidationRequest[]? consolidationRequests = null; - - if (requests is not null) - { - (deposits, withdrawalRequests, consolidationRequests) = requests.SplitRequests(); - } - - ConsensusRequestsProcessorMock consensusRequestsProcessorMock = new(); - using MergeTestBlockchain chain = await CreateBlockchain(Prague.Instance, null, null, null, consensusRequestsProcessorMock); - IEngineRpcModule rpc = CreateEngineModule(chain); - await BuildAndSendNewBlockV4(rpc, chain, true, Array.Empty()); - ExecutionPayloadV4 executionPayload2 = await BuildAndSendNewBlockV4(rpc, chain, true, Array.Empty()); - await rpc.engine_forkchoiceUpdatedV3(new ForkchoiceStateV1(executionPayload2.BlockHash!, - executionPayload2.BlockHash!, executionPayload2.BlockHash!)); - - IEnumerable payloadBodies = - rpc.engine_getPayloadBodiesByRangeV2(1, 3).Result.Data; - ExecutionPayloadBodyV2Result?[] expected = - { - new (Array.Empty(), Array.Empty() , deposits, withdrawalRequests, consolidationRequests), - }; - - payloadBodies.Should().BeEquivalentTo(expected, o => o.WithStrictOrdering()); - } - - [Test] - public async Task getPayloadBodiesByRangeV2_empty_response() - { - using MergeTestBlockchain chain = await CreateBlockchain(); - IEngineRpcModule rpc = CreateEngineModule(chain); - IEnumerable payloadBodies = - rpc.engine_getPayloadBodiesByRangeV2(1, 1).Result.Data; - ExecutionPayloadBodyV2Result?[] expected = Array.Empty(); - - payloadBodies.Should().BeEquivalentTo(expected); + yield return ExecutionRequestsProcessorMock.Requests; } - private async Task BuildAndSendNewBlockV4( + private async Task BuildAndSendNewBlockV4( IEngineRpcModule rpc, MergeTestBlockchain chain, bool waitForBlockImprovement, @@ -431,15 +300,15 @@ private async Task BuildAndSendNewBlockV4( ulong timestamp = Timestamper.UnixTime.Seconds; Hash256 random = Keccak.Zero; Address feeRecipient = Address.Zero; - ExecutionPayloadV4 executionPayload = await BuildAndGetPayloadResultV4(rpc, chain, head, + ExecutionPayloadV3 executionPayload = await BuildAndGetPayloadResultV4(rpc, chain, head, Keccak.Zero, head, timestamp, random, feeRecipient, withdrawals, waitForBlockImprovement); ResultWrapper executePayloadResult = - await rpc.engine_newPayloadV4(executionPayload, new byte[0][], executionPayload.ParentBeaconBlockRoot); + await rpc.engine_newPayloadV4(executionPayload, new byte[0][], executionPayload.ParentBeaconBlockRoot, executionRequests: ExecutionRequestsProcessorMock.Requests); executePayloadResult.Data.Status.Should().Be(PayloadStatus.Valid); return executionPayload; } - private async Task BuildAndGetPayloadResultV4( + private async Task BuildAndGetPayloadResultV4( IEngineRpcModule rpc, MergeTestBlockchain chain, Hash256 headBlockHash, diff --git a/src/Nethermind/Nethermind.Merge.Plugin.Test/ExecutionRequestsProcessorMock.cs b/src/Nethermind/Nethermind.Merge.Plugin.Test/ExecutionRequestsProcessorMock.cs new file mode 100644 index 00000000000..07bab9aed6a --- /dev/null +++ b/src/Nethermind/Nethermind.Merge.Plugin.Test/ExecutionRequestsProcessorMock.cs @@ -0,0 +1,56 @@ +// SPDX-FileCopyrightText: 2024 Demerzel Solutions Limited +// SPDX-License-Identifier: LGPL-3.0-only + +using System.Linq; +using DotNetty.Common.Utilities; +using Nethermind.Consensus.ExecutionRequests; +using Nethermind.Core; +using Nethermind.Core.Collections; +using Nethermind.Core.ExecutionRequest; +using Nethermind.Core.Specs; +using Nethermind.Core.Test.Builders; +using Nethermind.State; + +namespace Nethermind.Merge.Plugin.Test; + +public class ExecutionRequestsProcessorMock : IExecutionRequestsProcessor +{ + public static TestExecutionRequest[] depositRequests = + [ + TestItem.ExecutionRequestA, + TestItem.ExecutionRequestB, + TestItem.ExecutionRequestC + ]; + + public static TestExecutionRequest[] withdrawalRequests = + [ + TestItem.ExecutionRequestD, + TestItem.ExecutionRequestE, + TestItem.ExecutionRequestF + ]; + + public static TestExecutionRequest[] consolidationsRequests = + [ + TestItem.ExecutionRequestG, + TestItem.ExecutionRequestH, + TestItem.ExecutionRequestI + ]; + + public static byte[][] Requests + { + get + { + using ArrayPoolList list = TestExecutionRequestExtensions.GetFlatEncodedRequests(depositRequests, withdrawalRequests, consolidationsRequests); + return list.ToArray(); + } + } + + public void ProcessExecutionRequests(Block block, IWorldState state, TxReceipt[] receipts, IReleaseSpec spec) + { + if (block.IsGenesis) + return; + + block.ExecutionRequests = Requests; + block.Header.RequestsHash = ExecutionRequestExtensions.CalculateHashFromFlatEncodedRequests(Requests); + } +} diff --git a/src/Nethermind/Nethermind.Merge.Plugin/Data/ExecutionPayload.cs b/src/Nethermind/Nethermind.Merge.Plugin/Data/ExecutionPayload.cs index d1c7f7c6554..0d5ecbd7b42 100644 --- a/src/Nethermind/Nethermind.Merge.Plugin/Data/ExecutionPayload.cs +++ b/src/Nethermind/Nethermind.Merge.Plugin/Data/ExecutionPayload.cs @@ -12,7 +12,7 @@ using Nethermind.Serialization.Rlp; using Nethermind.State.Proofs; using System.Text.Json.Serialization; -using Nethermind.Core.ConsensusRequests; +using Nethermind.Core.ExecutionRequest; namespace Nethermind.Merge.Plugin.Data; @@ -77,23 +77,11 @@ public byte[][] Transactions /// - /// Gets or sets a collection of as defined in - /// EIP-6110. + /// Gets or sets a collection of as defined in + /// EIP-7685. /// - public virtual Deposit[]? DepositRequests { get; set; } - - - /// - /// Gets or sets a collection of as defined in - /// EIP-7002. - /// - public virtual WithdrawalRequest[]? WithdrawalRequests { get; set; } - - /// - /// Gets or sets a collection of as defined in - /// EIP-7251. - /// - public virtual ConsolidationRequest[]? ConsolidationRequests { get; set; } + [JsonIgnore] + public virtual byte[][]? ExecutionRequests { get; set; } /// @@ -232,12 +220,6 @@ public ValidationResult ValidateParams(IReleaseSpec spec, int version, out strin return ValidationResult.Fail; } - if (spec.RequestsEnabled) - { - error = "ExecutionPayloadV4 expected"; - return ValidationResult.Fail; - } - int actualVersion = GetExecutionPayloadVersion(); error = actualVersion switch @@ -252,7 +234,7 @@ public ValidationResult ValidateParams(IReleaseSpec spec, int version, out strin protected virtual int GetExecutionPayloadVersion() => this switch { - { DepositRequests: not null, WithdrawalRequests: not null, ConsolidationRequests: not null } => 4, + { ExecutionRequests: not null } => 4, { BlobGasUsed: not null } or { ExcessBlobGas: not null } or { ParentBeaconBlockRoot: not null } => 3, { Withdrawals: not null } => 2, _ => 1 diff --git a/src/Nethermind/Nethermind.Merge.Plugin/Data/ExecutionPayloadBodyV2Result.cs b/src/Nethermind/Nethermind.Merge.Plugin/Data/ExecutionPayloadBodyV2Result.cs deleted file mode 100644 index d929fcf6fd8..00000000000 --- a/src/Nethermind/Nethermind.Merge.Plugin/Data/ExecutionPayloadBodyV2Result.cs +++ /dev/null @@ -1,44 +0,0 @@ -// SPDX-FileCopyrightText: 2024 Demerzel Solutions Limited -// SPDX-License-Identifier: LGPL-3.0-only - -using System.Collections.Generic; -using Nethermind.Core; -using Nethermind.Core.ConsensusRequests; -using System.Text.Json.Serialization; - -namespace Nethermind.Merge.Plugin.Data; - -public class ExecutionPayloadBodyV2Result : ExecutionPayloadBodyV1Result -{ - public ExecutionPayloadBodyV2Result( - IReadOnlyList transactions, - IReadOnlyList? withdrawals, - IReadOnlyList? deposits, - IReadOnlyList? withdrawalsRequests, - IReadOnlyList? consolidationRequests - ) - : base(transactions, withdrawals) - { - DepositRequests = deposits; - WithdrawalRequests = withdrawalsRequests; - ConsolidationRequests = consolidationRequests; - } - - /// - /// Deposit requests . - /// - [JsonIgnore(Condition = JsonIgnoreCondition.Never)] - public IReadOnlyList? DepositRequests { get; set; } - - /// - /// Withdrawal requests . - /// - [JsonIgnore(Condition = JsonIgnoreCondition.Never)] - public IReadOnlyList? WithdrawalRequests { get; set; } - - /// - /// Consolidation requests . - /// - [JsonIgnore(Condition = JsonIgnoreCondition.Never)] - public IReadOnlyList? ConsolidationRequests { get; set; } -} diff --git a/src/Nethermind/Nethermind.Merge.Plugin/Data/ExecutionPayloadV3.cs b/src/Nethermind/Nethermind.Merge.Plugin/Data/ExecutionPayloadV3.cs index f05e355b183..62d3f85e99d 100644 --- a/src/Nethermind/Nethermind.Merge.Plugin/Data/ExecutionPayloadV3.cs +++ b/src/Nethermind/Nethermind.Merge.Plugin/Data/ExecutionPayloadV3.cs @@ -5,6 +5,7 @@ using System.Text.Json.Serialization; using Nethermind.Core; using Nethermind.Core.Crypto; +using Nethermind.Core.ExecutionRequest; using Nethermind.Core.Specs; using Nethermind.Int256; @@ -36,6 +37,7 @@ public override bool TryGetBlock([NotNullWhen(true)] out Block? block, UInt256? block.Header.ParentBeaconBlockRoot = ParentBeaconBlockRoot; block.Header.BlobGasUsed = BlobGasUsed; block.Header.ExcessBlobGas = ExcessBlobGas; + block.Header.RequestsHash = ExecutionRequests is not null ? ExecutionRequestExtensions.CalculateHashFromFlatEncodedRequests(ExecutionRequests) : null; return true; } diff --git a/src/Nethermind/Nethermind.Merge.Plugin/Data/ExecutionPayloadV4.cs b/src/Nethermind/Nethermind.Merge.Plugin/Data/ExecutionPayloadV4.cs deleted file mode 100644 index e0d65da1215..00000000000 --- a/src/Nethermind/Nethermind.Merge.Plugin/Data/ExecutionPayloadV4.cs +++ /dev/null @@ -1,101 +0,0 @@ -// SPDX-FileCopyrightText: 2022 Demerzel Solutions Limited -// SPDX-License-Identifier: LGPL-3.0-only - -using System; -using System.Collections.Generic; -using System.Diagnostics.CodeAnalysis; -using System.Linq; -using System.Runtime.InteropServices.JavaScript; -using System.Text.Json.Serialization; -using Nethermind.Core; -using Nethermind.Core.ConsensusRequests; -using Nethermind.Core.Crypto; -using Nethermind.Core.Specs; -using Nethermind.Int256; -using Nethermind.State.Proofs; - -namespace Nethermind.Merge.Plugin.Data; - -/// -/// Represents an object mapping the ExecutionPayloadV4 structure of the beacon chain spec. -/// -public class ExecutionPayloadV4 : ExecutionPayloadV3, IExecutionPayloadFactory -{ - protected new static TExecutionPayload Create(Block block) where TExecutionPayload : ExecutionPayloadV4, new() - { - TExecutionPayload executionPayload = ExecutionPayloadV3.Create(block); - ConsensusRequest[]? blockRequests = block.Requests; - (executionPayload.DepositRequests, executionPayload.WithdrawalRequests, executionPayload.ConsolidationRequests) = blockRequests?.SplitRequests() ?? ([], [], []); - return executionPayload; - } - - public new static ExecutionPayloadV4 Create(Block block) => Create(block); - - public override bool TryGetBlock([NotNullWhen(true)] out Block? block, UInt256? totalDifficulty = null) - { - if (!base.TryGetBlock(out block, totalDifficulty)) - { - return false; - } - - var depositsLength = DepositRequests?.Length ?? 0; - var withdrawalRequestsLength = WithdrawalRequests?.Length ?? 0; - var consolidationRequestsLength = ConsolidationRequests?.Length ?? 0; - var requestsCount = depositsLength + withdrawalRequestsLength + consolidationRequestsLength; - if (requestsCount > 0) - { - var requests = new ConsensusRequest[requestsCount]; - int i = 0; - for (; i < depositsLength; ++i) - { - requests[i] = DepositRequests![i]; - } - - for (; i < depositsLength + withdrawalRequestsLength; ++i) - { - requests[i] = WithdrawalRequests![i - depositsLength]; - } - - for (; i < requestsCount; ++i) - { - requests[i] = ConsolidationRequests![i - depositsLength - withdrawalRequestsLength]; - } - - block.Body.Requests = requests; - block.Header.RequestsRoot = new RequestsTrie(requests).RootHash; - } - else - { - block.Body.Requests = Array.Empty(); - block.Header.RequestsRoot = Keccak.EmptyTreeHash; - } - - return true; - } - - public override bool ValidateFork(ISpecProvider specProvider) => - specProvider.GetSpec(BlockNumber, Timestamp).DepositsEnabled - && specProvider.GetSpec(BlockNumber, Timestamp).WithdrawalRequestsEnabled - && specProvider.GetSpec(BlockNumber, Timestamp).ConsolidationRequestsEnabled; - - /// - /// Gets or sets as defined in - /// EIP-6110. - /// - [JsonRequired] - public sealed override Deposit[]? DepositRequests { get; set; } - - /// - /// Gets or sets as defined in - /// EIP-7002. - /// - [JsonRequired] - public sealed override WithdrawalRequest[]? WithdrawalRequests { get; set; } - - /// - /// Gets or sets as defined in - /// EIP-7251. - /// - [JsonRequired] - public sealed override ConsolidationRequest[]? ConsolidationRequests { get; set; } -} diff --git a/src/Nethermind/Nethermind.Merge.Plugin/Data/GetPayloadV4Result.cs b/src/Nethermind/Nethermind.Merge.Plugin/Data/GetPayloadV4Result.cs index 4f13cf363bf..e1e1fcaa934 100644 --- a/src/Nethermind/Nethermind.Merge.Plugin/Data/GetPayloadV4Result.cs +++ b/src/Nethermind/Nethermind.Merge.Plugin/Data/GetPayloadV4Result.cs @@ -2,8 +2,15 @@ // SPDX-License-Identifier: LGPL-3.0-only using Nethermind.Core; +using Nethermind.Core.ExecutionRequest; using Nethermind.Int256; namespace Nethermind.Merge.Plugin.Data; -public class GetPayloadV4Result(Block block, UInt256 blockFees, BlobsBundleV1 blobsBundle) : GetPayloadV3Result(block, blockFees, blobsBundle); +public class GetPayloadV4Result(Block block, UInt256 blockFees, BlobsBundleV1 blobsBundle, byte[][] executionRequests) : GetPayloadV3Result(block, blockFees, blobsBundle) +{ + public byte[][]? ExecutionRequests { get; } = executionRequests; + + public override string ToString() => + $"{{ExecutionPayload: {ExecutionPayload}, Fees: {BlockValue}, BlobsBundle blobs count: {BlobsBundle.Blobs.Length}, ShouldOverrideBuilder {ShouldOverrideBuilder}, ExecutionRequests count : {ExecutionRequests?.Length}}}"; +} diff --git a/src/Nethermind/Nethermind.Merge.Plugin/Data/IExecutionPayloadParams.cs b/src/Nethermind/Nethermind.Merge.Plugin/Data/IExecutionPayloadParams.cs index 46abda52dde..ca52c480c0e 100644 --- a/src/Nethermind/Nethermind.Merge.Plugin/Data/IExecutionPayloadParams.cs +++ b/src/Nethermind/Nethermind.Merge.Plugin/Data/IExecutionPayloadParams.cs @@ -5,6 +5,7 @@ using System.Linq; using Nethermind.Core; using Nethermind.Core.Crypto; +using Nethermind.Core.ExecutionRequest; using Nethermind.Core.Extensions; using Nethermind.Core.Specs; using Nethermind.Serialization.Rlp; @@ -14,6 +15,7 @@ namespace Nethermind.Merge.Plugin.Data; public interface IExecutionPayloadParams { ExecutionPayload ExecutionPayload { get; } + byte[][]? ExecutionRequests { get; set; } ValidationResult ValidateParams(IReleaseSpec spec, int version, out string? error); } @@ -22,15 +24,37 @@ public enum ValidationResult : byte { Success, Fail, Invalid }; public class ExecutionPayloadParams( TVersionedExecutionPayload executionPayload, byte[]?[] blobVersionedHashes, - Hash256? parentBeaconBlockRoot) + Hash256? parentBeaconBlockRoot, + byte[][]? executionRequests = null) : IExecutionPayloadParams where TVersionedExecutionPayload : ExecutionPayload { public TVersionedExecutionPayload ExecutionPayload => executionPayload; + /// + /// Gets or sets as defined in + /// EIP-7685. + /// + public byte[][]? ExecutionRequests { get; set; } = executionRequests; + ExecutionPayload IExecutionPayloadParams.ExecutionPayload => ExecutionPayload; public ValidationResult ValidateParams(IReleaseSpec spec, int version, out string? error) { + if (spec.RequestsEnabled) + { + if (ExecutionRequests is null) + { + error = "Execution requests must be set"; + return ValidationResult.Fail; + } + + if (ExecutionRequests.Length != ExecutionRequestExtensions.RequestPartsCount) + { + error = "Execution requests must have exactly three items"; + return ValidationResult.Invalid; + } + + } Transaction[]? transactions; try { diff --git a/src/Nethermind/Nethermind.Merge.Plugin/EngineRpcModule.Paris.cs b/src/Nethermind/Nethermind.Merge.Plugin/EngineRpcModule.Paris.cs index 4cf84584a76..89ed9992adf 100644 --- a/src/Nethermind/Nethermind.Merge.Plugin/EngineRpcModule.Paris.cs +++ b/src/Nethermind/Nethermind.Merge.Plugin/EngineRpcModule.Paris.cs @@ -7,6 +7,8 @@ using System.Threading.Tasks; using Nethermind.Consensus; using Nethermind.Consensus.Producers; +using Nethermind.Core.Crypto; +using Nethermind.Core.ExecutionRequest; using Nethermind.Core.Specs; using Nethermind.JsonRpc; using Nethermind.Merge.Plugin.Data; @@ -62,6 +64,7 @@ protected async Task> ForkchoiceUpdated protected async Task> NewPayload(IExecutionPayloadParams executionPayloadParams, int version) { ExecutionPayload executionPayload = executionPayloadParams.ExecutionPayload; + executionPayload.ExecutionRequests = executionPayloadParams.ExecutionRequests; if (!executionPayload.ValidateFork(_specProvider)) { diff --git a/src/Nethermind/Nethermind.Merge.Plugin/EngineRpcModule.Prague.cs b/src/Nethermind/Nethermind.Merge.Plugin/EngineRpcModule.Prague.cs index a787498000e..d554751d993 100644 --- a/src/Nethermind/Nethermind.Merge.Plugin/EngineRpcModule.Prague.cs +++ b/src/Nethermind/Nethermind.Merge.Plugin/EngineRpcModule.Prague.cs @@ -1,10 +1,10 @@ // SPDX-FileCopyrightText: 2022 Demerzel Solutions Limited // SPDX-License-Identifier: LGPL-3.0-only -using System.Collections.Generic; using System.Threading.Tasks; using Nethermind.Consensus; using Nethermind.Core.Crypto; +using Nethermind.Core.ExecutionRequest; using Nethermind.JsonRpc; using Nethermind.Merge.Plugin.Data; using Nethermind.Merge.Plugin.Handlers; @@ -13,20 +13,17 @@ namespace Nethermind.Merge.Plugin; public partial class EngineRpcModule : IEngineRpcModule { - private readonly IAsyncHandler _getPayloadHandlerV4; + IAsyncHandler _getPayloadHandlerV4; - private readonly IHandler, IEnumerable> _executionGetPayloadBodiesByHashV2Handler; - private readonly IGetPayloadBodiesByRangeV2Handler _executionGetPayloadBodiesByRangeV2Handler; - - public Task> engine_newPayloadV4(ExecutionPayloadV4 executionPayload, byte[]?[] blobVersionedHashes, Hash256? parentBeaconBlockRoot) => - NewPayload(new ExecutionPayloadParams(executionPayload, blobVersionedHashes, parentBeaconBlockRoot), EngineApiVersions.Prague); + /// + /// Method parameter list is extended with parameter. + /// EIP-7685. + /// + public Task> engine_newPayloadV4(ExecutionPayloadV3 executionPayload, byte[]?[] blobVersionedHashes, Hash256? parentBeaconBlockRoot, byte[][]? executionRequests) + { + return NewPayload(new ExecutionPayloadParams(executionPayload, blobVersionedHashes, parentBeaconBlockRoot, executionRequests), EngineApiVersions.Prague); + } public async Task> engine_getPayloadV4(byte[] payloadId) => await _getPayloadHandlerV4.HandleAsync(payloadId); - - public ResultWrapper> engine_getPayloadBodiesByHashV2(IReadOnlyList blockHashes) - => _executionGetPayloadBodiesByHashV2Handler.Handle(blockHashes); - - public Task>> engine_getPayloadBodiesByRangeV2(long start, long count) - => _executionGetPayloadBodiesByRangeV2Handler.Handle(start, count); } diff --git a/src/Nethermind/Nethermind.Merge.Plugin/EngineRpcModule.cs b/src/Nethermind/Nethermind.Merge.Plugin/EngineRpcModule.cs index 37c244ae47f..9a711d9aa3b 100644 --- a/src/Nethermind/Nethermind.Merge.Plugin/EngineRpcModule.cs +++ b/src/Nethermind/Nethermind.Merge.Plugin/EngineRpcModule.cs @@ -29,8 +29,6 @@ public EngineRpcModule( IForkchoiceUpdatedHandler forkchoiceUpdatedV1Handler, IHandler, IEnumerable> executionGetPayloadBodiesByHashV1Handler, IGetPayloadBodiesByRangeV1Handler executionGetPayloadBodiesByRangeV1Handler, - IHandler, IEnumerable> executionGetPayloadBodiesByHashV2Handler, - IGetPayloadBodiesByRangeV2Handler executionGetPayloadBodiesByRangeV2Handler, IHandler transitionConfigurationHandler, IHandler, IEnumerable> capabilitiesHandler, IAsyncHandler> getBlobsHandler, @@ -47,8 +45,6 @@ public EngineRpcModule( _forkchoiceUpdatedV1Handler = forkchoiceUpdatedV1Handler; _executionGetPayloadBodiesByHashV1Handler = executionGetPayloadBodiesByHashV1Handler; _executionGetPayloadBodiesByRangeV1Handler = executionGetPayloadBodiesByRangeV1Handler; - _executionGetPayloadBodiesByHashV2Handler = executionGetPayloadBodiesByHashV2Handler; - _executionGetPayloadBodiesByRangeV2Handler = executionGetPayloadBodiesByRangeV2Handler; _transitionConfigurationHandler = transitionConfigurationHandler; _getBlobsHandler = getBlobsHandler; _specProvider = specProvider ?? throw new ArgumentNullException(nameof(specProvider)); diff --git a/src/Nethermind/Nethermind.Merge.Plugin/Handlers/EngineRpcCapabilitiesProvider.cs b/src/Nethermind/Nethermind.Merge.Plugin/Handlers/EngineRpcCapabilitiesProvider.cs index 57d1ab5f5bd..3edcb837a34 100644 --- a/src/Nethermind/Nethermind.Merge.Plugin/Handlers/EngineRpcCapabilitiesProvider.cs +++ b/src/Nethermind/Nethermind.Merge.Plugin/Handlers/EngineRpcCapabilitiesProvider.cs @@ -51,15 +51,6 @@ public EngineRpcCapabilitiesProvider(ISpecProvider specProvider) #region Prague _capabilities[nameof(IEngineRpcModule.engine_getPayloadV4)] = (spec.RequestsEnabled, spec.RequestsEnabled); _capabilities[nameof(IEngineRpcModule.engine_newPayloadV4)] = (spec.RequestsEnabled, spec.RequestsEnabled); - _capabilities[nameof(IEngineRpcModule.engine_getPayloadBodiesByHashV2)] = (spec.RequestsEnabled, false); - _capabilities[nameof(IEngineRpcModule.engine_getPayloadBodiesByRangeV2)] = (spec.RequestsEnabled, false); - #endregion - - #region Prague - _capabilities[nameof(IEngineRpcModule.engine_getPayloadV4)] = (spec.RequestsEnabled, spec.RequestsEnabled); - _capabilities[nameof(IEngineRpcModule.engine_newPayloadV4)] = (spec.RequestsEnabled, spec.RequestsEnabled); - _capabilities[nameof(IEngineRpcModule.engine_getPayloadBodiesByHashV2)] = (spec.RequestsEnabled, false); - _capabilities[nameof(IEngineRpcModule.engine_getPayloadBodiesByRangeV2)] = (spec.RequestsEnabled, false); #endregion } diff --git a/src/Nethermind/Nethermind.Merge.Plugin/Handlers/GetPayloadBodiesByHashV2Handler.cs b/src/Nethermind/Nethermind.Merge.Plugin/Handlers/GetPayloadBodiesByHashV2Handler.cs deleted file mode 100644 index 0c95bbd88b0..00000000000 --- a/src/Nethermind/Nethermind.Merge.Plugin/Handlers/GetPayloadBodiesByHashV2Handler.cs +++ /dev/null @@ -1,38 +0,0 @@ -// SPDX-FileCopyrightText: 2024 Demerzel Solutions Limited -// SPDX-License-Identifier: LGPL-3.0-only - -using System; -using System.Collections.Generic; -using System.Linq; -using System.Threading.Tasks; -using Nethermind.Blockchain; -using Nethermind.Core; -using Nethermind.Core.ConsensusRequests; -using Nethermind.Core.Crypto; -using Nethermind.JsonRpc; -using Nethermind.Logging; -using Nethermind.Merge.Plugin.Data; - -namespace Nethermind.Merge.Plugin.Handlers; - - -public class GetPayloadBodiesByHashV2Handler(IBlockTree blockTree, ILogManager logManager) - : GetPayloadBodiesByHashV1Handler(blockTree, logManager), IHandler, IEnumerable> -{ - private readonly IBlockTree _blockTree = blockTree; - - public new ResultWrapper> Handle(IReadOnlyList blockHashes) => - !CheckHashCount(blockHashes, out string? error) - ? ResultWrapper>.Fail(error!, MergeErrorCodes.TooLargeRequest) - : ResultWrapper>.Success(GetRequests(blockHashes)); - - private IEnumerable GetRequests(IReadOnlyList blockHashes) - { - for (int i = 0; i < blockHashes.Count; i++) - { - Block? block = _blockTree.FindBlock(blockHashes[i]); - (Deposit[]? deposits, WithdrawalRequest[]? withdrawalRequests, ConsolidationRequest[]? consolidationRequests) = block?.Requests?.SplitRequests() ?? (null, null, null); - yield return block is null ? null : new ExecutionPayloadBodyV2Result(block.Transactions, block.Withdrawals, deposits, withdrawalRequests, consolidationRequests); - } - } -} diff --git a/src/Nethermind/Nethermind.Merge.Plugin/Handlers/GetPayloadBodiesByRangeV2Handler.cs b/src/Nethermind/Nethermind.Merge.Plugin/Handlers/GetPayloadBodiesByRangeV2Handler.cs deleted file mode 100644 index f1a3107457d..00000000000 --- a/src/Nethermind/Nethermind.Merge.Plugin/Handlers/GetPayloadBodiesByRangeV2Handler.cs +++ /dev/null @@ -1,51 +0,0 @@ -// SPDX-FileCopyrightText: 2024 Demerzel Solutions Limited -// SPDX-License-Identifier: LGPL-3.0-only - - -using System; -using System.Collections; -using System.Collections.Generic; -using System.Linq; -using System.Threading.Tasks; -using Nethermind.Blockchain; -using Nethermind.Core; -using Nethermind.Core.ConsensusRequests; -using Nethermind.JsonRpc; -using Nethermind.Logging; -using Nethermind.Merge.Plugin.Data; - -namespace Nethermind.Merge.Plugin.Handlers; - -public class GetPayloadBodiesByRangeV2Handler(IBlockTree blockTree, ILogManager logManager) : GetPayloadBodiesByRangeV1Handler(blockTree, logManager), IGetPayloadBodiesByRangeV2Handler -{ - public new Task>> Handle(long start, long count) - { - if (!CheckRangeCount(start, count, out string? error, out int errorCode)) - { - return ResultWrapper>.Fail(error!, errorCode); - } - - return Task.FromResult(ResultWrapper>.Success(GetRequests(start, count))); - } - - - private IEnumerable GetRequests(long start, long count) - { - var headNumber = _blockTree.Head?.Number ?? 0; - for (long i = start, c = Math.Min(start + count - 1, headNumber); i <= c; i++) - { - Block? block = _blockTree.FindBlock(i); - - if (block is null) - { - yield return null; - continue; - } - - (Deposit[]? deposits, WithdrawalRequest[]? withdrawalRequests, ConsolidationRequest[]? consolidationRequests) = block!.Requests?.SplitRequests() ?? (null, null, null); - yield return new ExecutionPayloadBodyV2Result(block.Transactions, block.Withdrawals, deposits, withdrawalRequests, consolidationRequests); - } - - yield break; - } -} diff --git a/src/Nethermind/Nethermind.Merge.Plugin/Handlers/GetPayloadV4Handler.cs b/src/Nethermind/Nethermind.Merge.Plugin/Handlers/GetPayloadV4Handler.cs index f56e0fef2d5..d403c8c43bb 100644 --- a/src/Nethermind/Nethermind.Merge.Plugin/Handlers/GetPayloadV4Handler.cs +++ b/src/Nethermind/Nethermind.Merge.Plugin/Handlers/GetPayloadV4Handler.cs @@ -24,7 +24,7 @@ public class GetPayloadV4Handler( { protected override GetPayloadV4Result GetPayloadResultFromBlock(IBlockProductionContext context) { - return new(context.CurrentBestBlock!, context.BlockFees, new BlobsBundleV1(context.CurrentBestBlock!)) + return new(context.CurrentBestBlock!, context.BlockFees, new BlobsBundleV1(context.CurrentBestBlock!), context.CurrentBestBlock!.ExecutionRequests!) { ShouldOverrideBuilder = censorshipDetector?.GetCensoredBlocks().Contains(new BlockNumberHash(context.CurrentBestBlock!)) ?? false }; diff --git a/src/Nethermind/Nethermind.Merge.Plugin/Handlers/IGetPayloadBodiesByRangeV2Handler.cs b/src/Nethermind/Nethermind.Merge.Plugin/Handlers/IGetPayloadBodiesByRangeV2Handler.cs deleted file mode 100644 index 9cd35c7d626..00000000000 --- a/src/Nethermind/Nethermind.Merge.Plugin/Handlers/IGetPayloadBodiesByRangeV2Handler.cs +++ /dev/null @@ -1,14 +0,0 @@ -// SPDX-FileCopyrightText: 2022 Demerzel Solutions Limited -// SPDX-License-Identifier: LGPL-3.0-only - -using System.Collections.Generic; -using System.Threading.Tasks; -using Nethermind.JsonRpc; -using Nethermind.Merge.Plugin.Data; - -namespace Nethermind.Merge.Plugin.Handlers; - -public interface IGetPayloadBodiesByRangeV2Handler -{ - Task>> Handle(long start, long count); -} diff --git a/src/Nethermind/Nethermind.Merge.Plugin/IEngineRpcModule.Prague.cs b/src/Nethermind/Nethermind.Merge.Plugin/IEngineRpcModule.Prague.cs index 15f3577ce42..d5b38eac8fe 100644 --- a/src/Nethermind/Nethermind.Merge.Plugin/IEngineRpcModule.Prague.cs +++ b/src/Nethermind/Nethermind.Merge.Plugin/IEngineRpcModule.Prague.cs @@ -5,6 +5,7 @@ using System.Threading.Tasks; using Nethermind.Consensus.Producers; using Nethermind.Core.Crypto; +using Nethermind.Core.ExecutionRequest; using Nethermind.JsonRpc; using Nethermind.JsonRpc.Modules; using Nethermind.Merge.Plugin.Data; @@ -17,23 +18,11 @@ public partial interface IEngineRpcModule : IRpcModule Description = "Verifies the payload according to the execution environment rules and returns the verification status and hash of the last valid block.", IsSharable = true, IsImplemented = true)] - Task> engine_newPayloadV4(ExecutionPayloadV4 executionPayload, byte[]?[] blobVersionedHashes, Hash256? parentBeaconBlockRoot); + Task> engine_newPayloadV4(ExecutionPayloadV3 executionPayload, byte[]?[] blobVersionedHashes, Hash256? parentBeaconBlockRoot, byte[][]? executionRequests); [JsonRpcMethod( Description = "Returns the most recent version of an execution payload and fees with respect to the transaction set contained by the mempool.", IsSharable = true, IsImplemented = true)] public Task> engine_getPayloadV4(byte[] payloadId); - - [JsonRpcMethod( - Description = "Returns an array of execution payload bodies for the list of provided block hashes.", - IsSharable = true, - IsImplemented = true)] - ResultWrapper> engine_getPayloadBodiesByHashV2(IReadOnlyList blockHashes); - - [JsonRpcMethod( - Description = "Returns an array of execution payload bodies for the provided number range", - IsSharable = true, - IsImplemented = true)] - Task>> engine_getPayloadBodiesByRangeV2(long start, long count); } diff --git a/src/Nethermind/Nethermind.Merge.Plugin/InvalidChainTracker/InvalidBlockInterceptor.cs b/src/Nethermind/Nethermind.Merge.Plugin/InvalidChainTracker/InvalidBlockInterceptor.cs index 7c62b158219..aa84112421f 100644 --- a/src/Nethermind/Nethermind.Merge.Plugin/InvalidChainTracker/InvalidBlockInterceptor.cs +++ b/src/Nethermind/Nethermind.Merge.Plugin/InvalidChainTracker/InvalidBlockInterceptor.cs @@ -123,6 +123,5 @@ private static bool ShouldNotTrackInvalidation(Block block) => // Body does not match header, but it does not mean the hash that the header point to is invalid. !BlockValidator.ValidateTxRootMatchesTxs(block, out _) || !BlockValidator.ValidateUnclesHashMatches(block, out _) || - !BlockValidator.ValidateWithdrawalsHashMatches(block, out _) || - !BlockValidator.ValidateRequestsHashMatches(block, out _); + !BlockValidator.ValidateWithdrawalsHashMatches(block, out _); } diff --git a/src/Nethermind/Nethermind.Merge.Plugin/MergePlugin.cs b/src/Nethermind/Nethermind.Merge.Plugin/MergePlugin.cs index 205b643ea26..4af5134e72d 100644 --- a/src/Nethermind/Nethermind.Merge.Plugin/MergePlugin.cs +++ b/src/Nethermind/Nethermind.Merge.Plugin/MergePlugin.cs @@ -367,8 +367,6 @@ IBlockImprovementContextFactory CreateBlockImprovementContextFactory() _api.Config().SimulateBlockProduction), new GetPayloadBodiesByHashV1Handler(_api.BlockTree, _api.LogManager), new GetPayloadBodiesByRangeV1Handler(_api.BlockTree, _api.LogManager), - new GetPayloadBodiesByHashV2Handler(_api.BlockTree, _api.LogManager), - new GetPayloadBodiesByRangeV2Handler(_api.BlockTree, _api.LogManager), new ExchangeTransitionConfigurationV1Handler(_poSSwitcher, _api.LogManager), new ExchangeCapabilitiesHandler(_api.RpcCapabilitiesProvider, _api.LogManager), new GetBlobsHandler(_api.TxPool), diff --git a/src/Nethermind/Nethermind.Merge.Plugin/Synchronization/ChainLevelHelper.cs b/src/Nethermind/Nethermind.Merge.Plugin/Synchronization/ChainLevelHelper.cs index 9a3f7c1ca30..3aed5334f49 100644 --- a/src/Nethermind/Nethermind.Merge.Plugin/Synchronization/ChainLevelHelper.cs +++ b/src/Nethermind/Nethermind.Merge.Plugin/Synchronization/ChainLevelHelper.cs @@ -159,7 +159,7 @@ public bool TrySetNextBlocks(int maxCount, BlockDownloadContext context) { Block? block = _blockTree.FindBlock(hashesToRequest[i], BlockTreeLookupOptions.None); if (block is null) return false; - BlockBody blockBody = new(block.Transactions, block.Uncles, block?.Withdrawals, block?.Requests); + BlockBody blockBody = new(block.Transactions, block.Uncles, block?.Withdrawals); context.SetBody(i + offset, blockBody); } diff --git a/src/Nethermind/Nethermind.Optimism/OptimismPlugin.cs b/src/Nethermind/Nethermind.Optimism/OptimismPlugin.cs index 0afaefd7d78..1228135f2f6 100644 --- a/src/Nethermind/Nethermind.Optimism/OptimismPlugin.cs +++ b/src/Nethermind/Nethermind.Optimism/OptimismPlugin.cs @@ -263,8 +263,6 @@ public async Task InitRpcModules() _api.Config().SimulateBlockProduction), new GetPayloadBodiesByHashV1Handler(_api.BlockTree, _api.LogManager), new GetPayloadBodiesByRangeV1Handler(_api.BlockTree, _api.LogManager), - new GetPayloadBodiesByHashV2Handler(_api.BlockTree, _api.LogManager), - new GetPayloadBodiesByRangeV2Handler(_api.BlockTree, _api.LogManager), new ExchangeTransitionConfigurationV1Handler(_api.PoSSwitcher, _api.LogManager), new ExchangeCapabilitiesHandler(_api.RpcCapabilitiesProvider, _api.LogManager), new GetBlobsHandler(_api.TxPool), diff --git a/src/Nethermind/Nethermind.Serialization.Rlp/BlockBodyDecoder.cs b/src/Nethermind/Nethermind.Serialization.Rlp/BlockBodyDecoder.cs index 6e38f63dc38..04d17149f09 100644 --- a/src/Nethermind/Nethermind.Serialization.Rlp/BlockBodyDecoder.cs +++ b/src/Nethermind/Nethermind.Serialization.Rlp/BlockBodyDecoder.cs @@ -4,7 +4,6 @@ using System.Linq; using System.Runtime.CompilerServices; using Nethermind.Core; -using Nethermind.Core.ConsensusRequests; namespace Nethermind.Serialization.Rlp; @@ -13,7 +12,6 @@ public class BlockBodyDecoder : IRlpValueDecoder private readonly TxDecoder _txDecoder = TxDecoder.Instance; private readonly HeaderDecoder _headerDecoder = new(); private readonly WithdrawalDecoder _withdrawalDecoderDecoder = new(); - private readonly ConsensusRequestDecoder _requestsDecoder = ConsensusRequestDecoder.Instance; private static BlockBodyDecoder? _instance = null; public static BlockBodyDecoder Instance => _instance ??= new BlockBodyDecoder(); @@ -30,19 +28,17 @@ public int GetLength(BlockBody item, RlpBehaviors rlpBehaviors) public int GetBodyLength(BlockBody b) { - (int txs, int uncles, int? withdrawals, int? requests) = GetBodyComponentLength(b); + (int txs, int uncles, int? withdrawals) = GetBodyComponentLength(b); return Rlp.LengthOfSequence(txs) + Rlp.LengthOfSequence(uncles) + - (withdrawals is not null ? Rlp.LengthOfSequence(withdrawals.Value) : 0) + - (requests is not null ? Rlp.LengthOfSequence(requests.Value) : 0); + (withdrawals is not null ? Rlp.LengthOfSequence(withdrawals.Value) : 0); } - public (int Txs, int Uncles, int? Withdrawals, int? Requests) GetBodyComponentLength(BlockBody b) => + public (int Txs, int Uncles, int? Withdrawals) GetBodyComponentLength(BlockBody b) => ( GetTxLength(b.Transactions), GetUnclesLength(b.Uncles), - (b.Withdrawals is not null ? GetWithdrawalsLength(b.Withdrawals) : null), - (b.Requests is not null ? GetRequestsLength(b.Requests) : null) + b.Withdrawals is not null ? GetWithdrawalsLength(b.Withdrawals) : null ); private int GetTxLength(Transaction[] transactions) => transactions.Sum(t => _txDecoder.GetLength(t, RlpBehaviors.None)); @@ -51,8 +47,6 @@ public int GetBodyLength(BlockBody b) private int GetWithdrawalsLength(Withdrawal[] withdrawals) => withdrawals.Sum(t => _withdrawalDecoderDecoder.GetLength(t, RlpBehaviors.None)); - private int GetRequestsLength(ConsensusRequest[] requests) => requests.Sum(t => _requestsDecoder.GetLength(t, RlpBehaviors.None)); - public BlockBody? Decode(ref Rlp.ValueDecoderContext ctx, RlpBehaviors rlpBehaviors = RlpBehaviors.None) { int sequenceLength = ctx.ReadSequenceLength(); @@ -73,18 +67,13 @@ public int GetBodyLength(BlockBody b) Transaction[] transactions = ctx.DecodeArray(_txDecoder); BlockHeader[] uncles = ctx.DecodeArray(_headerDecoder); Withdrawal[]? withdrawals = null; - ConsensusRequest[]? requests = null; - if (ctx.PeekNumberOfItemsRemaining(lastPosition, 1) > 0) - { - withdrawals = ctx.DecodeArray(_withdrawalDecoderDecoder); - } if (ctx.PeekNumberOfItemsRemaining(lastPosition, 1) > 0) { - requests = ctx.DecodeArray(_requestsDecoder); + withdrawals = ctx.DecodeArray(_withdrawalDecoderDecoder); } - return new BlockBody(transactions, uncles, withdrawals, requests); + return new BlockBody(transactions, uncles, withdrawals); } public void Serialize(RlpStream stream, BlockBody body) @@ -110,14 +99,5 @@ public void Serialize(RlpStream stream, BlockBody body) stream.Encode(withdrawal); } } - - if (body.Requests is not null) - { - stream.StartSequence(GetRequestsLength(body.Requests)); - foreach (ConsensusRequest? request in body.Requests) - { - stream.Encode(request); - } - } } } diff --git a/src/Nethermind/Nethermind.Serialization.Rlp/BlockDecoder.cs b/src/Nethermind/Nethermind.Serialization.Rlp/BlockDecoder.cs index 89d1cfd7a83..78ee520652c 100644 --- a/src/Nethermind/Nethermind.Serialization.Rlp/BlockDecoder.cs +++ b/src/Nethermind/Nethermind.Serialization.Rlp/BlockDecoder.cs @@ -5,7 +5,6 @@ using System.Buffers; using System.Collections.Generic; using Nethermind.Core; -using Nethermind.Core.ConsensusRequests; namespace Nethermind.Serialization.Rlp { @@ -34,20 +33,18 @@ public class BlockDecoder : IRlpValueDecoder, IRlpStreamDecoder return decoded; } - private (int Total, int Txs, int Uncles, int? Withdrawals, int? Requests) GetContentLength(Block item, RlpBehaviors rlpBehaviors) + private (int Total, int Txs, int Uncles, int? Withdrawals) GetContentLength(Block item, RlpBehaviors rlpBehaviors) { int headerLength = _headerDecoder.GetLength(item.Header, rlpBehaviors); - (int txs, int uncles, int? withdrawals, int? requests) = _blockBodyDecoder.GetBodyComponentLength(item.Body); + (int txs, int uncles, int? withdrawals) = _blockBodyDecoder.GetBodyComponentLength(item.Body); int contentLength = headerLength + Rlp.LengthOfSequence(txs) + Rlp.LengthOfSequence(uncles) + - (withdrawals is not null ? Rlp.LengthOfSequence(withdrawals.Value) : 0) + - (requests is not null ? Rlp.LengthOfSequence(requests.Value) : 0); - - return (contentLength, txs, uncles, withdrawals, requests); + (withdrawals is not null ? Rlp.LengthOfSequence(withdrawals.Value) : 0); + return (contentLength, txs, uncles, withdrawals); } public int GetLength(Block? item, RlpBehaviors rlpBehaviors) @@ -96,7 +93,7 @@ public void Encode(RlpStream stream, Block? item, RlpBehaviors rlpBehaviors = Rl return; } - (int contentLength, int txsLength, int unclesLength, int? withdrawalsLength, int? requestsLength) = GetContentLength(item, rlpBehaviors); + (int contentLength, int txsLength, int unclesLength, int? withdrawalsLength) = GetContentLength(item, rlpBehaviors); stream.StartSequence(contentLength); stream.Encode(item.Header); stream.StartSequence(txsLength); @@ -120,16 +117,6 @@ public void Encode(RlpStream stream, Block? item, RlpBehaviors rlpBehaviors = Rl stream.Encode(item.Withdrawals[i]); } } - - if (requestsLength.HasValue) - { - stream.StartSequence(requestsLength.Value); - - for (int i = 0; i < item.Requests.Length; i++) - { - stream.Encode(item.Requests[i]); - } - } } public static ReceiptRecoveryBlock? DecodeToReceiptRecoveryBlock(MemoryManager? memoryManager, Memory memory, RlpBehaviors rlpBehaviors) @@ -158,10 +145,6 @@ public void Encode(RlpStream stream, Block? item, RlpBehaviors rlpBehaviors = Rl { decoderContext.SkipItem(); // Skip withdrawals } - if (decoderContext.Position != blockCheck) - { - decoderContext.SkipItem(); // Skip requests - } if ((rlpBehaviors & RlpBehaviors.AllowExtraBytes) != RlpBehaviors.AllowExtraBytes) { decoderContext.Check(blockCheck); diff --git a/src/Nethermind/Nethermind.Serialization.Rlp/ConsensusRequestDecoder.cs b/src/Nethermind/Nethermind.Serialization.Rlp/ConsensusRequestDecoder.cs deleted file mode 100644 index 91ac5675f87..00000000000 --- a/src/Nethermind/Nethermind.Serialization.Rlp/ConsensusRequestDecoder.cs +++ /dev/null @@ -1,130 +0,0 @@ -// SPDX-FileCopyrightText: 2024 Demerzel Solutions Limited -// SPDX-License-Identifier: LGPL-3.0-only - -using System; -using Nethermind.Core.ConsensusRequests; - -namespace Nethermind.Serialization.Rlp; - -public class ConsensusRequestDecoder : IRlpStreamDecoder, IRlpValueDecoder, IRlpObjectDecoder -{ - public static ConsensusRequestDecoder Instance { get; } = new(); - - private readonly DepositDecoder _depositDecoder = DepositDecoder.Instance; - private readonly WithdrawalRequestDecoder _withdrawalRequestDecoder = WithdrawalRequestDecoder.Instance; - private readonly ConsolidationRequestDecoder _consolidationRequestDecoder = ConsolidationRequestDecoder.Instance; - public int GetContentLength(ConsensusRequest item, RlpBehaviors rlpBehaviors) - { - int length = item.Type switch - { - ConsensusRequestsType.ConsolidationRequest => _consolidationRequestDecoder.GetContentLength((ConsolidationRequest)item, rlpBehaviors), - ConsensusRequestsType.WithdrawalRequest => _withdrawalRequestDecoder.GetContentLength((WithdrawalRequest)item, rlpBehaviors), - ConsensusRequestsType.Deposit => _depositDecoder.GetContentLength((Deposit)item, rlpBehaviors), - _ => throw new RlpException($"Unsupported consensus request type {item.Type}") - }; - return length; - } - - public int GetLength(ConsensusRequest item, RlpBehaviors rlpBehaviors) - { - int length = item.Type switch - { - ConsensusRequestsType.ConsolidationRequest => _consolidationRequestDecoder.GetLength((ConsolidationRequest)item, rlpBehaviors), - ConsensusRequestsType.WithdrawalRequest => _withdrawalRequestDecoder.GetLength((WithdrawalRequest)item, rlpBehaviors), - ConsensusRequestsType.Deposit => _depositDecoder.GetLength((Deposit)item, rlpBehaviors), - _ => throw new RlpException($"Unsupported consensus request type {item.Type}") - }; - - if ((rlpBehaviors & RlpBehaviors.SkipTypedWrapping) == RlpBehaviors.SkipTypedWrapping) - { - return Rlp.LengthOf((byte)item.Type) + length; - } - - return Rlp.LengthOfSequence(Rlp.LengthOf((byte)item.Type) + length); - } - - public ConsensusRequest? Decode(RlpStream rlpStream, RlpBehaviors rlpBehaviors = RlpBehaviors.None) - { - if (rlpStream.IsNextItemNull()) - { - rlpStream.ReadByte(); - return null; - } - - if ((rlpBehaviors & RlpBehaviors.SkipTypedWrapping) == RlpBehaviors.None) - { - rlpStream.ReadPrefixAndContentLength(); - } - - ConsensusRequestsType consensusRequestsType = (ConsensusRequestsType)rlpStream.ReadByte(); - - ConsensusRequest result = consensusRequestsType switch - { - ConsensusRequestsType.ConsolidationRequest => _consolidationRequestDecoder.Decode(rlpStream, rlpBehaviors), - ConsensusRequestsType.WithdrawalRequest => _withdrawalRequestDecoder.Decode(rlpStream, rlpBehaviors), - ConsensusRequestsType.Deposit => _depositDecoder.Decode(rlpStream, rlpBehaviors), - - _ => throw new RlpException($"Unsupported consensus request type {consensusRequestsType}") - }; - - return result; - } - - public ConsensusRequest Decode(ref Rlp.ValueDecoderContext decoderContext, RlpBehaviors rlpBehaviors = RlpBehaviors.None) - { - if (decoderContext.IsNextItemNull()) - { - decoderContext.ReadByte(); - return null; - } - - if ((rlpBehaviors & RlpBehaviors.SkipTypedWrapping) == RlpBehaviors.None) - { - decoderContext.ReadPrefixAndContentLength(); - } - - ConsensusRequestsType consensusRequestsType = (ConsensusRequestsType)decoderContext.ReadByte(); - - ConsensusRequest result = consensusRequestsType switch - { - ConsensusRequestsType.ConsolidationRequest => _consolidationRequestDecoder.Decode(ref decoderContext, rlpBehaviors), - ConsensusRequestsType.WithdrawalRequest => _withdrawalRequestDecoder.Decode(ref decoderContext, rlpBehaviors), - ConsensusRequestsType.Deposit => _depositDecoder.Decode(ref decoderContext, rlpBehaviors), - _ => throw new RlpException($"Unsupported consensus request type {consensusRequestsType}") - }; - - return result; - } - - public void Encode(RlpStream stream, ConsensusRequest item, RlpBehaviors rlpBehaviors = RlpBehaviors.None) - { - int contentLength = GetContentLength(item, rlpBehaviors); - int sequenceLength = Rlp.LengthOfSequence(contentLength); - - if ((rlpBehaviors & RlpBehaviors.SkipTypedWrapping) == RlpBehaviors.None) - { - stream.StartByteArray(sequenceLength + 1, false); - } - - stream.WriteByte((byte)item.Type); - switch (item.Type) - { - case ConsensusRequestsType.ConsolidationRequest: - _consolidationRequestDecoder.Encode(stream, (ConsolidationRequest)item, rlpBehaviors); - break; - case ConsensusRequestsType.WithdrawalRequest: - _withdrawalRequestDecoder.Encode(stream, (WithdrawalRequest)item, rlpBehaviors); - break; - case ConsensusRequestsType.Deposit: - _depositDecoder.Encode(stream, (Deposit)item, rlpBehaviors); - break; - } - } - - public Rlp Encode(ConsensusRequest item, RlpBehaviors rlpBehaviors = RlpBehaviors.None) - { - RlpStream rlpStream = new RlpStream(GetLength(item, rlpBehaviors)); - Encode(rlpStream, item, rlpBehaviors); - return new Rlp(rlpStream.Data.ToArray()); - } -} diff --git a/src/Nethermind/Nethermind.Serialization.Rlp/ConsolidationRequestDecoder.cs b/src/Nethermind/Nethermind.Serialization.Rlp/ConsolidationRequestDecoder.cs deleted file mode 100644 index 99b2f3e49e8..00000000000 --- a/src/Nethermind/Nethermind.Serialization.Rlp/ConsolidationRequestDecoder.cs +++ /dev/null @@ -1,58 +0,0 @@ -// SPDX-FileCopyrightText: 2024 Demerzel Solutions Limited -// SPDX-License-Identifier: LGPL-3.0-only - -using System; -using Nethermind.Core; -using Nethermind.Core.ConsensusRequests; - -namespace Nethermind.Serialization.Rlp; - -public class ConsolidationRequestDecoder : IRlpStreamDecoder, IRlpValueDecoder -{ - public static ConsolidationRequestDecoder Instance { get; } = new(); - public int GetLength(ConsolidationRequest item, RlpBehaviors rlpBehaviors) => - Rlp.LengthOfSequence(GetContentLength(item, rlpBehaviors)); - - public int GetContentLength(ConsolidationRequest item, RlpBehaviors rlpBehaviors) => - Rlp.LengthOf(item.SourceAddress) + Rlp.LengthOf(item.SourcePubkey) + - Rlp.LengthOf(item.TargetPubkey); - - public ConsolidationRequest Decode(RlpStream rlpStream, RlpBehaviors rlpBehaviors = RlpBehaviors.None) - { - int _ = rlpStream.ReadSequenceLength(); - Address sourceAddress = rlpStream.DecodeAddress(); - ArgumentNullException.ThrowIfNull(sourceAddress); - byte[] SourcePubkey = rlpStream.DecodeByteArray(); - byte[] TargetPubkey = rlpStream.DecodeByteArray(); - return new ConsolidationRequest() - { - SourceAddress = sourceAddress, - SourcePubkey = SourcePubkey, - TargetPubkey = TargetPubkey - }; - } - - public ConsolidationRequest Decode(ref Rlp.ValueDecoderContext decoderContext, RlpBehaviors rlpBehaviors = RlpBehaviors.None) - { - int _ = decoderContext.ReadSequenceLength(); - Address sourceAddress = decoderContext.DecodeAddress(); - ArgumentNullException.ThrowIfNull(sourceAddress); - byte[] SourcePubkey = decoderContext.DecodeByteArray(); - byte[] TargetPubkey = decoderContext.DecodeByteArray(); - return new ConsolidationRequest() - { - SourceAddress = sourceAddress, - SourcePubkey = SourcePubkey, - TargetPubkey = TargetPubkey - }; - } - - public void Encode(RlpStream stream, ConsolidationRequest item, RlpBehaviors rlpBehaviors = RlpBehaviors.None) - { - int contentLength = GetContentLength(item, rlpBehaviors); - stream.StartSequence(contentLength); - stream.Encode(item.SourceAddress); - stream.Encode(item.SourcePubkey); - stream.Encode(item.TargetPubkey); - } -} diff --git a/src/Nethermind/Nethermind.Serialization.Rlp/DepositDecoder.cs b/src/Nethermind/Nethermind.Serialization.Rlp/DepositDecoder.cs deleted file mode 100644 index 9fdc2a3bd1e..00000000000 --- a/src/Nethermind/Nethermind.Serialization.Rlp/DepositDecoder.cs +++ /dev/null @@ -1,89 +0,0 @@ -// SPDX-FileCopyrightText: 2022 Demerzel Solutions Limited -// SPDX-License-Identifier: LGPL-3.0-only - -using Nethermind.Core.ConsensusRequests; - -namespace Nethermind.Serialization.Rlp; - -public class DepositDecoder : IRlpStreamDecoder, IRlpValueDecoder -{ - public static DepositDecoder Instance { get; } = new(); - - public Deposit? Decode(RlpStream rlpStream, RlpBehaviors rlpBehaviors = RlpBehaviors.None) - { - if (rlpStream.IsNextItemNull()) - { - rlpStream.ReadByte(); - - return null; - } - - rlpStream.ReadSequenceLength(); - - return new() - { - Pubkey = rlpStream.DecodeByteArray(), - WithdrawalCredentials = rlpStream.DecodeByteArray(), - Amount = rlpStream.DecodeULong(), - Signature = rlpStream.DecodeByteArray(), - Index = rlpStream.DecodeULong(), - }; - } - - public Deposit? Decode(ref Rlp.ValueDecoderContext decoderContext, RlpBehaviors rlpBehaviors = RlpBehaviors.None) - { - if (decoderContext.IsNextItemNull()) - { - decoderContext.ReadByte(); - - return null; - } - - decoderContext.ReadSequenceLength(); - - return new() - { - Pubkey = decoderContext.DecodeByteArray(), - WithdrawalCredentials = decoderContext.DecodeByteArray(), - Amount = decoderContext.DecodeULong(), - Signature = decoderContext.DecodeByteArray(), - Index = decoderContext.DecodeULong(), - }; - } - - public void Encode(RlpStream stream, Deposit? item, RlpBehaviors rlpBehaviors = RlpBehaviors.None) - { - if (item is null) - { - stream.EncodeNullObject(); - return; - } - - var contentLength = GetContentLength(item, rlpBehaviors); - - stream.StartSequence(contentLength); - stream.Encode(item.Pubkey); - stream.Encode(item.WithdrawalCredentials); - stream.Encode(item.Amount); - stream.Encode(item.Signature); - stream.Encode(item.Index.Value); - } - - public Rlp Encode(Deposit? item, RlpBehaviors rlpBehaviors = RlpBehaviors.None) - { - var stream = new RlpStream(GetLength(item, rlpBehaviors)); - - Encode(stream, item, rlpBehaviors); - - return new(stream.Data.ToArray()); - } - - public int GetContentLength(Deposit item, RlpBehaviors rlpBehaviors) => - Rlp.LengthOf(item.Pubkey) + - Rlp.LengthOf(item.WithdrawalCredentials) + - Rlp.LengthOf(item.Amount) + - Rlp.LengthOf(item.Signature) + - Rlp.LengthOf(item.Index); - - public int GetLength(Deposit item, RlpBehaviors rlpBehaviors) => Rlp.LengthOfSequence(GetContentLength(item, rlpBehaviors)); -} diff --git a/src/Nethermind/Nethermind.Serialization.Rlp/HeaderDecoder.cs b/src/Nethermind/Nethermind.Serialization.Rlp/HeaderDecoder.cs index 98dce2b0610..e70f2c9c9b6 100644 --- a/src/Nethermind/Nethermind.Serialization.Rlp/HeaderDecoder.cs +++ b/src/Nethermind/Nethermind.Serialization.Rlp/HeaderDecoder.cs @@ -92,7 +92,7 @@ public class HeaderDecoder : IRlpValueDecoder, IRlpStreamDecoder= 5 && decoderContext.Position != headerCheck) { - blockHeader.RequestsRoot = decoderContext.DecodeKeccak(); + blockHeader.RequestsHash = decoderContext.DecodeKeccak(); } } @@ -184,7 +184,7 @@ public class HeaderDecoder : IRlpValueDecoder, IRlpStreamDecoder= 5 && rlpStream.Position != headerCheck) { - blockHeader.RequestsRoot = rlpStream.DecodeKeccak(); + blockHeader.RequestsHash = rlpStream.DecodeKeccak(); } } @@ -256,9 +256,9 @@ public void Encode(RlpStream rlpStream, BlockHeader? header, RlpBehaviors rlpBeh rlpStream.Encode(header.ParentBeaconBlockRoot); } - if (header.RequestsRoot is not null) + if (header.RequestsHash is not null) { - rlpStream.Encode(header.RequestsRoot); + rlpStream.Encode(header.RequestsHash); } } @@ -302,7 +302,7 @@ private static int GetContentLength(BlockHeader? item, RlpBehaviors rlpBehaviors + (item.ParentBeaconBlockRoot is null ? 0 : Rlp.LengthOfKeccakRlp) + (item.BlobGasUsed is null ? 0 : Rlp.LengthOf(item.BlobGasUsed.Value)) + (item.ExcessBlobGas is null ? 0 : Rlp.LengthOf(item.ExcessBlobGas.Value)) - + (item.RequestsRoot is null ? 0 : Rlp.LengthOf(item.RequestsRoot)); + + (item.RequestsHash is null ? 0 : Rlp.LengthOf(item.RequestsHash)); if (notForSealing) { diff --git a/src/Nethermind/Nethermind.Serialization.Rlp/RlpStream.cs b/src/Nethermind/Nethermind.Serialization.Rlp/RlpStream.cs index 5c1919959ef..0c000b7b001 100644 --- a/src/Nethermind/Nethermind.Serialization.Rlp/RlpStream.cs +++ b/src/Nethermind/Nethermind.Serialization.Rlp/RlpStream.cs @@ -16,7 +16,6 @@ using Nethermind.Core.Crypto; using Nethermind.Core.Extensions; using Nethermind.Int256; -using Nethermind.Core.ConsensusRequests; namespace Nethermind.Serialization.Rlp { @@ -27,7 +26,6 @@ public class RlpStream private static readonly BlockInfoDecoder _blockInfoDecoder = new(); private static readonly TxDecoder _txDecoder = TxDecoder.Instance; private static readonly WithdrawalDecoder _withdrawalDecoder = new(); - private static readonly ConsensusRequestDecoder _requestsDecoder = ConsensusRequestDecoder.Instance; private static readonly LogEntryDecoder _logEntryDecoder = LogEntryDecoder.Instance; private readonly CappedArray _data; @@ -89,7 +87,6 @@ public void Encode(Transaction value, RlpBehaviors rlpBehaviors = RlpBehaviors.N } public void Encode(Withdrawal value) => _withdrawalDecoder.Encode(this, value); - public void Encode(ConsensusRequest value) => _requestsDecoder.Encode(this, value); public void Encode(LogEntry value) { diff --git a/src/Nethermind/Nethermind.Serialization.Rlp/WithdrawalRequestDecoder.cs b/src/Nethermind/Nethermind.Serialization.Rlp/WithdrawalRequestDecoder.cs deleted file mode 100644 index 450a842cc9c..00000000000 --- a/src/Nethermind/Nethermind.Serialization.Rlp/WithdrawalRequestDecoder.cs +++ /dev/null @@ -1,67 +0,0 @@ -// SPDX-FileCopyrightText: 2024 Demerzel Solutions Limited -// SPDX-License-Identifier: LGPL-3.0-only - -using System; -using Nethermind.Core; -using Nethermind.Core.ConsensusRequests; - -namespace Nethermind.Serialization.Rlp; - -public class WithdrawalRequestDecoder : IRlpStreamDecoder, IRlpValueDecoder, IRlpObjectDecoder -{ - public static WithdrawalRequestDecoder Instance { get; } = new(); - public int GetLength(WithdrawalRequest item, RlpBehaviors rlpBehaviors) => - Rlp.LengthOfSequence(GetContentLength(item, rlpBehaviors)); - - public int GetContentLength(WithdrawalRequest item, RlpBehaviors rlpBehaviors) => - Rlp.LengthOf(item.SourceAddress) + Rlp.LengthOf(item.ValidatorPubkey) + - Rlp.LengthOf(item.Amount); - - public WithdrawalRequest Decode(RlpStream rlpStream, RlpBehaviors rlpBehaviors = RlpBehaviors.None) - { - _ = rlpStream.ReadSequenceLength(); - Address sourceAddress = rlpStream.DecodeAddress(); - ArgumentNullException.ThrowIfNull(sourceAddress); - byte[] validatorPubkey = rlpStream.DecodeByteArray(); - ulong amount = rlpStream.DecodeULong(); - return new WithdrawalRequest - { - SourceAddress = sourceAddress, - ValidatorPubkey = validatorPubkey, - Amount = amount - }; - } - - public WithdrawalRequest Decode(ref Rlp.ValueDecoderContext decoderContext, RlpBehaviors rlpBehaviors = RlpBehaviors.None) - { - _ = decoderContext.ReadSequenceLength(); - Address sourceAddress = decoderContext.DecodeAddress(); - ArgumentNullException.ThrowIfNull(sourceAddress); - byte[] validatorPubkey = decoderContext.DecodeByteArray(); - ulong amount = decoderContext.DecodeULong(); - return new WithdrawalRequest - { - SourceAddress = sourceAddress, - ValidatorPubkey = validatorPubkey, - Amount = amount - }; - } - - public void Encode(RlpStream stream, WithdrawalRequest item, RlpBehaviors rlpBehaviors = RlpBehaviors.None) - { - int contentLength = GetContentLength(item, rlpBehaviors); - stream.StartSequence(contentLength); - stream.Encode(item.SourceAddress); - stream.Encode(item.ValidatorPubkey!); - stream.Encode(item.Amount); - } - - public Rlp Encode(WithdrawalRequest item, RlpBehaviors rlpBehaviors = RlpBehaviors.None) - { - RlpStream rlpStream = new(GetLength(item, rlpBehaviors)); - - Encode(rlpStream, item, rlpBehaviors); - - return new Rlp(rlpStream.Data.ToArray()); - } -} diff --git a/src/Nethermind/Nethermind.Specs/ChainSpecStyle/ChainSpecLoader.cs b/src/Nethermind/Nethermind.Specs/ChainSpecStyle/ChainSpecLoader.cs index 4df70834b08..1ed55c51e3c 100644 --- a/src/Nethermind/Nethermind.Specs/ChainSpecStyle/ChainSpecLoader.cs +++ b/src/Nethermind/Nethermind.Specs/ChainSpecStyle/ChainSpecLoader.cs @@ -10,8 +10,8 @@ using System.Text.Json; using Nethermind.Config; using Nethermind.Core; -using Nethermind.Core.ConsensusRequests; using Nethermind.Core.Crypto; +using Nethermind.Core.ExecutionRequest; using Nethermind.Int256; using Nethermind.Serialization.Json; using Nethermind.Specs.ChainSpecStyle.Json; @@ -316,7 +316,7 @@ private static void LoadGenesis(ChainSpecJson chainSpecJson, ChainSpec chainSpec var requestsEnabled = depositsEnabled || withdrawalRequestsEnabled || consolidationRequestsEnabled; if (requestsEnabled) - genesisHeader.RequestsRoot = Keccak.EmptyTreeHash; ; + genesisHeader.RequestsHash = ExecutionRequestExtensions.EmptyRequestsHash; bool isEip4844Enabled = chainSpecJson.Params.Eip4844TransitionTimestamp is not null && genesisHeader.Timestamp >= chainSpecJson.Params.Eip4844TransitionTimestamp; if (isEip4844Enabled) @@ -345,8 +345,7 @@ private static void LoadGenesis(ChainSpecJson chainSpecJson, ChainSpec chainSpec genesisHeader, Array.Empty(), Array.Empty(), - Array.Empty(), - requestsEnabled ? Array.Empty() : null); + Array.Empty()); } private static void LoadAllocations(ChainSpecJson chainSpecJson, ChainSpec chainSpec) diff --git a/src/Nethermind/Nethermind.State/Proofs/RequestsTrie.cs b/src/Nethermind/Nethermind.State/Proofs/RequestsTrie.cs deleted file mode 100644 index d69e1d0c8d7..00000000000 --- a/src/Nethermind/Nethermind.State/Proofs/RequestsTrie.cs +++ /dev/null @@ -1,35 +0,0 @@ -// SPDX-FileCopyrightText: 2024 Demerzel Solutions Limited -// SPDX-License-Identifier: LGPL-3.0-only - -using System; -using Nethermind.Core.Buffers; -using Nethermind.Core.ConsensusRequests; -using Nethermind.Core.Crypto; -using Nethermind.Serialization.Rlp; -using Nethermind.State.Trie; -using Nethermind.Trie; - -namespace Nethermind.State.Proofs; - -public class RequestsTrie(ConsensusRequest[]? requests, bool canBuildProof = false, ICappedArrayPool? bufferPool = null) - : PatriciaTrie(requests, canBuildProof, bufferPool) -{ - private static readonly ConsensusRequestDecoder _codec = ConsensusRequestDecoder.Instance; - - protected override void Initialize(ConsensusRequest[] requests) - { - var key = 0; - - foreach (ConsensusRequest req in requests) - { - Set(Rlp.Encode(key++).Bytes, _codec.Encode(req, RlpBehaviors.SkipTypedWrapping).Bytes); - } - } - - public static Hash256 CalculateRoot(ConsensusRequest[] requests) - { - using TrackingCappedArrayPool cappedArray = new(requests.Length * 4); - Hash256 rootHash = new RequestsTrie(requests, canBuildProof: false, bufferPool: cappedArray).RootHash; - return rootHash; - } -} diff --git a/src/Nethermind/Nethermind.Taiko.Test/TxPoolContentListsTests.cs b/src/Nethermind/Nethermind.Taiko.Test/TxPoolContentListsTests.cs index 7ba68003dc4..e20084942a4 100644 --- a/src/Nethermind/Nethermind.Taiko.Test/TxPoolContentListsTests.cs +++ b/src/Nethermind/Nethermind.Taiko.Test/TxPoolContentListsTests.cs @@ -75,8 +75,6 @@ public int[][] Test_TxLists_AreConstructed( Substitute.For(), Substitute.For, IEnumerable>>(), Substitute.For(), - Substitute.For, IEnumerable>>(), - Substitute.For(), Substitute.For>(), Substitute.For, IEnumerable>>(), Substitute.For>>(), diff --git a/src/Nethermind/Nethermind.Taiko/Rpc/TaikoEngineRpcModule.cs b/src/Nethermind/Nethermind.Taiko/Rpc/TaikoEngineRpcModule.cs index 32a3e1e8d46..cfd45fa0501 100644 --- a/src/Nethermind/Nethermind.Taiko/Rpc/TaikoEngineRpcModule.cs +++ b/src/Nethermind/Nethermind.Taiko/Rpc/TaikoEngineRpcModule.cs @@ -40,8 +40,6 @@ public class TaikoEngineRpcModule(IAsyncHandler getPa IForkchoiceUpdatedHandler forkchoiceUpdatedV1Handler, IHandler, IEnumerable> executionGetPayloadBodiesByHashV1Handler, IGetPayloadBodiesByRangeV1Handler executionGetPayloadBodiesByRangeV1Handler, - IHandler, IEnumerable> executionGetPayloadBodiesByHashV2Handler, - IGetPayloadBodiesByRangeV2Handler executionGetPayloadBodiesByRangeV2Handler, IHandler transitionConfigurationHandler, IHandler, IEnumerable> capabilitiesHandler, IAsyncHandler> getBlobsHandler, @@ -60,8 +58,6 @@ public class TaikoEngineRpcModule(IAsyncHandler getPa forkchoiceUpdatedV1Handler, executionGetPayloadBodiesByHashV1Handler, executionGetPayloadBodiesByRangeV1Handler, - executionGetPayloadBodiesByHashV2Handler, - executionGetPayloadBodiesByRangeV2Handler, transitionConfigurationHandler, capabilitiesHandler, getBlobsHandler, diff --git a/src/Nethermind/Nethermind.Taiko/TaikoPlugin.cs b/src/Nethermind/Nethermind.Taiko/TaikoPlugin.cs index 1305e7ec83f..ede4fdbc880 100644 --- a/src/Nethermind/Nethermind.Taiko/TaikoPlugin.cs +++ b/src/Nethermind/Nethermind.Taiko/TaikoPlugin.cs @@ -227,8 +227,6 @@ public async Task InitRpcModules() _api.Config().SimulateBlockProduction), new GetPayloadBodiesByHashV1Handler(_api.BlockTree, _api.LogManager), new GetPayloadBodiesByRangeV1Handler(_api.BlockTree, _api.LogManager), - new GetPayloadBodiesByHashV2Handler(_api.BlockTree, _api.LogManager), - new GetPayloadBodiesByRangeV2Handler(_api.BlockTree, _api.LogManager), new ExchangeTransitionConfigurationV1Handler(_api.PoSSwitcher, _api.LogManager), new ExchangeCapabilitiesHandler(_api.RpcCapabilitiesProvider, _api.LogManager), new GetBlobsHandler(_api.TxPool),