From d2c45698b8be605cca5775bc1517ff3cf4af4c19 Mon Sep 17 00:00:00 2001 From: Daniil Ankushin <71745946+AnkushinDaniil@users.noreply.github.com> Date: Sat, 28 Nov 2026 16:42:19 +0100 Subject: [PATCH 1/4] EIP-8369 Profile 2 on current master, with a claim replay payer fix Co-authored-by: Marc Harvey-Hill <10379486+Marchhill@users.noreply.github.com> Co-authored-by: Stavros Vlachakis <89769224+svlachakis@users.noreply.github.com> Co-authored-by: Manuel Arto <43347768+manusw7@users.noreply.github.com> Co-authored-by: Alexey Osipov Co-authored-by: Ruben Buniatyan --- .github/workflows/run-nethtest.yml | 11 +- .../EngineInclusionListExpectationTests.cs | 44 +- .../EngineNewPayloadParamsTests.cs | 23 + .../Ethereum.Test.Base/BlockchainTestBase.cs | 80 +- .../Ethereum.Test.Base/JsonToEthereumTest.cs | 6 +- .../AuraBlockProcessorTests.cs | 5 +- .../Engine/EngineTests.cs | 2 - .../ExternalClInterceptingEngineRpcModule.cs | 13 +- .../Core/Eip8369VerifyBudgetFillBenchmarks.cs | 128 ++ .../BlockProcessorTests.cs | 6 +- .../BlockchainProcessorTests.cs | 32 - .../Profile2EligibilityReplayerTests.cs | 324 ++++ .../Nethermind.Blockchain.Test/ReorgTests.cs | 5 +- .../TransactionsExecutorTests.cs | 67 + .../Validators/InclusionListValidatorTests.cs | 610 +++++++- .../Nethermind.Config/BlocksConfig.cs | 2 + .../Nethermind.Config/IBlocksConfig.cs | 7 + .../BlockCachePreWarmerTests.cs | 14 - ...onListBlockProducerTxSourceFactoryTests.cs | 4 +- .../InclusionListTxSourceTests.cs | 129 +- .../MempoolStatePrewarmerTests.cs | 4 +- .../PayloadAttributesPayloadIdTests.cs | 67 +- .../PayloadAttributesValidateTests.cs | 9 +- .../Processing/BranchProcessorVerdictTests.cs | 166 +- .../FinalizedBlockAccessListTests.cs | 96 -- .../RecoverSignaturesTest.cs | 10 +- .../Decoders/InclusionListDecoder.cs | 33 + .../Processing/BlockCachePreWarmer.cs | 23 +- .../Processing/BlockHashEventArgs.cs | 7 +- ...cessor.BlockProductionTransactionPicker.cs | 4 +- ...sor.BlockProductionTransactionsExecutor.cs | 21 +- ...or.IBlockProductionTransactionsExecutor.cs | 19 +- .../Processing/BlockchainProcessor.cs | 18 +- .../Processing/BranchProcessor.cs | 66 +- .../Processing/IBlockProcessingQueue.cs | 5 +- .../IInclusionListSatisfactionChecker.cs | 15 - .../IProfile2EligibilityReplayer.cs | 28 + .../InclusionListSatisfactionChecker.cs | 22 - .../Processing/MempoolStatePrewarmer.cs | 2 +- .../Processing/Profile2EligibilityReplayer.cs | 236 +++ .../Processing/RecoverSignatures.cs | 9 - .../Producers/BlockToProduce.cs | 6 + .../Producers/PayloadAttributes.cs | 73 +- .../Transactions/IInclusionListTxSource.cs | 16 +- .../Transactions/InclusionListTxSource.cs | 92 +- .../Validators/InclusionListValidator.cs | 199 ++- .../Builders/BlockBuilder.cs | 6 - .../Eip8369Profile2Tests.cs | 153 ++ src/Nethermind/Nethermind.Core/Block.cs | 13 +- .../Nethermind.Core/Eip7805Constants.cs | 13 +- .../Nethermind.Core/Eip8369Constants.cs | 37 + .../Nethermind.Core/Eip8369Profile2.cs | 150 ++ .../Nethermind.Core/EngineApiVersions.cs | 3 +- .../Nethermind.Core/FrameTxValidation.cs | 6 +- .../Nethermind.Core/InclusionLists.cs | 78 + .../CanonicalQuantityConverter.cs | 31 + .../Nethermind.Core/OmissionClaim.cs | 19 + .../FrameTxValidationPrefixSimulationTests.cs | 102 ++ .../Tracing/FrameTxValidationTracer.cs | 114 +- .../TransactionProcessing/ExecutionOptions.cs | 4 + .../TransactionProcessorBase.FrameTx.cs | 40 +- .../Modules/BlockProcessingModule.cs | 6 +- .../Data/CanonicalQuantityConverterTests.cs | 48 + .../EngineModuleTests.Eip8369.cs | 430 ++++++ .../EngineModuleTests.V1.cs | 15 +- .../EngineModuleTests.V3.cs | 6 +- .../EngineModuleTests.V4.cs | 2 +- .../EngineModuleTests.V7.cs | 1351 +++++------------ ...etInclusionListTransactionsHandlerTests.cs | 3 +- .../InclusionChecksTests.cs | 61 + .../InclusionListBuilderTests.cs | 97 +- .../NewPayloadHandlerRaceConditionTests.cs | 608 -------- .../SszRest/SszCodecTests.cs | 30 +- .../SszRest/SszMiddlewareTests.cs | 137 +- .../BlockProduction/PostMergeBlockProducer.cs | 1 + .../Data/ExecutionPayload.cs | 7 - .../Data/ExecutionPayloadV3.cs | 4 - .../Data/ForkchoiceUpdatedV2Result.cs | 32 - .../Data/GetPayloadDirectResponseWriter.cs | 35 +- .../Data/GetPayloadV7Result.cs | 27 + .../Data/IExecutionPayloadParams.cs | 42 +- .../Data/NewPayloadV1Result.cs | 2 - .../Data/PayloadStatus.cs | 3 - .../Data/PayloadStatusV2.cs | 6 +- .../EngineRpcModule.Bogota.cs | 322 +--- .../EngineRpcModule.Paris.cs | 1 - .../EngineRpcModule.cs | 27 +- .../Handlers/EngineRpcCapabilitiesProvider.cs | 1 + .../GetInclusionListTransactionsHandler.cs | 7 +- .../Handlers/GetPayloadV6Handler.cs | 2 +- .../Handlers/GetPayloadV7Handler.cs | 24 + .../IInclusionListComplianceEvaluator.cs | 24 +- .../Handlers/InclusionChecks.cs | 61 + .../Handlers/InclusionListBuilder.cs | 100 +- .../Handlers/NewPayloadHandler.cs | 370 ++--- .../Handlers/NewPayloadWithWitnessHandler.cs | 6 +- .../IEngineRpcModule.Bogota.cs | 15 +- .../Nethermind.Merge.Plugin/MergePlugin.cs | 2 + .../Handlers/ForkchoiceUpdatedV5SszHandler.cs | 56 - .../Handlers/NewPayloadV6SszHandler.cs | 3 +- .../SszRest/Handlers/SszRestPaths.cs | 2 +- .../SszRest/Handlers/SszVersionDescriptors.cs | 26 +- .../SszRest/SszCodec.cs | 20 +- .../SszRest/SszMiddlewareConfigurer.cs | 3 +- .../SszRest/SszWireTypes.cs | 47 +- .../SszRest/WireConversionExtensions.cs | 24 + .../FinalizedBlockAccessListProcessor.cs | 5 +- .../Ethereum/StartupPipelineWarmer.cs | 10 +- .../ChainSpecStyle/GethGenesisLoaderTests.cs | 3 +- .../ChainSpecStyle/GethGenesisParityTests.cs | 1 + .../Nethermind.Specs.Test/ForkTests.cs | 15 + .../Nethermind.Specs/Forks/26_Bogota.cs | 1 + .../Forks/Eip8369Prototype.cs | 20 + .../Nethermind.Specs/SpecNameParser.cs | 1 + .../CertainBatchLookupTests.cs | 4 +- .../TxPoolContentListsTests.cs | 4 +- .../Rpc/TaikoEngineRpcModule.cs | 18 +- 117 files changed, 4574 insertions(+), 3131 deletions(-) create mode 100644 src/Nethermind/Ethereum.Basic.Test/EngineNewPayloadParamsTests.cs create mode 100644 src/Nethermind/Nethermind.Benchmark/Core/Eip8369VerifyBudgetFillBenchmarks.cs create mode 100644 src/Nethermind/Nethermind.Blockchain.Test/Profile2EligibilityReplayerTests.cs delete mode 100644 src/Nethermind/Nethermind.Consensus/Processing/IInclusionListSatisfactionChecker.cs create mode 100644 src/Nethermind/Nethermind.Consensus/Processing/IProfile2EligibilityReplayer.cs delete mode 100644 src/Nethermind/Nethermind.Consensus/Processing/InclusionListSatisfactionChecker.cs create mode 100644 src/Nethermind/Nethermind.Consensus/Processing/Profile2EligibilityReplayer.cs create mode 100644 src/Nethermind/Nethermind.Core.Test/Eip8369Profile2Tests.cs create mode 100644 src/Nethermind/Nethermind.Core/Eip8369Constants.cs create mode 100644 src/Nethermind/Nethermind.Core/Eip8369Profile2.cs create mode 100644 src/Nethermind/Nethermind.Core/InclusionLists.cs create mode 100644 src/Nethermind/Nethermind.Core/JsonConverters/CanonicalQuantityConverter.cs create mode 100644 src/Nethermind/Nethermind.Core/OmissionClaim.cs create mode 100644 src/Nethermind/Nethermind.Merge.Plugin.Test/Data/CanonicalQuantityConverterTests.cs create mode 100644 src/Nethermind/Nethermind.Merge.Plugin.Test/EngineModuleTests.Eip8369.cs create mode 100644 src/Nethermind/Nethermind.Merge.Plugin.Test/InclusionChecksTests.cs delete mode 100644 src/Nethermind/Nethermind.Merge.Plugin/Data/ForkchoiceUpdatedV2Result.cs create mode 100644 src/Nethermind/Nethermind.Merge.Plugin/Data/GetPayloadV7Result.cs create mode 100644 src/Nethermind/Nethermind.Merge.Plugin/Handlers/GetPayloadV7Handler.cs create mode 100644 src/Nethermind/Nethermind.Merge.Plugin/Handlers/InclusionChecks.cs delete mode 100644 src/Nethermind/Nethermind.Merge.Plugin/SszRest/Handlers/ForkchoiceUpdatedV5SszHandler.cs create mode 100644 src/Nethermind/Nethermind.Specs/Forks/Eip8369Prototype.cs diff --git a/.github/workflows/run-nethtest.yml b/.github/workflows/run-nethtest.yml index 80f1faf44784..1dc2d36ba0c1 100644 --- a/.github/workflows/run-nethtest.yml +++ b/.github/workflows/run-nethtest.yml @@ -623,16 +623,19 @@ jobs: # lane carried for ethereum/execution-specs#3582, #3406, the EIP-7610 collision scenario # and the EIP-7928 boundary at test_tx_gas_limit are no longer needed. # - # What remains is the aggregate inclusion-list size cap, which is ours rather than the - # spec's: these cases carry an ~131 KB initcode or calldata payload, 16x the per-list - # MAX_BYTES_PER_INCLUSION_LIST of EIP-7805, so engine_newPayloadV6 answers -32602 before - # validating and the fixture cannot demonstrate the rejection it expects. + # What remains is the inclusion-list size cap: these cases carry a single transaction over + # the per-list MAX_BYTES_PER_INCLUSION_LIST of EIP-7805, which fits no committee position, + # so engine_newPayloadV6 answers -32602 before validating and the fixture cannot + # demonstrate the rejection it expects. 'test_contract_creating_tx.*inclusion_list' 'test_tx_gas_limit_cap_contract_creation.*inclusion_list' 'test_oversized_initcode_tx_no_state_gas.*inclusion_list' 'test_max_initcode_size.*inclusion_list' 'test_calldata_floor_exceeding_tx_gas_limit_cap.*inclusion_list' 'test_tx_gas_limit_cap_authorized_tx.*inclusion_list' + 'test_transaction_validity_type_.*inclusion_list.*multiple_access_lists_multiple_storage_keys' + 'TestCreateTxGasBoundary::test_create_tx_gas_boundary.*inclusion_list' + 'test_intrinsic_execution_gas_exceeds_cap.*inclusion_list' # The inclusion-list variant keeps rlp_modifier while clearing header_verify, so header # blob-gas fields are never recomputed. Fix pending as ethereum/execution-specs#3406. 'test_invalid_block_blob_count.*inclusion_list' diff --git a/src/Nethermind/Ethereum.Basic.Test/EngineInclusionListExpectationTests.cs b/src/Nethermind/Ethereum.Basic.Test/EngineInclusionListExpectationTests.cs index 80aee8fdb54c..15ec9e957322 100644 --- a/src/Nethermind/Ethereum.Basic.Test/EngineInclusionListExpectationTests.cs +++ b/src/Nethermind/Ethereum.Basic.Test/EngineInclusionListExpectationTests.cs @@ -4,48 +4,24 @@ #nullable enable annotations using Ethereum.Test.Base; -using Nethermind.JsonRpc; -using Nethermind.Merge.Plugin.Data; using Nethermind.Serialization.Json; using NUnit.Framework; namespace Ethereum.Basic.Test; -// EIP-7805 compliance is reported twice: by engine_newPayloadV6 and again by the fork-choice update to -// that head, and a fixture's inclusionListSatisfied is the expectation for both. +// EIP-7805 inclusion is checked apart from execution: engine_newPayloadV6 returns the check's identifier, and a +// fixture's inclusionListSatisfied is the expectation for the verdict that check completes with. [TestFixture] public class EngineInclusionListExpectationTests { private static readonly IJsonSerializer _serializer = new EthereumJsonSerializer(); - [TestCase("{}", true, ExpectedResult = null, TestName = "Silent fixture accepts any answer")] - [TestCase("""{"inclusionListSatisfied": true}""", true, ExpectedResult = null, TestName = "Reported value matches")] - [TestCase("""{"inclusionListSatisfied": true}""", false, ExpectedResult = "engine_forkchoiceUpdatedV5 returned VALID and reported inclusionListSatisfied=False, expected True", TestName = "Reported value contradicts")] - [TestCase("""{"inclusionListSatisfied": true}""", null, ExpectedResult = "engine_forkchoiceUpdatedV5 returned VALID and reported inclusionListSatisfied=null, expected True", TestName = "Field absent where one was expected")] - [TestCase("""{"inclusionListSatisfied": false}""", true, ExpectedResult = "engine_forkchoiceUpdatedV5 returned VALID and reported inclusionListSatisfied=True, expected False", TestName = "Unsatisfied expectation contradicts")] - public string? Forkchoice_response_is_checked_against_the_fixture(string json, bool? reported) => - BlockchainTestBase.DescribeFcuInclusionListMismatch(ForkchoiceResponse(reported), _serializer.Deserialize(json), fcuVersion: 5); - - // A head that never became VALID reports no compliance either, so the message must not read as an - // EIP-7805 contradiction. - [Test] - public void Non_valid_head_is_named_rather_than_blamed_on_the_inclusion_list() => - Assert.That(BlockchainTestBase.DescribeFcuInclusionListMismatch( - ForkchoiceResponse(null, PayloadStatus.Syncing), - _serializer.Deserialize("""{"inclusionListSatisfied": true}"""), fcuVersion: 5), - Is.EqualTo("engine_forkchoiceUpdatedV5 returned SYNCING and reported inclusionListSatisfied=null, expected True")); - - // A version that cannot carry the field must fail rather than read as an absent one. - [Test] - public void Fork_choice_version_that_cannot_report_compliance_is_a_mismatch() => - Assert.That(BlockchainTestBase.DescribeFcuInclusionListMismatch( - ResultWrapper.Success(new ForkchoiceUpdatedV1Result()), - _serializer.Deserialize("""{"inclusionListSatisfied": true}"""), fcuVersion: 4), - Does.StartWith("engine_forkchoiceUpdatedV4 answered with ForkchoiceUpdatedV1Result, which cannot report inclusionListSatisfied")); - - private static ResultWrapper ForkchoiceResponse(bool? inclusionListSatisfied, string status = PayloadStatus.Valid) => - ResultWrapper.Success(new ForkchoiceUpdatedV2Result - { - PayloadStatus = new PayloadStatusV2 { Status = status, InclusionListSatisfied = inclusionListSatisfied } - }); + [TestCase("{}", true, ExpectedResult = null, TestName = "Silent fixture accepts any verdict")] + [TestCase("{}", null, ExpectedResult = null, TestName = "Silent fixture accepts a missing verdict")] + [TestCase("""{"inclusionListSatisfied": true}""", true, ExpectedResult = null, TestName = "Verdict matches")] + [TestCase("""{"inclusionListSatisfied": true}""", false, ExpectedResult = "engine_newPayloadV6 inclusion check reported inclusionListSatisfied=False, expected True", TestName = "Verdict contradicts")] + [TestCase("""{"inclusionListSatisfied": false}""", true, ExpectedResult = "engine_newPayloadV6 inclusion check reported inclusionListSatisfied=True, expected False", TestName = "Unsatisfied expectation contradicts")] + [TestCase("""{"inclusionListSatisfied": false}""", null, ExpectedResult = "engine_newPayloadV6 inclusion check reported inclusionListSatisfied=null, expected False", TestName = "Missing verdict is never taken as either verdict")] + public string? Inclusion_verdict_is_checked_against_the_fixture(string json, bool? verdict) => + BlockchainTestBase.DescribeInclusionVerdictMismatch(_serializer.Deserialize(json), verdict, payloadVersion: 6); } diff --git a/src/Nethermind/Ethereum.Basic.Test/EngineNewPayloadParamsTests.cs b/src/Nethermind/Ethereum.Basic.Test/EngineNewPayloadParamsTests.cs new file mode 100644 index 000000000000..23c5dbd1c26b --- /dev/null +++ b/src/Nethermind/Ethereum.Basic.Test/EngineNewPayloadParamsTests.cs @@ -0,0 +1,23 @@ +// SPDX-FileCopyrightText: 2026 Demerzel Solutions Limited +// SPDX-License-Identifier: LGPL-3.0-only + +using System.Text.Json; +using Ethereum.Test.Base; +using NUnit.Framework; + +namespace Ethereum.Basic.Test; + +[TestFixture] +public class EngineNewPayloadParamsTests +{ + [TestCase("""["0xpayload",["0xh"],"0xroot",["0xreq"],["0x00","0x01","0x02","0x03","0x04","0x05","0x06","0x07","0x08","0x09","0x0a","0x0b","0x0c","0x0d","0x0e","0x0f","0x10"]]""", 5, 4, ExpectedResult = """["0xpayload",["0xh"],"0xroot",["0xreq"]]""", TestName = "Version below 6 passes through")] + [TestCase("""["0xpayload",["0xh"],"0xroot",["0xreq"],[["0x00","0x10"],["0x01"],["0x02"],["0x03"],["0x04"],["0x05"],["0x06"],["0x07"],["0x08"],["0x09"],["0x0a"],["0x0b"],["0x0c"],["0x0d"],["0x0e"],["0x0f"]],[]]""", 6, 6, ExpectedResult = """["0xpayload",["0xh"],"0xroot",["0xreq"],[["0x00","0x10"],["0x01"],["0x02"],["0x03"],["0x04"],["0x05"],["0x06"],["0x07"],["0x08"],["0x09"],["0x0a"],["0x0b"],["0x0c"],["0x0d"],["0x0e"],["0x0f"]],[]]""", TestName = "Nested inclusion lists pass through")] + [TestCase("""["0xpayload",["0xh"],"0xroot",["0xreq"],["0x00","0x01","0x02","0x03","0x04","0x05","0x06","0x07","0x08","0x09","0x0a","0x0b","0x0c","0x0d","0x0e","0x0f","0x10"]]""", 6, 6, ExpectedResult = """["0xpayload",["0xh"],"0xroot",["0xreq"],[["0x00","0x10"],["0x01"],["0x02"],["0x03"],["0x04"],["0x05"],["0x06"],["0x07"],["0x08"],["0x09"],["0x0a"],["0x0b"],["0x0c"],["0x0d"],["0x0e"],["0x0f"]],[]]""", TestName = "Flat list goes round-robin into 16 positions")] + [TestCase("""["0xpayload",["0xh"],"0xroot",["0xreq"],[]]""", 6, 6, ExpectedResult = """["0xpayload",["0xh"],"0xroot",["0xreq"],[[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[]],[]]""", TestName = "Empty flat list gives 16 empty positions")] + public string Flat_fixture_inclusion_list_is_split_across_committee_positions(string parameters, int payloadVersion, int paramCount) + { + using JsonDocument document = JsonDocument.Parse(parameters); + JsonElement[] elements = [.. document.RootElement.EnumerateArray()]; + return "[" + string.Join(",", BlockchainTestBase.NewPayloadParams(elements, paramCount, payloadVersion)) + "]"; + } +} diff --git a/src/Nethermind/Ethereum.Test.Base/BlockchainTestBase.cs b/src/Nethermind/Ethereum.Test.Base/BlockchainTestBase.cs index 5a038ebd8400..0305a18b3f9e 100644 --- a/src/Nethermind/Ethereum.Test.Base/BlockchainTestBase.cs +++ b/src/Nethermind/Ethereum.Test.Base/BlockchainTestBase.cs @@ -245,10 +245,10 @@ protected async Task RunTest( blockchainProcessor.BlockRemoved += (_, args) => { if (args.ProcessingResult != ProcessingResult.Success) + { asyncBlockError = args.Message ?? args.Exception?.Message; - // An unsatisfied inclusion list still commits the block, so it is no rejection. - if (args.ProcessingResult is not (ProcessingResult.Success or ProcessingResult.InclusionListUnsatisfied)) rejectionRecorder.Record(args.BlockHash, args.Message ?? args.Exception?.Message ?? args.ProcessingResult.ToString()); + } }; Result suggestResult = SuggestBlocks(test, failOnInvalidRlp, blockValidator, blockTree, parentHeader, blockDecoder, WithholdBlockAccessLists, undeliveredAccessLists, rejectionRecorder); parentHeader = suggestResult.Data!; @@ -747,7 +747,7 @@ private static async Task> RunNewPayloads(TestEngineNewPayloadsJs && validationError is null; int paramCount = NewPayloadParamCounts[newPayloadVersion]; - IEnumerable paramsRaw = enginePayload.Params.Take(paramCount).Select(static p => p.GetRawText()); + IEnumerable paramsRaw = NewPayloadParams(enginePayload.Params, paramCount, newPayloadVersion); string paramsJson = "[" + string.Join(",", paramsRaw) + "]"; string npMethod = expectWitness ? "engine_newPayloadWithWitnessV" + newPayloadVersion : "engine_newPayloadV" + newPayloadVersion; @@ -765,9 +765,8 @@ private static async Task> RunNewPayloads(TestEngineNewPayloadsJs if (expectWitness) { - // The witness result has no PayloadStatusV2, and engine_newPayloadWithWitnessV6 retains no - // compliance for the fork-choice update either, so the expectation cannot be checked here - // and must not be silently dropped. + // The witness result has no PayloadStatusV2, so it cannot carry the inclusion check's identifier, + // and the expectation must not be silently dropped. Assert.That(enginePayload.InclusionListSatisfied, Is.Null, $"engine_newPayloadWithWitnessV{newPayloadVersion} cannot report inclusionListSatisfied, which this fixture states"); @@ -799,17 +798,20 @@ private static async Task> RunNewPayloads(TestEngineNewPayloadsJs PayloadStatusV1 payloadStatus = GetPayloadStatus(npResponse, newPayloadVersion); UseFirstRejection(payloadStatus, enginePayload, firstRejections); RecordInvalidPayload(rejectionRecorder, payloadIndex, enginePayload, payloadStatus); - AssertPayloadStatus(payloadStatus, validationError, newPayloadVersion, matchExpectedExceptions, enginePayload.InclusionListSatisfied); + AssertPayloadStatus(payloadStatus, validationError, newPayloadVersion, matchExpectedExceptions); + if (payloadStatus is PayloadStatusV2 { Status: PayloadStatus.Valid } statusV2) + { + Assert.That(DescribeInclusionVerdictMismatch(enginePayload, statusV2.InclusionListSatisfied, newPayloadVersion), Is.Null); + } lastStatus = payloadStatus.Status; if (payloadStatus.ValidationError is not null) lastValidationError = payloadStatus.ValidationError; // The block is committed even when unsatisfied, so the head must still advance. - if (payloadStatus.Status is PayloadStatus.Valid or PayloadStatus.InclusionListUnsatisfied) + if (payloadStatus.Status == PayloadStatus.Valid) { Hash256 blockHash = new(enginePayload.Params[0].GetProperty("blockHash").GetString()!); - JsonRpcResponse fcuResponse = await MoveHeadToCommitted(rpcService, rpcContext, processingQueue, fcuVersion, blockHash, finalizeHeads); - AssertFcuInclusionListSatisfied(fcuResponse, enginePayload, fcuVersion); + await MoveHeadToCommitted(rpcService, rpcContext, processingQueue, fcuVersion, blockHash, finalizeHeads); } } } @@ -819,6 +821,21 @@ private static async Task> RunNewPayloads(TestEngineNewPayloadsJs : Result.Fail(lastValidationError, lastStatus); } + internal static IEnumerable NewPayloadParams(JsonElement[] parameters, int paramCount, int payloadVersion) + { + if (payloadVersion < 6 || parameters.Length < 5 || parameters[4].ValueKind != JsonValueKind.Array + || parameters[4].EnumerateArray().Any(static t => t.ValueKind != JsonValueKind.String)) + return parameters.Take(paramCount).Select(static p => p.GetRawText()); + + List[] lists = [.. Enumerable.Range(0, Eip7805Constants.InclusionListCommitteeSize).Select(static _ => new List())]; + int position = 0; + foreach (JsonElement transaction in parameters[4].EnumerateArray()) + lists[position++ % lists.Length].Add(transaction.GetRawText()); + + string inclusionLists = "[" + string.Join(",", lists.Select(static l => "[" + string.Join(",", l) + "]")) + "]"; + return [.. parameters.Take(4).Select(static p => p.GetRawText()), inclusionLists, "[]"]; + } + /// /// Gives an INVALID payload whose block the client rejected before the validation error of that first rejection. /// @@ -899,7 +916,7 @@ private static bool TryGetRpcError(JsonRpcResponse response, out int errorCode, private static PayloadStatusV1 GetPayloadStatus(JsonRpcResponse response, int payloadVersion) => response switch { - // newPayloadV6 returns PayloadStatusV2 (derives from V1), preserving inclusionListSatisfied. + // newPayloadV6 returns PayloadStatusV2 (derives from V1), preserving the inclusion check's identifier. ResultWrapper { Result.ResultType: ResultType.Success } v2Wrapper => v2Wrapper.Data, ResultWrapper { Result.ResultType: ResultType.Success } resultWrapper => resultWrapper.Data, JsonRpcSuccessResponse { Result: PayloadStatusV1 payloadStatus } => payloadStatus, @@ -943,48 +960,24 @@ private static void AssertExpectedRpcError(int errorCode, string? errorMessage, private static void AssertPayloadWasNotExpectedToError(int? expectedErrorCode, string? validationError, int payloadVersion) => Assert.That(DescribeMissingRpcError(expectedErrorCode, validationError, payloadVersion), Is.Null); - private static void AssertPayloadStatus(PayloadStatusV1 payloadStatus, string? expectedValidationError, int payloadVersion, bool matchExpectedException, bool? expectedInclusionListSatisfied = null) + private static void AssertPayloadStatus(PayloadStatusV1 payloadStatus, string? expectedValidationError, int payloadVersion, bool matchExpectedException) { string expectedStatus = expectedValidationError is null ? PayloadStatus.Valid : PayloadStatus.Invalid; Assert.That(payloadStatus.Status, Is.EqualTo(expectedStatus), $"engine_newPayloadV{payloadVersion} returned {payloadStatus.Status}, expected {expectedStatus}. ValidationError: {payloadStatus.ValidationError}"); - // EIP-7805: IL compliance is only reported for a VALID payload (execution-apis#609). - if (expectedInclusionListSatisfied is { } expectedIlSatisfied && payloadStatus.Status == PayloadStatus.Valid) - Assert.That((payloadStatus as PayloadStatusV2)?.InclusionListSatisfied, Is.EqualTo(expectedIlSatisfied), - $"engine_newPayloadV{payloadVersion} reported inclusionListSatisfied={(payloadStatus as PayloadStatusV2)?.InclusionListSatisfied}, expected {expectedIlSatisfied}"); - if (expectedValidationError is not null && matchExpectedException) AssertValidationError(payloadStatus.ValidationError, expectedValidationError, payloadVersion); } /// - /// Describes why the inclusion-list compliance reported by the fork-choice update that follows a payload - /// contradicts the fixture (EIP-7805), or null when it matches or the fixture states no expectation. + /// Describes why the inclusion verdict for a VALID payload contradicts the fixture (EIP-7805), or null when + /// it matches or the fixture states no expectation. /// - /// - /// execution-apis bogota.md pins the fork-choice answer for a head just deemed VALID by - /// engine_newPayloadV6: it repeats the compliance answer determined there, so the expectation is - /// the fixture's inclusionListSatisfied. A fork-choice version that cannot carry the field is a - /// mismatch in its own right rather than an absent field. The reported payload status is named too: an - /// FCU answering SYNCING also reports no compliance, and that is a different failure from the head being - /// VALID and disagreeing. - /// - internal static string? DescribeFcuInclusionListMismatch(JsonRpcResponse response, TestEngineNewPayloadsJson enginePayload, int fcuVersion) - { - if (enginePayload.InclusionListSatisfied is not bool expected) return null; - - if ((response as IResultWrapper)?.Data is not ForkchoiceUpdatedV2Result result) - return $"engine_forkchoiceUpdatedV{fcuVersion} answered with {((response as IResultWrapper)?.Data ?? response).GetType().Name}, which cannot report inclusionListSatisfied, expected {expected}"; - - bool? actual = result.PayloadStatus.InclusionListSatisfied; - - return actual == expected + /// The verdict engine_newPayloadV6 returned. + internal static string? DescribeInclusionVerdictMismatch(TestEngineNewPayloadsJson enginePayload, bool? verdict, int payloadVersion) => + enginePayload.InclusionListSatisfied is not bool expected || verdict == expected ? null - : $"engine_forkchoiceUpdatedV{fcuVersion} returned {result.PayloadStatus.Status} and reported inclusionListSatisfied={actual?.ToString() ?? "null"}, expected {expected}"; - } - - private static void AssertFcuInclusionListSatisfied(JsonRpcResponse response, TestEngineNewPayloadsJson enginePayload, int fcuVersion) => - Assert.That(DescribeFcuInclusionListMismatch(response, enginePayload, fcuVersion), Is.Null); + : $"engine_newPayloadV{payloadVersion} inclusion check reported inclusionListSatisfied={verdict?.ToString() ?? "null"}, expected {expected}"; private static void AssertValidationError(string? actualError, string expectedError, int payloadVersion) { @@ -1156,10 +1149,7 @@ private static void AssertFcuValid(JsonRpcResponse response, int fcuVersion, Has string? status = response switch { ResultWrapper resultWrapper => resultWrapper.Data?.PayloadStatus.Status, - // engine_forkchoiceUpdatedV5 returns ForkchoiceUpdatedV2Result, which does not derive from V1. - ResultWrapper v2Wrapper => v2Wrapper.Data?.PayloadStatus.Status, JsonRpcSuccessResponse { Result: ForkchoiceUpdatedV1Result result } => result.PayloadStatus.Status, - JsonRpcSuccessResponse { Result: ForkchoiceUpdatedV2Result v2Result } => v2Result.PayloadStatus.Status, _ => null }; Assert.That(status, Is.EqualTo(PayloadStatus.Valid), $"engine_forkchoiceUpdatedV{fcuVersion} to {blockHash} answered {response.GetType().Name}"); diff --git a/src/Nethermind/Ethereum.Test.Base/JsonToEthereumTest.cs b/src/Nethermind/Ethereum.Test.Base/JsonToEthereumTest.cs index 6d86d7dceaf9..6d587cf4dc7c 100644 --- a/src/Nethermind/Ethereum.Test.Base/JsonToEthereumTest.cs +++ b/src/Nethermind/Ethereum.Test.Base/JsonToEthereumTest.cs @@ -133,9 +133,9 @@ public static BlockHeader Convert(TestBlockHeaderJson? headerJson) return engineNewPayload.ValidationError; } - // An inline validation error trails the real arguments, and newPayloadV6 adds a fifth one, - // so index 4 there is the inclusion list rather than the error. - int validationErrorParamIndex = newPayloadVersion >= 6 ? 5 : newPayloadVersion >= 4 ? 4 : 3; + // An inline validation error trails the real arguments, and newPayloadV6 adds two more: the separate + // inclusion lists and the omission claims. + int validationErrorParamIndex = newPayloadVersion >= 6 ? 6 : newPayloadVersion >= 4 ? 4 : 3; if (engineNewPayload.Params.Length <= validationErrorParamIndex) { return null; diff --git a/src/Nethermind/Nethermind.AuRa.Test/AuraBlockProcessorTests.cs b/src/Nethermind/Nethermind.AuRa.Test/AuraBlockProcessorTests.cs index 646875d57276..b92b9df6f476 100644 --- a/src/Nethermind/Nethermind.AuRa.Test/AuraBlockProcessorTests.cs +++ b/src/Nethermind/Nethermind.AuRa.Test/AuraBlockProcessorTests.cs @@ -29,7 +29,6 @@ using Nethermind.Logging; using Nethermind.Specs; using Nethermind.Specs.Forks; -using Nethermind.State; using Nethermind.TxPool; using NSubstitute; using NUnit.Framework; @@ -307,9 +306,7 @@ static BlockHeader Process(BranchProcessor auRaBlockProcessor, BlockHeader paren GnosisSpecProvider.Instance, stateProvider, blockhashProvider, - new InclusionListSatisfactionChecker(GnosisSpecProvider.Instance, Substitute.For()), - LimboLogs.Instance, - Substitute.For()); + LimboLogs.Instance); return (branchProcessor, stateProvider, blockTree, stateHeaderProvider); } diff --git a/src/Nethermind/Nethermind.BeaconChain.Test/Engine/EngineTests.cs b/src/Nethermind/Nethermind.BeaconChain.Test/Engine/EngineTests.cs index f3f1064cd96c..b5edc21bcebc 100644 --- a/src/Nethermind/Nethermind.BeaconChain.Test/Engine/EngineTests.cs +++ b/src/Nethermind/Nethermind.BeaconChain.Test/Engine/EngineTests.cs @@ -264,7 +264,6 @@ public void Payload_converter_maps_fields_versioned_hashes_and_requests([Values] [TestCase(PayloadStatus.Valid, ExecutionStatus.Valid)] [TestCase(PayloadStatus.Syncing, ExecutionStatus.Optimistic)] [TestCase(PayloadStatus.Accepted, ExecutionStatus.Optimistic)] - [TestCase(PayloadStatus.InclusionListUnsatisfied, ExecutionStatus.Optimistic)] [TestCase(PayloadStatus.Invalid, ExecutionStatus.Invalid)] public async Task Engine_driver_maps_statuses_and_bridges_the_transition_hook(string status, ExecutionStatus expected) { @@ -507,7 +506,6 @@ public void Payload_converter_maps_a_gloas_payload_onto_v4_and_encodes_builder_r [TestCase(PayloadStatus.Valid, ExecutionStatus.Valid)] [TestCase(PayloadStatus.Syncing, ExecutionStatus.Optimistic)] [TestCase(PayloadStatus.Accepted, ExecutionStatus.Optimistic)] - [TestCase(PayloadStatus.InclusionListUnsatisfied, ExecutionStatus.Optimistic)] [TestCase(PayloadStatus.Invalid, ExecutionStatus.Invalid)] public void Engine_driver_notifies_a_gloas_envelope_payload_through_newPayloadV5_and_maps_its_status(string status, ExecutionStatus expected) { diff --git a/src/Nethermind/Nethermind.BeaconChain/Engine/ExternalClInterceptingEngineRpcModule.cs b/src/Nethermind/Nethermind.BeaconChain/Engine/ExternalClInterceptingEngineRpcModule.cs index a73d7cd02946..e68f3df77190 100644 --- a/src/Nethermind/Nethermind.BeaconChain/Engine/ExternalClInterceptingEngineRpcModule.cs +++ b/src/Nethermind/Nethermind.BeaconChain/Engine/ExternalClInterceptingEngineRpcModule.cs @@ -89,8 +89,8 @@ public Task> engine_newPayloadV4(ExecutionPayload public Task> engine_newPayloadV5(ExecutionPayloadV4 executionPayload, Hash256?[] blobVersionedHashes, Hash256? parentBeaconBlockRoot, byte[][]? executionRequests) => Detect(() => _engine.engine_newPayloadV5(executionPayload, blobVersionedHashes, parentBeaconBlockRoot, executionRequests)); - public Task> engine_newPayloadV6(ExecutionPayloadV4 executionPayload, Hash256?[] blobVersionedHashes, Hash256? parentBeaconBlockRoot, byte[][]? executionRequests, byte[][]? inclusionListTransactions) - => Detect(() => _engine.engine_newPayloadV6(executionPayload, blobVersionedHashes, parentBeaconBlockRoot, executionRequests, inclusionListTransactions)); + public Task> engine_newPayloadV6(ExecutionPayloadV4 executionPayload, Hash256?[] blobVersionedHashes, Hash256? parentBeaconBlockRoot, byte[][]? executionRequests, byte[][][]? inclusionLists, OmissionClaim[]? omissionClaims) + => Detect(() => _engine.engine_newPayloadV6(executionPayload, blobVersionedHashes, parentBeaconBlockRoot, executionRequests, inclusionLists, omissionClaims)); public Task> engine_forkchoiceUpdatedV1(ForkchoiceStateV1 forkchoiceState, PayloadAttributes? payloadAttributes = null) => Detect(() => _engine.engine_forkchoiceUpdatedV1(forkchoiceState, payloadAttributes)); @@ -104,7 +104,7 @@ public Task> engine_forkchoiceUpdatedV3 public Task> engine_forkchoiceUpdatedV4(ForkchoiceStateV1 forkchoiceState, PayloadAttributes? payloadAttributes = null, BitArray? custodyColumns = null) => Detect(() => _engine.engine_forkchoiceUpdatedV4(forkchoiceState, payloadAttributes, custodyColumns)); - public Task> engine_forkchoiceUpdatedV5(ForkchoiceStateV1 forkchoiceState, PayloadAttributes? payloadAttributes = null, BitArray? custodyColumns = null) + public Task> engine_forkchoiceUpdatedV5(ForkchoiceStateV1 forkchoiceState, PayloadAttributes? payloadAttributes = null, BitArray? custodyColumns = null) => Detect(() => _engine.engine_forkchoiceUpdatedV5(forkchoiceState, payloadAttributes, custodyColumns)); public Task> engine_newPayloadWithWitnessV4(ExecutionPayloadV3 executionPayload, Hash256?[] blobVersionedHashes, Hash256? parentBeaconBlockRoot, byte[][]? executionRequests) @@ -113,8 +113,8 @@ public Task> engine_newPayloadWithW public Task> engine_newPayloadWithWitnessV5(ExecutionPayloadV4 executionPayload, Hash256?[] blobVersionedHashes, Hash256? parentBeaconBlockRoot, byte[][]? executionRequests) => ForwardWitnessCall(() => _engine.engine_newPayloadWithWitnessV5(executionPayload, blobVersionedHashes, parentBeaconBlockRoot, executionRequests)); - public Task> engine_newPayloadWithWitnessV6(ExecutionPayloadV4 executionPayload, Hash256?[] blobVersionedHashes, Hash256? parentBeaconBlockRoot, byte[][]? executionRequests, byte[][]? inclusionListTransactions) - => ForwardWitnessCall(() => _engine.engine_newPayloadWithWitnessV6(executionPayload, blobVersionedHashes, parentBeaconBlockRoot, executionRequests, inclusionListTransactions)); + public Task> engine_newPayloadWithWitnessV6(ExecutionPayloadV4 executionPayload, Hash256?[] blobVersionedHashes, Hash256? parentBeaconBlockRoot, byte[][]? executionRequests, byte[][][]? inclusionLists, OmissionClaim[]? omissionClaims) + => ForwardWitnessCall(() => _engine.engine_newPayloadWithWitnessV6(executionPayload, blobVersionedHashes, parentBeaconBlockRoot, executionRequests, inclusionLists, omissionClaims)); public ResultWrapper> engine_exchangeCapabilities(IEnumerable methods) => _engine.engine_exchangeCapabilities(methods); @@ -143,6 +143,9 @@ public ResultWrapper engine_exchangeTransitionConfigu public Task> engine_getPayloadV6(byte[] payloadId) => _engine.engine_getPayloadV6(payloadId); + public Task> engine_getPayloadV7(byte[] payloadId) + => _engine.engine_getPayloadV7(payloadId); + public ResultWrapper> engine_getPayloadBodiesByHashV1(IReadOnlyList blockHashes) => _engine.engine_getPayloadBodiesByHashV1(blockHashes); diff --git a/src/Nethermind/Nethermind.Benchmark/Core/Eip8369VerifyBudgetFillBenchmarks.cs b/src/Nethermind/Nethermind.Benchmark/Core/Eip8369VerifyBudgetFillBenchmarks.cs new file mode 100644 index 000000000000..9242a398b57f --- /dev/null +++ b/src/Nethermind/Nethermind.Benchmark/Core/Eip8369VerifyBudgetFillBenchmarks.cs @@ -0,0 +1,128 @@ +// SPDX-FileCopyrightText: 2026 Demerzel Solutions Limited +// SPDX-License-Identifier: LGPL-3.0-only + +using System; +using System.Collections.Generic; +using System.Security.Cryptography; +using BenchmarkDotNet.Attributes; +using Nethermind.Consensus.Processing; +using Nethermind.Core; +using Nethermind.Core.Crypto; +using Nethermind.Core.Specs; +using Nethermind.Core.Test.Builders; +using Nethermind.Crypto; +using Nethermind.Int256; +using Nethermind.Serialization.Rlp; +using Nethermind.Specs.Forks; + +namespace Nethermind.Benchmarks.Core; + +/// +/// The EIP-7805 per-IL VERIFY budget fill at its most signature-heavy: all 16 committee positions filled to +/// MAX_TRANSACTIONS_BYTES_PER_INCLUSION_LIST with the smallest frame transactions that carry one +/// signature, each verifying in full and then failing, so the fill debits only the signature cost. +/// +/// The byte cap binds before the gas budget: at the signature debit alone a position could hold about +/// 370 secp256k1 or 150 P256 entries, but its 8 KiB fits far fewer. Distinct entries at every position is the +/// worst case; one set shared by all positions is what the per-hash verification memo collapses. +[MemoryDiagnoser] +public class Eip8369VerifyBudgetFillBenchmarks +{ + private static readonly IReleaseSpec Spec = new Specs.Test.OverridableReleaseSpec(Bogota.Instance) { IsEip8141Enabled = true }; + private readonly EthereumEcdsa _ecdsa = new(BlockchainIds.Mainnet); + + private Transaction[][] _distinctSecp256k1 = []; + private Transaction[][] _sharedSecp256k1 = []; + private Transaction[][] _distinctP256 = []; + + [GlobalSetup] + public void Setup() + { + _distinctSecp256k1 = Fill(Secp256k1Signature, distinct: true); + _sharedSecp256k1 = Fill(Secp256k1Signature, distinct: false); + _distinctP256 = Fill(P256Signature, distinct: true); + Console.WriteLine($"// entries: distinct secp256k1 {InclusionLists.Distinct(_distinctSecp256k1).Length}, shared secp256k1 {InclusionLists.Distinct(_sharedSecp256k1).Length}, distinct P256 {InclusionLists.Distinct(_distinctP256).Length}"); + } + + [Benchmark(Baseline = true)] + public int Secp256k1_distinct_at_every_position() => Run(_distinctSecp256k1); + + [Benchmark] + public int Secp256k1_shared_by_every_position() => Run(_sharedSecp256k1); + + [Benchmark] + public int P256_distinct_at_every_position() => Run(_distinctP256); + + private int Run(Transaction[][] inclusionLists) => + Eip8369Profile2.AdmitByVerifyBudget(InclusionLists.InFillOrder(inclusionLists), Eip8369Constants.MaxVerifyGasPerTx, + tx => Profile2EligibilityReplayer.AreSignaturesValid(tx, _ecdsa, Spec)).Count; + + /// Fills every position to its byte cap, with fresh entries per position or one list for all. + private static Transaction[][] Fill(Func signature, bool distinct) + { + Transaction[][] inclusionLists = new Transaction[Eip7805Constants.InclusionListCommitteeSize][]; + ulong nonce = 0; + for (int position = 0; position < inclusionLists.Length; position++) + { + if (!distinct && position > 0) + { + inclusionLists[position] = inclusionLists[0]; + continue; + } + + List transactions = []; + int bytes = 0; + while (true) + { + Transaction tx = FrameTx(nonce++, signature); + byte[] encoded = TxDecoder.Instance.Encode(tx, RlpBehaviors.SkipTypedWrapping); + if (bytes + encoded.Length > Eip7805Constants.MaxBytesPerInclusionList) break; + bytes += encoded.Length; + tx.Hash = Keccak.Compute(encoded); + transactions.Add(tx); + } + inclusionLists[position] = [.. transactions]; + } + return inclusionLists; + } + + private static Transaction FrameTx(ulong nonce, Func signature) => new() + { + Type = TxType.FrameTx, + ChainId = BlockchainIds.Mainnet, + Nonce = nonce, + SenderAddress = TestItem.AddressA, + Frames = [new TxFrame(FrameMode.Verify, FrameFlags.ApproveExecutionAndPayment, target: null, gasLimit: 1, UInt256.Zero, default)], + FrameSignatures = [signature(nonce)], + GasPrice = 1, + DecodedMaxFeePerGas = 1, + }; + + // A canonical signature by another key over another message: recovery runs in full, then the signer mismatches. + private static TxFrameSignature Secp256k1Signature(ulong seed) + { + Signature signed = new EthereumEcdsa(BlockchainIds.Mainnet).Sign(TestItem.PrivateKeyB, Keccak.Compute(seed.ToString()).ValueHash256); + byte[] raw = new byte[TxFrameSignature.Secp256k1SignatureLength]; + raw[0] = signed.RecoveryId; + signed.R.Span.CopyTo(raw.AsSpan(1, 32)); + signed.S.Span.CopyTo(raw.AsSpan(33, 32)); + return new TxFrameSignature(TxFrameSignature.SchemeSecp256k1, TestItem.AddressA, ReadOnlyMemory.Empty, raw); + } + + // A real key whose address is the signer, with a low-s signature over another message: P256VERIFY runs and fails. + private static TxFrameSignature P256Signature(ulong seed) + { + using ECDsa key = ECDsa.Create(ECCurve.NamedCurves.nistP256); + ECParameters parameters = key.ExportParameters(false); + byte[] rs = key.SignHash(Keccak.Compute(seed.ToString()).BytesToArray(), DSASignatureFormat.IeeeP1363FixedFieldConcatenation); + UInt256 s = new(rs.AsSpan(32, 32), isBigEndian: true); + if (s > SecP256r1Curve.HalfN) (SecP256r1Curve.N - s).ToBigEndian(rs.AsSpan(32, 32)); + + byte[] raw = new byte[TxFrameSignature.P256SignatureLength]; + rs.CopyTo(raw, 0); + parameters.Q.X!.CopyTo(raw, 64); + parameters.Q.Y!.CopyTo(raw, 96); + Address signer = new(Keccak.Compute(raw.AsSpan(64, 64)).Bytes[12..]); + return new TxFrameSignature(TxFrameSignature.SchemeP256, signer, ReadOnlyMemory.Empty, raw); + } +} diff --git a/src/Nethermind/Nethermind.Blockchain.Test/BlockProcessorTests.cs b/src/Nethermind/Nethermind.Blockchain.Test/BlockProcessorTests.cs index 5b5172de2e02..03cbe8b444a7 100644 --- a/src/Nethermind/Nethermind.Blockchain.Test/BlockProcessorTests.cs +++ b/src/Nethermind/Nethermind.Blockchain.Test/BlockProcessorTests.cs @@ -2447,9 +2447,7 @@ private static (BlockProcessor processor, BranchProcessor branchProcessor, IWorl specProvider, stateProvider, Substitute.For(), - new InclusionListSatisfactionChecker(HoodiSpecProvider.Instance, Substitute.For()), LimboLogs.Instance, - Substitute.For(), preWarmer); return (processor, branchProcessor, stateProvider, stateHeaderProvider); @@ -4524,9 +4522,7 @@ private static CanonicalReceiptEventSetup BuildCanonicalReceiptEventSetup(bool b specProvider, stateProvider, Substitute.For(), - new InclusionListSatisfactionChecker(specProvider, Substitute.For()), - LimboLogs.Instance, - Substitute.For()); + LimboLogs.Instance); return new(block, stateHeaderProvider.Parent!, balManager, handler, executor, branchProcessor, container); } diff --git a/src/Nethermind/Nethermind.Blockchain.Test/BlockchainProcessorTests.cs b/src/Nethermind/Nethermind.Blockchain.Test/BlockchainProcessorTests.cs index b4e36305466a..2156ae72804c 100644 --- a/src/Nethermind/Nethermind.Blockchain.Test/BlockchainProcessorTests.cs +++ b/src/Nethermind/Nethermind.Blockchain.Test/BlockchainProcessorTests.cs @@ -247,10 +247,6 @@ private class BranchProcessorMock : IBranchProcessor internal readonly HashSet Processed = []; - // The instance actually handed to the branch processor, so tests can assert that transient - // non-RLP data survived recovery-queue resolution. - internal readonly ConcurrentDictionary ProcessedBlockByHash = new(); - private readonly ConcurrentHashSet _allowedToFail = []; private readonly HashSet _rootProcessed = []; @@ -305,7 +301,6 @@ public Block[] Process(BlockHeader? baseBlock, IReadOnlyList suggestedBlo } Processed.AddRange(suggestedBlocks.Select(x => x.Hash!)); - foreach (Block suggested in suggestedBlocks) ProcessedBlockByHash[suggested.Hash!] = suggested; _logger.Info($"Processing {suggestedBlocks.Last().ToString(Block.Format.Short)}"); int nextBlock = 0; @@ -524,18 +519,6 @@ public ProcessingTestContext AndRecoveryQueueLimitHasBeenReached() return this; } - public ProcessingTestContext InclusionListPreservedFor(Block block) - { -#pragma warning disable NUnit2045 // The successful prerequisite is required before accessing its result. - Assert.That(_branchProcessor.ProcessedBlockByHash.TryGetValue(block.Hash!, out Block? processed), Is.True, - $"Block {block.ToString(Block.Format.Short)} was not processed"); -#pragma warning restore NUnit2045 - Assert.That(processed!.InclusionListTransactions, Is.Not.Null, - "Inclusion list was dropped before validation (recovery-queue re-resolve stripped it)"); - Assert.That(processed.InclusionListTransactions!, Has.Length.EqualTo(block.InclusionListTransactions!.Length)); - return this; - } - public AfterBlock Processed(Block block) { _headBefore = _blockTree.Head?.Hash; @@ -1782,21 +1765,6 @@ public void Can_change_branch_on_invalid_block_when_invalid_branch_is_in_the_que .ProcessedSkipped(_block4D8).IsDeletedAsInvalid() .FullyProcessed(_blockB2D4).BecomesNewHead(); - // A hash-only BlockRef re-resolved from the DB would lose the non-RLP inclusion list before validation. - [Test, MaxTime(Timeout.MaxTestTime)] - public void Inclusion_list_survives_recovery_queue_backlog() - { - Transaction ilTx = Build.A.Transaction.SignedAndResolved(TestItem.PrivateKeyA).TestObject; - Block ilBlock = Build.A.Block.WithNumber(1).WithNonce(111).WithParent(_block0).WithDifficulty(2) - .WithInclusionListTransactions([ilTx]).TestObject; - - When.ProcessingBlocks - .AndRecoveryQueueLimitHasBeenReached() - .FullyProcessed(_block0).BecomesGenesis() - .FullyProcessed(ilBlock).BecomesNewHead() - .InclusionListPreservedFor(ilBlock); - } - [Test, MaxTime(Timeout.MaxTestTime)] [Ignore("Not implemented yet - scenario when from suggested blocks we can see that previously suggested will not be winning")] [Todo(Improve.Performance, "We can skip processing losing branches by implementing code to pass this test")] diff --git a/src/Nethermind/Nethermind.Blockchain.Test/Profile2EligibilityReplayerTests.cs b/src/Nethermind/Nethermind.Blockchain.Test/Profile2EligibilityReplayerTests.cs new file mode 100644 index 000000000000..00b89a53ccfa --- /dev/null +++ b/src/Nethermind/Nethermind.Blockchain.Test/Profile2EligibilityReplayerTests.cs @@ -0,0 +1,324 @@ +// SPDX-FileCopyrightText: 2026 Demerzel Solutions Limited +// SPDX-License-Identifier: LGPL-3.0-only + +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Threading.Tasks; +using Autofac; +using Nethermind.Config; +using Nethermind.Consensus.Processing; +using Nethermind.Core; +using Nethermind.Core.BlockAccessLists; +using Nethermind.Core.Crypto; +using Nethermind.Core.Extensions; +using Nethermind.Core.Specs; +using Nethermind.Core.Test.Blockchain; +using Nethermind.Core.Test.Builders; +using Nethermind.Core.Test.Container; +using Nethermind.Crypto; +using Nethermind.Evm; +using Nethermind.Evm.State; +using Nethermind.Int256; +using Nethermind.Logging; +using Nethermind.Specs; +using Nethermind.Specs.Forks; +using Nethermind.Specs.Test; +using NUnit.Framework; + +namespace Nethermind.Blockchain.Test; + +/// EIP-8369 Profile 2 eligibility replayed at an evaluation index over the node's own wiring. +/// The sender approves only while the storage slot it reads is zero, so the access list decides the +/// verdict by writing that slot, or the sender's nonce or balance, at a chosen block access index. +[TestFixture] +public class Profile2EligibilityReplayerTests +{ + private static readonly Address Sender = TestItem.AddressD; + private static readonly IReleaseSpec Spec = new OverridableReleaseSpec(Eip8141Prototype.Instance) { IsEip8272Enabled = true }; + private const ulong BlockSlot = 10_000; + + public static IEnumerable Cases + { + get + { + // Block access index 0 is pre-execution; transaction i writes at index i + 1. + static TestCaseData Case(string name, byte slot, ReadOnlyAccountChanges? changes, int index, bool eligible) => + new(slot, changes, index, eligible) { TestName = name }; + + ReadOnlyAccountChanges slotWrittenByTx1 = Changes(storage: [new ReadOnlySlotChanges(0, [new StorageChange(2, 1)])]); + yield return Case("Eligible before the transaction that invalidates it", 0, slotWrittenByTx1, 1, true); + yield return Case("Ineligible after the transaction that invalidates it", 0, slotWrittenByTx1, 2, false); + yield return Case("Pre-execution writes precede index zero", 0, + Changes(storage: [new ReadOnlySlotChanges(0, [new StorageChange(0, 1)])]), 0, false); + + ReadOnlyAccountChanges nonceBumpedByTx0 = Changes(nonces: [new NonceChange(1, 1)]); + yield return Case("Nonce still matches before the transaction that bumps it", 0, nonceBumpedByTx0, 0, true); + yield return Case("Nonce mismatch after the transaction that bumps it", 0, nonceBumpedByTx0, 1, false); + + yield return Case("Payer that cannot cover the maximum cost is ineligible", 0, + Changes(balances: [new BalanceChange(1, UInt256.Zero)]), 1, false); + + yield return Case("Read of the last slot inside the surface is eligible", (byte)(Eip8369Constants.AaVopsSlotCount - 1), null, 0, true); + yield return Case("Read of the first slot outside the surface is ineligible", (byte)Eip8369Constants.AaVopsSlotCount, null, 0, false); + } + } + + [TestCaseSource(nameof(Cases))] + public async Task Replays_the_validation_prefix_at_the_evaluation_index(byte slot, ReadOnlyAccountChanges? changes, int index, bool eligible) + { + using BasicTestBlockchain chain = await CreateChain(slot); + IProfile2EligibilityReplayer replayer = chain.Container.Resolve(); + Block block = ChildOfHead(chain, new ReadOnlyBlockAccessList([changes ?? Changes()], 1)); + + Assert.That(IsEligible(replayer, block, FrameTx(), index), Is.EqualTo(eligible)); + } + + /// The payer is held to the max_cost execution escrows at the block's base fee, not to max_fee, + /// so a candidate the block could have included at this index is never judged ineligible. + [TestCase(0, true, TestName = "Payer holding exactly the escrow at the block's base fee is eligible")] + [TestCase(-1, false, TestName = "Payer one wei short of the escrow at the block's base fee is ineligible")] + public async Task Payer_is_bounded_by_the_escrow_at_the_blocks_base_fee(int offset, bool eligible) + { + using BasicTestBlockchain chain = await CreateChain(0); + IProfile2EligibilityReplayer replayer = chain.Container.Resolve(); + Transaction tx = FrameTx(); + BlockHeader header = ChildOfHead(chain, null).Header; + FrameTxValidation.TryCalculateGasBudget(tx, Spec, out _, out _, out ulong maxGas); + FrameTxFeeBudget.TryCalculate(tx.MaxFee, tx.MaxPriorityFeePerGas, maxGas, header.BaseFeePerGas, UInt256.Zero, out _, out UInt256 escrow); + UInt256 balance = offset < 0 ? escrow - 1 : escrow; + Block block = ChildOfHead(chain, new ReadOnlyBlockAccessList([Changes(balances: [new BalanceChange(1, balance)])], 1)); + + Assume.That(escrow, Is.LessThan(tx.MaxFee)); + Assert.That(IsEligible(replayer, block, tx, 1), Is.EqualTo(eligible)); + } + + [Test] + public async Task The_replay_is_bounded_by_the_forks_verify_gas_cap_whatever_the_local_cap() + { + using BasicTestBlockchain chain = await CreateChain(ApproveWhileSlotIsZero(0), localMaxVerifyGas: 1); + IProfile2EligibilityReplayer replayer = chain.Container.Resolve(); + + Assert.That(IsEligible(replayer, ChildOfHead(chain, new ReadOnlyBlockAccessList([Changes()], 1)), FrameTx(), 0), Is.True); + } + + [Test] + public async Task Max_fee_below_the_required_max_fee_at_the_blocks_base_fee_is_ineligible() + { + using BasicTestBlockchain chain = await CreateChain(0); + IProfile2EligibilityReplayer replayer = chain.Container.Resolve(); + Transaction tx = FrameTx(); + Block block = ChildOfHead(chain, new ReadOnlyBlockAccessList([Changes()], 1)); + FrameTxValidation.TryCalculateGasBudget(tx, Spec, out _, out _, out ulong maxGas); + block.Header.BaseFeePerGas = tx.MaxFee / maxGas + 1; + + Assert.That(IsEligible(replayer, block, tx, 0), Is.False); + } + + /// EIP-8369 Profile 2 bounds the prefix by MAX_VERIFY_GAS_PER_TX, not EIP-8141's mempool + /// MAX_VERIFY_GAS, so a prefix spending between the two is ineligible. + /// The frame declares 290,000, under MAX_VERIFY_GAS; the wide expansion alone runs past + /// MAX_VERIFY_GAS_PER_TX, which a replayer under the mempool bound would let through. + [TestCase(64UL, true, TestName = "Prefix well under MAX_VERIFY_GAS_PER_TX is eligible")] + [TestCase(11_000UL, false, TestName = "Prefix over MAX_VERIFY_GAS_PER_TX but under MAX_VERIFY_GAS is ineligible")] + public async Task Prefix_is_bounded_by_the_profile_2_cap(ulong memoryWords, bool eligible) + { + using BasicTestBlockchain chain = await CreateChain(ExpandMemoryThenApprove(memoryWords)); + IProfile2EligibilityReplayer replayer = chain.Container.Resolve(); + + Transaction tx = FrameTx(verifyGas: 290_000); + Assert.That(IsEligible(replayer, ChildOfHead(chain, new ReadOnlyBlockAccessList([Changes()], 1)), tx, 0), Is.EqualTo(eligible)); + } + + /// EIP-8369 § Attesters takes current_slot from the block itself, so the canonical + /// recent_root_verify frame accepts a reference exactly RECENT_ROOT_USABLE_WINDOW slots back, + /// and rejects one at the block's own slot. + [TestCase(BlockSlot - Eip8272Constants.RecentRootUsableWindow, true, TestName = "Recent root at the oldest usable slot is eligible")] + [TestCase(BlockSlot - 1, true, TestName = "Recent root one slot back is eligible")] + [TestCase(BlockSlot, false, TestName = "Recent root at the block's own slot is ineligible")] + public async Task Recent_roots_are_anchored_at_the_blocks_own_slot(ulong referenceSlot, bool eligible) + { + ValueHash256 sourceId = Keccak.Compute("source").ValueHash256; + ValueHash256 root = Keccak.Compute("root").ValueHash256; + using BasicTestBlockchain chain = await CreateChain(ApproveWhileSlotIsZero(0), worldState => + { + worldState.CreateAccountIfNotExists(Eip8272Constants.RecentRootAddress, UInt256.Zero, 1); + worldState.InsertCode(Eip8272Constants.RecentRootAddress, Eip8272Constants.RecentRootCode, Spec); + worldState.Set(RecentRootStore.ReferenceCell(sourceId, referenceSlot), RecentRootStore.EntryHash(sourceId, referenceSlot, root).ToUInt256()); + }); + IProfile2EligibilityReplayer replayer = chain.Container.Resolve(); + + Transaction tx = FrameTx(); + tx.Frames = [FrameTxTestFrames.RecentRootVerify(50_000, (sourceId, referenceSlot, root)), .. tx.Frames!]; + Assert.That(IsEligible(replayer, ChildOfHead(chain, new ReadOnlyBlockAccessList([Changes()], 1)), tx, 0), Is.EqualTo(eligible)); + } + + public enum DeployFactory { Contract, Codeless, Delegated } + + /// EIP-7805 replay: the deploy frame's factory is a dependency of the deployment, so it must be a contract + /// whose code no authority can change. A delegated factory CREATEs the same sender as the contract it delegates to, + /// so only the factory rule tells them apart. + [TestCase(DeployFactory.Contract, true, TestName = "Deploy frame through a contract factory is eligible")] + [TestCase(DeployFactory.Codeless, false, TestName = "Deploy frame through a codeless factory is ineligible")] + [TestCase(DeployFactory.Delegated, false, TestName = "Deploy frame through a delegated factory is ineligible")] + public async Task Deploy_frame_factory_must_be_an_undelegated_contract(DeployFactory kind, bool eligible) + { + Address factory = TestItem.AddressE; + Address delegate_ = TestItem.AddressF; + Address deployed = ContractAddress.From(factory, 0); + byte[] approve = [(byte)Instruction.PUSH1, (byte)FrameFlags.ApproveExecutionAndPayment, (byte)Instruction.PUSH1, 0, (byte)Instruction.PUSH1, 0, (byte)Instruction.APPROVE]; + byte[] create = Prepare.EvmCode.Create(Prepare.EvmCode.ForInitOf(approve).Done, 0).Done; + using BasicTestBlockchain chain = await CreateChain([], worldState => + { + worldState.CreateAccount(deployed, 10.Ether); + switch (kind) + { + case DeployFactory.Contract: + worldState.CreateAccount(factory, 0); + worldState.InsertCode(factory, create, Spec); + break; + case DeployFactory.Delegated: + worldState.CreateAccount(delegate_, 0); + worldState.InsertCode(delegate_, create, Spec); + worldState.CreateAccount(factory, 0); + worldState.InsertCode(factory, (byte[])[.. Eip7702Constants.DelegationHeader, .. delegate_.Bytes], Spec); + break; + } + }); + IProfile2EligibilityReplayer replayer = chain.Container.Resolve(); + + Transaction tx = FrameTx(); + tx.SenderAddress = deployed; + tx.Frames = [new TxFrame(FrameMode.Default, FrameFlags.None, factory, executionGasLimit: 200_000, stateGasLimit: 200_000, UInt256.Zero, default), .. tx.Frames!]; + + Assert.That(IsEligible(replayer, ChildOfHead(chain, new ReadOnlyBlockAccessList([Changes()], 1)), tx, 0), Is.EqualTo(eligible)); + } + + /// With no access list there is no state to reconstruct, which neither excuses the omission nor decides it. + [Test] + public async Task A_block_without_an_access_list_leaves_the_candidate_undecided() + { + using BasicTestBlockchain chain = await CreateChain(slot: (byte)Eip8369Constants.AaVopsSlotCount); + IProfile2EligibilityReplayer replayer = chain.Container.Resolve(); + + Assert.That(IsEligible(replayer, ChildOfHead(chain, null), FrameTx(), 0), Is.Null); + } + + /// Several candidates at several indices, in no particular order, reconstruct the block's state + /// once and still see each index's own state. + [Test] + public async Task A_batch_reconstructs_the_state_once_and_judges_each_index_on_its_own_state() + { + using BasicTestBlockchain chain = await CreateChain(slot: 0); + CountingEnvFactory envFactory = new(chain.Container.Resolve()); + using Profile2EligibilityReplayer replayer = new(envFactory, chain.Container.Resolve(), LimboLogs.Instance); + Block block = ChildOfHead(chain, new ReadOnlyBlockAccessList( + [Changes(storage: [new ReadOnlySlotChanges(0, [new StorageChange(2, 1), new StorageChange(3, 0)])])], 1)); + + bool?[] eligible = replayer.AreEligible(block, + [(FrameTx(), 2), (FrameTx(), 0), (FrameTx(), 1), (FrameTx(), 0), (FrameTx(), 2), (FrameTx(), 1), (FrameTx(), 3)], Spec); + + using (Assert.EnterMultipleScope()) + { + // Slot 0 is set by transaction 1 and cleared by transaction 2, so only index 2 sees it set. + Assert.That(eligible, Is.EqualTo(new bool?[] { false, true, true, true, false, true, true })); + Assert.That(envFactory.ScopesBuilt, Is.EqualTo(1)); + } + } + + /// Counts the parent-state scopes the replayer opens, each one a reconstruction of the block's state. + private sealed class CountingEnvFactory(IReadOnlyTxProcessingEnvFactory inner) : IReadOnlyTxProcessingEnvFactory + { + public int ScopesBuilt { get; private set; } + + public IReadOnlyTxProcessorSource Create() => new CountingSource(inner.Create(), this); + + private sealed class CountingSource(IReadOnlyTxProcessorSource inner, CountingEnvFactory owner) : IReadOnlyTxProcessorSource + { + public bool TryBuild(BlockHeader? baseBlock, [NotNullWhen(true)] out IReadOnlyTxProcessingScope? scope) => inner.TryBuild(baseBlock, out scope); + + public bool TryBuildAtTarget(BlockHeader targetBlock, [NotNullWhen(true)] out IReadOnlyTxProcessingScope? scope) + { + owner.ScopesBuilt++; + return inner.TryBuildAtTarget(targetBlock, out scope); + } + + public void Dispose() => inner.Dispose(); + } + } + + private static bool? IsEligible(IProfile2EligibilityReplayer replayer, Block block, Transaction tx, int index) => + replayer.AreEligible(block, [(tx, index)], Spec)[0]; + + private static Task CreateChain(byte slot) => CreateChain(ApproveWhileSlotIsZero(slot)); + + private static Task CreateChain(byte[] senderCode, Action? genesis = null, ulong? localMaxVerifyGas = null) => BasicTestBlockchain.Create(builder => + { + builder.AddSingleton(new TestSpecProvider(Spec)); + if (localMaxVerifyGas is { } cap) builder.AddSingleton(new BlocksConfig { FocilProfile2MaxVerifyGas = cap }); + builder.AddScoped((worldState, specProvider) => + new FunctionalGenesisPostProcessor(_ => + { + worldState.CreateAccount(Sender, 10.Ether); + worldState.InsertCode(Sender, senderCode, specProvider.GenesisSpec); + genesis?.Invoke(worldState); + worldState.RecalculateStateRoot(); + })); + }); + + private static Block ChildOfHead(BasicTestBlockchain chain, ReadOnlyBlockAccessList? blockAccessList) + { + BlockHeader head = chain.BlockTree.Head!.Header; + Block block = Build.A.Block + .WithParent(head) + .WithTimestamp(head.Timestamp + 12) + .WithGasLimit(30_000_000) + .WithSlotNumber(BlockSlot) + .WithTransactions(Build.A.Transaction.TestObject, Build.A.Transaction.WithNonce(1).TestObject) + .TestObject; + block.BlockAccessList = blockAccessList; + return block; + } + + private static ReadOnlyAccountChanges Changes( + ReadOnlySlotChanges[]? storage = null, NonceChange[]? nonces = null, BalanceChange[]? balances = null) => + new(Sender, storage ?? [], [], balances ?? [], nonces ?? [], []); + + // SLOAD(slot); nonzero jumps to a revert, zero approves execution and payment. + private static byte[] ApproveWhileSlotIsZero(byte slot) => + [ + (byte)Instruction.PUSH1, slot, (byte)Instruction.SLOAD, + (byte)Instruction.PUSH1, 0x0e, (byte)Instruction.JUMPI, + (byte)Instruction.PUSH1, (byte)FrameFlags.ApproveExecutionAndPayment, + (byte)Instruction.PUSH1, 0, (byte)Instruction.PUSH1, 0, (byte)Instruction.APPROVE, + (byte)Instruction.STOP, + (byte)Instruction.JUMPDEST, (byte)Instruction.PUSH1, 0, (byte)Instruction.PUSH1, 0, (byte)Instruction.REVERT, + ]; + + // Expands memory to the given number of words with one MLOAD, then approves execution and payment. + private static byte[] ExpandMemoryThenApprove(ulong words) + { + ulong offset = (words - 1) * 32; + return + [ + (byte)Instruction.PUSH3, (byte)(offset >> 16), (byte)(offset >> 8), (byte)offset, + (byte)Instruction.MLOAD, (byte)Instruction.POP, + (byte)Instruction.PUSH1, (byte)FrameFlags.ApproveExecutionAndPayment, + (byte)Instruction.PUSH1, 0, (byte)Instruction.PUSH1, 0, (byte)Instruction.APPROVE, + (byte)Instruction.STOP, + ]; + } + + private static Transaction FrameTx(ulong verifyGas = 100_000) => new() + { + Type = TxType.FrameTx, + ChainId = TestBlockchainIds.ChainId, + Nonce = 0, + SenderAddress = Sender, + Frames = [new TxFrame(FrameMode.Verify, FrameFlags.ApproveExecutionAndPayment, target: null, gasLimit: verifyGas, UInt256.Zero, default)], + FrameSignatures = [], + GasPrice = 1.GWei, + DecodedMaxFeePerGas = 1.GWei, + MaxFee = 1.Ether, + }; +} diff --git a/src/Nethermind/Nethermind.Blockchain.Test/ReorgTests.cs b/src/Nethermind/Nethermind.Blockchain.Test/ReorgTests.cs index c43827ab856b..0007cc24f4c8 100644 --- a/src/Nethermind/Nethermind.Blockchain.Test/ReorgTests.cs +++ b/src/Nethermind/Nethermind.Blockchain.Test/ReorgTests.cs @@ -24,7 +24,6 @@ using Nethermind.Evm.TransactionProcessing; using Nethermind.Logging; using Nethermind.Specs; -using Nethermind.TxPool; using Nethermind.Evm.State; using Nethermind.State; using NSubstitute; @@ -115,9 +114,7 @@ public void Setup() MainnetSpecProvider.Instance, stateProvider, blockhashProvider, - new InclusionListSatisfactionChecker(MainnetSpecProvider.Instance, Substitute.For()), - LimboLogs.Instance, - Substitute.For()); + LimboLogs.Instance); _blockchainProcessor = new BlockchainProcessor( _blockTree, diff --git a/src/Nethermind/Nethermind.Blockchain.Test/TransactionsExecutorTests.cs b/src/Nethermind/Nethermind.Blockchain.Test/TransactionsExecutorTests.cs index b23f356b77c4..5cb8eea181b8 100644 --- a/src/Nethermind/Nethermind.Blockchain.Test/TransactionsExecutorTests.cs +++ b/src/Nethermind/Nethermind.Blockchain.Test/TransactionsExecutorTests.cs @@ -726,6 +726,73 @@ public void Frame_transaction_that_can_never_pay_is_evicted_from_the_pool(FrameP } } + public enum ClaimSkip { NeverApproves, StaleNonce, BuilderPolicy } + + // EIP-8369: a claim binds the builder, which is judged at the claimed index alone, so a skipped candidate is + // claimed only where it is invalid, never where the builder's own policy passed it over. + [TestCase(ClaimSkip.NeverApproves, true, TestName = "Builder claims a candidate whose prefix fails at the index")] + [TestCase(ClaimSkip.StaleNonce, true, TestName = "Builder claims a candidate whose nonce is invalid at the index")] + [TestCase(ClaimSkip.BuilderPolicy, false, TestName = "Builder does not claim a candidate skipped by its own policy")] + public void Builder_claims_only_candidates_invalid_at_the_index(ClaimSkip skip, bool claimed) + { + ISpecProvider specProvider = new TestSpecProvider(Eip8369Prototype.Instance); + IReleaseSpec spec = specProvider.GenesisSpec; + IWorldState stateProvider = TestWorldStateFactory.CreateForTest(); + using IDisposable scope = stateProvider.BeginScope(IWorldState.PreGenesis); + stateProvider.CreateAccount(TestItem.AddressA, 100.Ether); + stateProvider.InsertCode(TestItem.AddressA, skip == ClaimSkip.NeverApproves + ? Prepare.EvmCode.Op(Instruction.JUMPDEST).PushData(0).Op(Instruction.JUMP).Done + : Prepare.EvmCode.PushData((byte)FrameFlags.ApproveExecutionAndPayment).PushData(0).PushData(0).Op(Instruction.APPROVE).Done, + spec); + stateProvider.Commit(spec); + stateProvider.CommitTree(0); + + Transaction candidate = new() + { + Type = TxType.FrameTx, + ChainId = TestBlockchainIds.ChainId, + Nonce = skip == ClaimSkip.StaleNonce ? 5UL : 0UL, + NonceKeys = [UInt256.Zero], + SenderAddress = TestItem.AddressA, + Frames = [new TxFrame(FrameMode.Verify, FrameFlags.ApproveExecutionAndPayment, target: null, 100_000, UInt256.Zero, default)], + FrameSignatures = [], + GasLimit = 100_000, + GasPrice = 1, + DecodedMaxFeePerGas = 1, + }; + candidate.Hash = candidate.CalculateHash(); + + EthereumVirtualMachine virtualMachine = new(new TestBlockhashProvider(specProvider), specProvider, LimboLogs.Instance); + ITransactionProcessor transactionProcessor = new EthereumTransactionProcessor( + BlobBaseFeeCalculator.Instance, specProvider, stateProvider, virtualMachine, + new EthereumCodeInfoRepository(stateProvider), LimboLogs.Instance); + BlockProcessor.BlockProductionTransactionsExecutor txExecutor = new( + new BuildUpTransactionProcessorAdapter(transactionProcessor), + stateProvider, + // A zero transaction-size budget stands in for any skip of the builder's own choosing. + new BlockProcessor.BlockProductionTransactionPicker(specProvider, skip == ClaimSkip.BuilderPolicy ? 0 : BlocksConfig.DefaultMaxTxKilobytes), + LimboLogs.Instance, + NullBlockAccessListManager.Instance, + NullTxPool.Instance); + + Block block = Build.A.Block.WithNumber(1).WithBaseFeePerGas(0).WithGasLimit(30_000_000).TestObject; + BlockToProduce blockToProduce = new(block.Header, [candidate], []) + { + InclusionListCandidates = new HashSet { candidate.Hash }, + }; + BlockReceiptsTracer receiptsTracer = new(); + receiptsTracer.StartNewBlockTrace(blockToProduce); + txExecutor.SetBlockExecutionContext(new BlockExecutionContext(blockToProduce.Header, spec)); + txExecutor.ProcessTransactions(blockToProduce, ProcessingOptions.ProducingBlock, receiptsTracer, CancellationToken.None); + + using (Assert.EnterMultipleScope()) + { + Assert.That(blockToProduce.Transactions, Is.Empty); + Assert.That(blockToProduce.OmissionClaims ?? [], + claimed ? Is.EqualTo(new[] { new OmissionClaim(candidate.Hash, 0) }) : Is.Empty); + } + } + private sealed class CountingTxProcessorAdapter(ITransactionProcessorAdapter inner) : ITransactionProcessorAdapter { public int Attempts { get; private set; } diff --git a/src/Nethermind/Nethermind.Blockchain.Test/Validators/InclusionListValidatorTests.cs b/src/Nethermind/Nethermind.Blockchain.Test/Validators/InclusionListValidatorTests.cs index 080ad96cbcef..38897f18c499 100644 --- a/src/Nethermind/Nethermind.Blockchain.Test/Validators/InclusionListValidatorTests.cs +++ b/src/Nethermind/Nethermind.Blockchain.Test/Validators/InclusionListValidatorTests.cs @@ -1,7 +1,10 @@ // SPDX-FileCopyrightText: 2026 Demerzel Solutions Limited // SPDX-License-Identifier: LGPL-3.0-only +using System; using System.Collections.Generic; +using System.Linq; +using Nethermind.Consensus.Processing; using Nethermind.Consensus.Validators; using Nethermind.Core; using Nethermind.Core.Crypto; @@ -20,10 +23,11 @@ namespace Nethermind.Blockchain.Test.Validators; public class InclusionListValidatorTests { private static readonly ISpecProvider _specProvider = new CustomSpecProvider(((ForkActivation)0, Bogota.Instance)); - // Bogota carries inclusion lists alone; a chain wanting frame transactions too schedules their - // transition alongside it. That combination is what makes a frame transaction reachable as an entry. - private static readonly ISpecProvider _frameSpecProvider = new CustomSpecProvider( - ((ForkActivation)0, new OverridableReleaseSpec(Bogota.Instance) { IsEip8141Enabled = true })); + // Bogota carries inclusion lists alone; Profile 2 is active once frame transactions, keyed nonces and + // recent roots are scheduled alongside them, as Eip8369Prototype does. + private static readonly ISpecProvider _frameSpecProvider = new CustomSpecProvider(((ForkActivation)0, Eip8369Prototype.Instance)); + // Inclusion lists and frame transactions without EIP-8250 and EIP-8272: Profile 2 is not yet active. + private static readonly IReleaseSpec _preProfile2Spec = new OverridableReleaseSpec(Bogota.Instance) { IsEip8141Enabled = true }; private static readonly TxValidator _txValidator = new(TestBlockchainIds.ChainId); private static readonly Transaction _validTx = BuildTx(); @@ -31,14 +35,12 @@ public static IEnumerable SatisfactionCases { get { - static TestCaseData Case(string name, Transaction[]? il, bool satisfied, Transaction[]? blockTxs = null, ulong gasUsed = 1_000_000, UInt256 baseFee = default, ulong senderNonce = 0) => + static TestCaseData Case(string name, Transaction[] il, bool satisfied, Transaction[]? blockTxs = null, ulong gasUsed = 1_000_000, UInt256 baseFee = default, ulong senderNonce = 0) => new(blockTxs ?? [], il, gasUsed, baseFee, senderNonce, satisfied) { TestName = name }; yield return Case("Full block is satisfied", [_validTx], true, gasUsed: 30_000_000); yield return Case("All IL txs included", [_validTx], true, blockTxs: [_validTx]); yield return Case("Appendable IL tx excluded", [_validTx], false); - // Null IL = non-engine-API path (genesis, RLP import); validator treats as not applicable. - yield return Case("No IL", null, true); yield return Case("Empty IL", [], true); yield return Case("Sender lacks balance", [BuildTx(value: 100.Ether, to: TestItem.AddressB)], true); yield return Case("Wrong nonce", [BuildTx(nonce: 5, to: TestItem.AddressB)], true); @@ -70,8 +72,49 @@ static TestCaseData Case(string name, Transaction[]? il, bool satisfied, Transac } } + /// Before Profile 2 is active an omitted frame transaction is excused, as before this change: committee + /// positions and claims have no effect, and nothing is replayed or signature-checked. + [TestCase(10_000_000_000_000_000_000UL, 0UL, TestName = "Before Profile 2 an omitted frame tx is excused despite a claim")] + [TestCase(1UL, 1UL, TestName = "Before Profile 2 an omitted frame tx is excused whatever its sender's state")] + public void Frame_tx_omission_is_excused_before_profile_2(ulong senderBalance, ulong senderNonce) + { + // Without EIP-8250 a frame transaction still carries the scalar account nonce. + Transaction candidate = Candidate(1, 100_000); + candidate.NonceKeys = null; + Profile2Case profile2 = Profile2Block([candidate], blockTxCount: 3, claims: [new(candidate.Hash!, 1)]); + FakeReplayer replayer = new((_, _) => true); + + bool result = InclusionListValidator.IsSatisfied(profile2.Block, profile2.Lists!, StateWith(TestItem.AddressA, senderBalance, senderNonce), + _preProfile2Spec, _txValidator, Eip8369Constants.MaxVerifyGasPerTx, profile2.Claims, replayer); + + using (Assert.EnterMultipleScope()) + { + Assert.That(Eip8369Profile2.IsActive(_preProfile2Spec), Is.False); + Assert.That(result, Is.True); + Assert.That(replayer.ReplayedAt, Is.Empty); + Assert.That(replayer.SignatureChecks, Is.Zero); + } + } + + /// EIP-7805 excludes blob transactions from the appendability check, so their omission is excused + /// whether or not Profile 2 is active. + [TestCase(false, true, TestName = "Omitted blob tx is excused before Profile 2 is active")] + [TestCase(true, true, TestName = "Omitted blob tx is excused once Profile 2 is active")] + public void Blob_tx_omission_is_excused_once_profile_2_is_active(bool profile2Active, bool satisfied) + { + IReleaseSpec spec = profile2Active ? Eip8369Prototype.Instance : Bogota.Instance; + Block block = Build.A.Block + .WithGasLimit(30_000_000) + .WithGasUsed(1_000_000) + .WithBlobGasUsed(0) + .WithExcessBlobGas(0) + .TestObject; + + Assert.That(IsSatisfied(block, [BuildBlobTx()], StateWith(TestItem.AddressA, 10.Ether, 0), spec), Is.EqualTo(satisfied)); + } + [TestCaseSource(nameof(SatisfactionCases))] - public void Inclusion_list_satisfaction(Transaction[] blockTxs, Transaction[]? il, ulong gasUsed, UInt256 baseFee, ulong senderNonce, bool satisfied) + public void Inclusion_list_satisfaction(Transaction[] blockTxs, Transaction[] il, ulong gasUsed, UInt256 baseFee, ulong senderNonce, bool satisfied) { Block block = Build.A.Block .WithGasLimit(30_000_000) @@ -80,11 +123,10 @@ public void Inclusion_list_satisfaction(Transaction[] blockTxs, Transaction[]? i .WithTransactions(blockTxs) .WithBlobGasUsed(0) .WithExcessBlobGas(0) - .WithInclusionListTransactions(il) .TestObject; IReadOnlyStateProvider state = StateWith(TestItem.AddressA, 10.Ether, senderNonce); - Assert.That(InclusionListValidator.IsSatisfied(block, state, _specProvider.GetSpec(block.Header), _txValidator), Is.EqualTo(satisfied)); + Assert.That(IsSatisfied(block, il, state, _specProvider.GetSpec(block.Header)), Is.EqualTo(satisfied)); } // EIP-8037 admits a transaction per dimension, so an entry that fits the state gas the block actually spent @@ -102,46 +144,529 @@ public bool Appendability_is_judged_per_block_gas_dimension(ulong ilGasLimit, bo .WithGasUsed(513_317) .WithBaseFeePerGas(UInt256.Zero) .WithTransactions([]) - .WithInclusionListTransactions([BuildTx(gasLimit: ilGasLimit, to: TestItem.AddressB)]) .TestObject; if (dimensionsKnown) block.Header.GasUsedPerDimension = (513_317, 97_920); - return InclusionListValidator.IsSatisfied(block, StateWith(TestItem.AddressA, 10.Ether, 0), _specProvider.GetSpec(block.Header), _txValidator); + return IsSatisfied(block, [BuildTx(gasLimit: ilGasLimit, to: TestItem.AddressB)], StateWith(TestItem.AddressA, 10.Ether, 0), _specProvider.GetSpec(block.Header)); } - // Judging a frame transaction by the Profile 1 rules would read the account nonce it does not use. The - // well-formedness assertion keeps the case honest: without it the entry could pass for being malformed. - [Test] - public void Omitted_frame_transaction_is_not_judged() + /// EIP-8369 Profile 2: an omitted frame transaction is judged when it is a candidate and excused + /// when it is not, so both sides of the boundary are pinned rather than only the excuse. + public static IEnumerable FrameCases { - Transaction frameTx = BuildFrameTx(); + get + { + static TestCaseData Case(string name, Transaction[] il, bool satisfied, Transaction[]? blockTxs = null, + UInt256 payerBalance = default, UInt256 senderBalance = default, ulong gasUsed = 1_000_000, + UInt256 baseFee = default, ulong maxVerifyGasPerTx = Eip8369Constants.MaxVerifyGasPerTx, + bool wellFormed = true) => + new(il, blockTxs ?? [], senderBalance.IsZero ? 10.Ether : senderBalance, payerBalance, gasUsed, + baseFee, maxVerifyGasPerTx, wellFormed, satisfied) + { TestName = name }; + + // A Profile 2 candidate the payload could have appended is now an unjustified omission. + yield return Case("Omitted Profile 2 candidate is censoring", [BuildFrameTx()], false); + + Transaction included = BuildFrameTx(); + included.Hash = Keccak.Zero; + yield return Case("Included frame transaction repeated in the IL is satisfied", + [included, included], true, blockTxs: [included]); + Transaction omitted = BuildFrameTx(frames: [SelfVerify(110_000)]); + omitted.Hash = Keccak.EmptyTreeHash; + yield return Case("Included frame duplicates do not excuse a different omitted candidate", + [included, included, omitted], false, blockTxs: [included]); + + // Outside both EIP-8369 profiles: blob gas has its own budget, over which the EIP defines no check. + yield return Case("Omitted blob-carrying frame transaction is excused", [BuildFrameTx(blobCount: 1)], true); + // Condition 2: a prefix matching none of the four admitted shapes. + yield return Case("Omitted frame transaction with an unrecognized prefix is excused", + [BuildFrameTx([Body(50_000)])], true); + // Condition 3: a VERIFY frame behind the validation prefix. + yield return Case("Omitted frame transaction with a VERIFY frame after its prefix is excused", + [BuildFrameTx([SelfVerify(), Body(50_000), Verify(50_000)])], true); + // Condition 4, and the knob that sets it: the same transaction is judged once the cap is lifted. + yield return Case("Omitted frame transaction over the VERIFY budget is excused", + [BuildFrameTx([SelfVerify(2_000_000)])], true); + // Lifting the per-transaction cap cannot admit it: it still overruns MAX_VERIFY_GAS_PER_IL. + yield return Case("Omitted frame transaction over the per-IL VERIFY budget stays excused once the per-transaction cap is lifted", + [BuildFrameTx([SelfVerify(2_000_000)])], true, maxVerifyGasPerTx: 0); + yield return Case("Omitted frame transaction within the per-IL VERIFY budget is judged once the per-transaction cap is lifted", + [BuildFrameTx([SelfVerify(1_000_000)])], false, maxVerifyGasPerTx: 0); + // Condition 1: a candidate shape is not enough, the transaction must also be statically valid. + yield return Case("Omitted malformed frame transaction is excused", + [BuildFrameTx([SelfVerify(value: UInt256.One)])], true, wellFormed: false); + + yield return Case("Omitted sponsored frame transaction is excused", + [BuildFrameTx(SponsoredFrames)], true, payerBalance: 10.Ether); + + // The determinate justifications EIP-8369 leaves to the attester's own reading of the payload. + // 1,105,000 gas remains: the frame limits alone fit, and only the EIP-8141 intrinsic cost on + // top of them — which Transaction.GasLimit leaves out — puts the reservation over. + yield return Case("Omitted frame transaction whose max_gas does not fit the remaining gas is excused", + [BuildFrameTx([SelfVerify(), Body(1_000_000)])], true, gasUsed: 28_895_000); + yield return Case("Omitted frame transaction priced below the base fee is excused", + [BuildFrameTx(maxFeePerGas: 1.GWei)], true, baseFee: 5.GWei); + yield return Case("Omitted frame transaction with a tip above its max fee per gas is censoring", + [BuildFrameTx(maxFeePerGas: UInt256.One)], false); + } + } + + /// An excused entry excuses itself alone. Hoisting the excusal to the whole list would report + /// genuine censoring as satisfied, and no case below a single-entry list can catch that. + [TestCase(false, ExpectedResult = false, TestName = "Ordinary entry behind an excused frame transaction is still judged")] + // Keeps the case above from passing vacuously against a validator that fails any multi-entry list. + [TestCase(true, ExpectedResult = true, TestName = "Ordinary entry behind an excused frame transaction can satisfy the list")] + public bool Frame_transaction_skip_is_per_entry(bool ordinaryEntryIncluded) + { + // A frame transaction whose prefix matches no admitted shape: outside Profile 2, so excused. + Transaction[] il = [BuildFrameTx([Body(50_000)]), _validTx]; Block block = Build.A.Block .WithGasLimit(30_000_000) .WithGasUsed(1_000_000) - .WithTransactions([]) - .WithInclusionListTransactions([frameTx]) + .WithTransactions(ordinaryEntryIncluded ? [_validTx] : []) .TestObject; + + return IsSatisfied(block, il, StateWith(TestItem.AddressA, 10.Ether, 0), _frameSpecProvider.GetSpec(block.Header)); + } + + [TestCaseSource(nameof(FrameCases))] + public void Frame_transaction_omission_follows_eip_8369_profile_2( + Transaction[] il, Transaction[] blockTxs, UInt256 senderBalance, UInt256 payerBalance, + ulong gasUsed, UInt256 baseFee, ulong maxVerifyGasPerTx, bool wellFormed, bool satisfied) + { + Block block = Build.A.Block + .WithGasLimit(30_000_000) + .WithGasUsed(gasUsed) + .WithBaseFeePerGas(baseFee) + .WithTransactions(blockTxs) + .TestObject; + // Admission is by hash and by committee position, so every entry gets a hash and sits at position 0. + for (int i = 0; i < il.Length; i++) il[i].Hash ??= Keccak.Compute($"frame-case-{i}"); IReleaseSpec spec = _frameSpecProvider.GetSpec(block.Header); + IReadOnlyStateProvider state = StateWith((TestItem.AddressA, senderBalance, 0), (TestItem.AddressB, payerBalance, 0)); using (Assert.EnterMultipleScope()) { - Assert.That((bool)_txValidator.IsWellFormed(frameTx, spec, block.GasLimit), Is.True); - Assert.That(InclusionListValidator.IsSatisfied(block, StateWith(TestItem.AddressA, 10.Ether, 0), spec, _txValidator), Is.True); + // Keeps every case honest: an entry could otherwise be excused for being malformed instead. + foreach (Transaction tx in il) + if (tx.SupportsFrames) + Assert.That((bool)_txValidator.IsWellFormed(tx, spec, block.GasLimit), Is.EqualTo(wellFormed)); + + Assert.That(InclusionListValidator.IsSatisfied(block, AtPositions(il), state, spec, _txValidator, maxVerifyGasPerTx, claims: null), Is.EqualTo(satisfied)); } } - private static Transaction BuildFrameTx() => new() + [TestCase(0UL, ExpectedResult = false)] + [TestCase(1UL, ExpectedResult = true)] + public bool Profile_2_appendability_uses_the_exact_state_reservation(ulong excess) { - Type = TxType.FrameTx, - ChainId = TestBlockchainIds.ChainId, - SenderAddress = TestItem.AddressA, - Nonce = 0, - Frames = [new TxFrame(FrameMode.Verify, FrameFlags.ApproveExecutionAndPayment, target: null, gasLimit: 100_000, UInt256.Zero, default)], - FrameSignatures = [], - GasLimit = 100_000, - GasPrice = 1.GWei, - DecodedMaxFeePerGas = 10.GWei, - }; + Transaction candidate = WithHash(BuildFrameTx([ + SelfVerify(), + new(FrameMode.Default, FrameFlags.None, TestItem.AddressC, 50_000, 200_000, UInt256.Zero, default), + ]), "state-reservation"); + Profile2Case profile2 = Profile2Block([candidate], blockTxCount: 0); + Block block = profile2.Block; + IReleaseSpec spec = _frameSpecProvider.GetSpec(block.Header); + Assert.That(FrameTxValidation.TryCalculateBlockGasReservations(candidate, spec, out _, out ulong stateReservation), Is.True); + ulong stateUsed = block.GasLimit - stateReservation + excess; + block.Header.GasUsed = stateUsed; + block.Header.GasUsedPerDimension = (28_000_000, stateUsed); + Assert.That((bool)_txValidator.IsWellFormed(candidate, spec, block.GasLimit), Is.True); + + return IsSatisfied(profile2, new FakeReplayer((_, _) => true)); + } + + [Test] + public void A_full_state_dimension_does_not_excuse_a_candidate_reserving_no_state_gas() + { + Transaction candidate = Candidate(1, 100_000); + Profile2Case profile2 = Profile2Block([candidate], blockTxCount: 0); + Block block = profile2.Block; + IReleaseSpec spec = _frameSpecProvider.GetSpec(block.Header); + Assert.That(FrameTxValidation.TryCalculateBlockGasReservations(candidate, spec, out _, out ulong stateReservation), Is.True); + block.Header.GasUsed = block.GasLimit; + block.Header.GasUsedPerDimension = (1_000_000, block.GasLimit); + + using (Assert.EnterMultipleScope()) + { + Assert.That(stateReservation, Is.Zero); + Assert.That(IsSatisfied(profile2, new FakeReplayer((_, _) => true)), Is.False); + } + } + + [TestCase(null, false, null, TestName = "An undecided replay with no candidate proved unjustified leaves the verdict undecided")] + [TestCase(null, null, null, TestName = "Only undecided replays leave the verdict undecided")] + [TestCase(null, true, false, TestName = "A candidate proved unjustified condemns the block whatever else is undecided")] + [TestCase(false, false, true, TestName = "Candidates proved ineligible excuse the omissions")] + public void An_undecided_replay_is_not_taken_as_eligibility(bool? first, bool? second, bool? expected) + { + Transaction[] candidates = [Candidate(1, 100_000), Candidate(2, 100_000)]; + Profile2Case profile2 = Profile2Block(candidates, blockTxCount: 0); + FakeReplayer replayer = new((tx, _) => ReferenceEquals(tx, candidates[0]) ? first : second); + Block block = profile2.Block; + IReleaseSpec spec = _frameSpecProvider.GetSpec(block.Header); + + bool? verdict = InclusionListValidator.Evaluate(block, profile2.Lists, StateWith(TestItem.AddressA, 10.Ether, 0), spec, + _txValidator, Eip8369Constants.MaxVerifyGasPerTx, profile2.Claims, replayer); + + using (Assert.EnterMultipleScope()) + { + Assert.That(verdict, Is.EqualTo(expected)); + Assert.That(IsSatisfied(profile2, replayer), Is.EqualTo(expected is true)); + } + } + + private static readonly Transaction _candidate = Candidate(1, 100_000); + + /// EIP-7805 § Evaluation index: the one index an omitted Profile 2 candidate is replayed at, and how a + /// claim moves it. Each case names the indices the candidate is eligible at and the replays the verdict is + /// expected to take, so a resolution rule that picks the wrong index fails on the call. + public static IEnumerable ClaimCases + { + get + { + const int end = 3; + static TestCaseData Case(string name, OmissionClaim[]? claims, int[] eligibleAt, bool satisfied, int[] replayedAt) => + new(claims, eligibleAt, satisfied, replayedAt) { TestName = name }; + Hash256 hash = _candidate.Hash!; + + yield return Case("Unclaimed candidate eligible at the end is censoring", null, [end], false, [end]); + yield return Case("Unclaimed candidate ineligible at the end is excused by replay", null, [], true, [end]); + yield return Case("Claim excuses a candidate ineligible where the builder tried", + [new(hash, 1)], [end], true, [1]); + yield return Case("Claim at index zero is before every block transaction", + [new(hash, 0)], [end], true, [0]); + yield return Case("Claim leaves enforced a candidate eligible where the builder tried", + [new(hash, 1)], [1, end], false, [1]); + yield return Case("Claim condemns a candidate eligible where claimed though ineligible at the end", + [new(hash, 1)], [1], false, [1]); + yield return Case("Out-of-range claim resolves to the end of the payload", + [new(hash, 99)], [end], false, [end]); + yield return Case("Claim at the end is the default index", [new(hash, end)], [end], false, [end]); + yield return Case("Duplicate claims for one hash are all ignored", + [new(hash, 1), new(hash, 2)], [end], false, [end]); + yield return Case("A hash claimed three times stays ignored", + [new(hash, 1), new(hash, 1), new(hash, 2)], [end], false, [end]); + yield return Case("Each hash resolves its own claim among several", + [new(Keccak.Compute("elsewhere"), 2), new(hash, 1)], [end], true, [1]); + yield return Case("Claim for a hash outside the list is ignored", + [new(Keccak.Compute("elsewhere"), 1)], [end], false, [end]); + } + } + + [TestCaseSource(nameof(ClaimCases))] + public void Profile_2_omission_is_judged_at_the_resolved_evaluation_index( + OmissionClaim[]? claims, int[] eligibleAt, bool satisfied, int[] replayedAt) + { + Profile2Case block = Profile2Block([_candidate], blockTxCount: 3, claims: claims); + FakeReplayer replayer = new((_, index) => System.Array.IndexOf(eligibleAt, index) >= 0); + + using (Assert.EnterMultipleScope()) + { + Assert.That(IsSatisfied(block, replayer), Is.EqualTo(satisfied)); + Assert.That(replayer.ReplayedAt, Is.EqualTo(replayedAt)); + Assert.That(replayer.Batches, Is.EqualTo(1)); + } + } + + /// A claim is looked up only for an omitted candidate, so it cannot touch anything else. + [TestCase(true, TestName = "Claim for an included candidate is ignored")] + [TestCase(false, TestName = "Claim for a non-candidate is ignored")] + public void Claim_is_ignored_outside_an_omitted_candidate(bool included) + { + Transaction entry = included ? _candidate : WithHash(BuildFrameTx([Body(50_000)]), "non-candidate"); + Profile2Case block = Profile2Block([entry], blockTxCount: 3, claims: [new(entry.Hash!, 1)], included: included ? [entry] : []); + FakeReplayer replayer = new((_, _) => true); + + using (Assert.EnterMultipleScope()) + { + Assert.That(IsSatisfied(block, replayer), Is.True); + Assert.That(replayer.ReplayedAt, Is.Empty); + } + } + + /// EIP-7805 § VERIFY budget: the budget filled per committee position, in ascending hash order. + /// Only the named candidate is eligible, so whether its omission is excused is the fill's verdict alone. A + /// candidate's order argument is the leading byte of its hash, which fixes where the fill takes it. + public static IEnumerable BudgetCases + { + get + { + static TestCaseData Case(string name, Transaction[][] lists, Transaction candidate, bool satisfied, Transaction? badSignature = null) => + new(lists, candidate, badSignature, satisfied) { TestName = name }; + + // 1-of-N: pooled into one budget, the stuffed position's 1,040,000 would leave the honest one 8,576. + Transaction honest = Candidate(5, 100_000); + yield return Case("One position stuffed with VERIFY cost cannot excuse another position's candidate", + [[Candidate(1, 260_000), Candidate(2, 260_000), Candidate(3, 260_000), Candidate(4, 260_000)], [honest]], honest, false); + + // Of 1,048,576: the four fillers debit 800,000 and leave 248,576, which the second's cost exceeds. + Transaction[] filler = [Candidate(1, 200_000), Candidate(2, 200_000), Candidate(3, 200_000), Candidate(4, 200_000)]; + Transaction first = filler[0]; + Transaction second = Candidate(5, 250_000); + yield return Case("Candidate over its own position's remaining budget is excused", [[.. filler, second]], second, true); + yield return Case("A duplicate in one list is debited once", [[.. filler[..3], first, second]], second, false); + yield return Case("The fill takes a position's entries by hash, not by arrival", [[second, .. filler]], second, true); + yield return Case("Candidate carried at several positions is enforced when any admits it", + [[.. filler, second], [second]], second, false); + Transaction[] otherFiller = [Candidate(1, 210_000), Candidate(2, 210_000), Candidate(3, 210_000), Candidate(4, 210_000)]; + yield return Case("Candidate carried at several positions is excused when none admits it", + [[.. filler, second], [.. otherFiller, second]], second, true); + + // The fillers leave 248,576, which the overflow's 250,000 exceeds; ignored without a debit, it leaves + // room for the last. + Transaction last = Candidate(6, 200_000); + yield return Case("Occurrence over the remaining budget is ignored without a debit", + [[.. filler, Candidate(5, 250_000), last]], last, false); + + // Three fillers leave 448,576; the signed candidate's whole 252,800 then leaves too little for the + // last, its 2,800 signature cost alone does not. + Transaction[] signedFiller = filler[..3]; + Transaction signed = Candidate(4, 250_000, signatures: 1); + Transaction afterSigned = Candidate(5, 250_000); + // EIP-7805 step 1: entries failing the noncryptographic candidate conditions are skipped without a debit, + // so four of them at 260,000 leave the whole budget to the honest candidate. A wrong chain ID is a replay + // check, not one of those conditions, so it debits as a candidate does. + yield return Case("Entries outside Profile 2 do not debit the budget", + [[.. Enumerable.Range(1, 4).Select(i => Ordered(BuildFrameTx([Verify(260_000)]), (byte)i)), honest]], honest, false); + yield return Case("Statically invalid entries do not debit the budget", + [[.. Enumerable.Range(1, 4).Select(i => Ordered(BuildFrameTx([SelfVerify(260_000, UInt256.One)]), (byte)i)), honest]], honest, false); + yield return Case("Entries with another chain ID debit the budget", + [[.. Enumerable.Range(1, 4).Select(i => Ordered(WithChainId(Candidate((byte)i, 260_000), 999), (byte)i)), honest]], honest, true); + yield return Case("Invalid signatures keep only the signature debit", [[.. signedFiller, signed, afterSigned]], afterSigned, false, badSignature: signed); + yield return Case("Valid signatures debit the whole cost", [[.. signedFiller, signed, afterSigned]], afterSigned, true); + } + } + + [TestCaseSource(nameof(BudgetCases))] + public void Profile_2_verify_budget_is_filled_per_committee_position( + Transaction[][] lists, Transaction candidate, Transaction? badSignature, bool satisfied) + { + Profile2Case block = Profile2Block(lists, blockTxCount: 0); + FakeReplayer replayer = new((tx, _) => ReferenceEquals(tx, candidate), tx => !ReferenceEquals(tx, badSignature)); + + Assert.That(IsSatisfied(block, replayer), Is.EqualTo(satisfied)); + } + + /// EIP-7805 § Separate inclusion lists: a validator at several positions has the same list at each, and + /// each identical fill has its own budget without multiplying anyone's. + [Test] + public void Identical_lists_at_several_positions_fill_independently() + { + Transaction[] filler = [Candidate(1, 200_000), Candidate(2, 200_000), Candidate(3, 200_000), Candidate(4, 200_000)]; + Transaction over = Candidate(5, 250_000); + Transaction[] list = [.. filler, over]; + + using (Assert.EnterMultipleScope()) + { + // Over its list's remaining budget at every position, so repeating the list admits it nowhere. + Assert.That(IsSatisfied(Profile2Block([list, list, list], blockTxCount: 0), new FakeReplayer((tx, _) => ReferenceEquals(tx, over))), Is.True); + // Within budget at one position of its own, so the stuffed copies elsewhere cannot excuse it. + Assert.That(IsSatisfied(Profile2Block([list, list, [over]], blockTxCount: 0), new FakeReplayer((tx, _) => ReferenceEquals(tx, over))), Is.False); + } + } + + /// An entry carried at every committee position is verified once, not once per position. + [Test] + public void Signatures_are_verified_once_per_entry_across_positions() + { + Transaction signed = Candidate(1, 100_000, signatures: 1); + Transaction[][] lists = [.. Enumerable.Repeat(new[] { signed, Candidate(2, 100_000) }, Eip7805Constants.InclusionListCommitteeSize)]; + FakeReplayer replayer = new((_, _) => false); + + IsSatisfied(Profile2Block(lists, blockTxCount: 0), replayer); + + // Both entries sit at all 16 positions: 2 verifications, not 32. + Assert.That(replayer.SignatureChecks, Is.EqualTo(2)); + } + + /// Every omitted candidate of a block, at every index it is judged at, reaches the replayer in one + /// batch, so the block's state is reconstructed once however many candidates and claimed indices there are. + [Test] + public void Candidates_are_replayed_in_one_batch() + { + Transaction[] candidates = [Candidate(1, 100_000), Candidate(2, 100_000), Candidate(3, 100_000)]; + Profile2Case block = Profile2Block(candidates, blockTxCount: 3, + claims: [new(candidates[0].Hash!, 0), new(candidates[1].Hash!, 2)]); + FakeReplayer replayer = new((_, _) => false); + + using (Assert.EnterMultipleScope()) + { + Assert.That(IsSatisfied(block, replayer), Is.True); + Assert.That(replayer.Batches, Is.EqualTo(1)); + Assert.That(replayer.ReplayedAt, Is.EquivalentTo(new[] { 0, 2, 3 })); + } + } + + /// EIP-7805: a claimed candidate must fit the gas the block used before its claim, not after the + /// whole payload. The block is full at the end, so only the gas before the claim lets it fit. + [TestCase(true, false, TestName = "Claim before a full block's transactions is judged on the gas used before it")] + [TestCase(false, true, TestName = "Without per-transaction gas a claim is judged on the whole block's gas")] + public void Claimed_candidate_fits_the_gas_used_before_its_index(bool withGasUsedBefore, bool satisfied) + { + Profile2Case profile2 = Profile2Block([_candidate], blockTxCount: 3, claims: [new(_candidate.Hash!, 1)]); + Block block = profile2.Block; + block.Header.GasUsed = block.GasLimit; + block.Header.GasUsedPerDimension = (block.GasLimit, block.GasLimit); + (ulong, ulong)[] gasUsedBefore = [(0, 0), (21_000, 0), (block.GasLimit - 21_000, 0)]; + FakeReplayer replayer = new((_, index) => index == 1); + + bool result = IsSatisfied(profile2, replayer, withGasUsedBefore ? gasUsedBefore : null); + + Assert.That(result, Is.EqualTo(satisfied)); + } + + /// The gas used before each transaction is read off the receipts only when they add up to the block's totals. + [TestCase(30_000UL, 5_000UL, true, TestName = "Receipts adding up to the block's gas give the gas before each transaction")] + [TestCase(30_001UL, 5_000UL, false, TestName = "Receipts not adding up to the block's gas give nothing")] + public void Gas_used_before_each_transaction_comes_from_consistent_receipts(ulong totalExecution, ulong totalState, bool consistent) + { + Block block = Profile2Block(Array.Empty(), blockTxCount: 2).Block; + block.Header.GasUsedPerDimension = (totalExecution, totalState); + TxReceipt[] receipts = [new() { BlockGasUsed = 21_000, StorageGasUsed = 5_000 }, new() { BlockGasUsed = 9_000 }]; + + (ulong Execution, ulong State)[]? before = InclusionListValidator.GasUsedBeforeEachTransaction(block, receipts); + + Assert.That(before, consistent ? Is.EqualTo(new (ulong, ulong)[] { (0, 0), (21_000, 5_000) }) : Is.Null); + } + + /// Pads with empty lists to one per committee position. + private static Transaction[][] AtPositions(params Transaction[][] lists) + { + Transaction[][] positions = new Transaction[Eip7805Constants.InclusionListCommitteeSize][]; + for (int position = 0; position < positions.Length; position++) positions[position] = position < lists.Length ? lists[position] : []; + return positions; + } + + private sealed class FakeReplayer(Func eligible, Func? signaturesValid = null) + : IProfile2EligibilityReplayer + { + public List ReplayedAt { get; } = []; + + public int Batches { get; private set; } + + public int SignatureChecks { get; private set; } + + public bool AreSignaturesValid(Transaction transaction, IReleaseSpec spec) + { + SignatureChecks++; + return signaturesValid?.Invoke(transaction) ?? true; + } + + public bool?[] AreEligible(Block block, IReadOnlyList<(Transaction Transaction, int Index)> requests, IReleaseSpec spec) + { + Batches++; + bool?[] verdicts = new bool?[requests.Count]; + for (int i = 0; i < requests.Count; i++) + { + ReplayedAt.Add(requests[i].Index); + verdicts[i] = eligible(requests[i].Transaction, requests[i].Index); + } + return verdicts; + } + } + + /// A block with the separate lists and claims it is checked against. + private sealed record Profile2Case(Block Block, Transaction[][] Lists, OmissionClaim[]? Claims); + + private static bool IsSatisfied(Profile2Case profile2, IProfile2EligibilityReplayer replayer, (ulong, ulong)[]? gasUsedBefore = null) => + InclusionListValidator.IsSatisfied(profile2.Block, profile2.Lists, StateWith(TestItem.AddressA, 10.Ether, 0), _frameSpecProvider.GetSpec(profile2.Block.Header), + _txValidator, Eip8369Constants.MaxVerifyGasPerTx, profile2.Claims, replayer, gasUsedBefore); + + /// Whether honours , the list at committee position 0. + private static bool IsSatisfied(Block block, Transaction[] il, IReadOnlyStateProvider state, IReleaseSpec spec) => + InclusionListValidator.IsSatisfied(block, AtPositions(il), state, spec, _txValidator, Eip8369Constants.MaxVerifyGasPerTx, claims: null); + + /// A block omitting , which sits at committee position 0. + private static Profile2Case Profile2Block(Transaction[] il, int blockTxCount, OmissionClaim[]? claims = null, Transaction[]? included = null) => + Profile2Block([il], blockTxCount, claims, included); + + /// A block omitting , one per committee position from position 0. + private static Profile2Case Profile2Block(Transaction[][] lists, int blockTxCount, OmissionClaim[]? claims = null, Transaction[]? included = null) + { + List blockTxs = [.. included ?? []]; + for (int i = blockTxs.Count; i < blockTxCount; i++) + blockTxs.Add(BuildTx(nonce: (ulong)i + 10, to: TestItem.AddressB)); + + Transaction[][] positions = AtPositions(lists); + Block block = Build.A.Block + .WithGasLimit(30_000_000) + .WithGasUsed(1_000_000) + .WithTransactions([.. blockTxs]) + .TestObject; + return new Profile2Case(block, positions, claims); + } + + /// The hash's leading byte, which places the candidate in a position's fill order. + private static Transaction Candidate(byte order, ulong verifyGas, int signatures = 0) + { + Transaction tx = WithHash(BuildFrameTx([SelfVerify(verifyGas)]), $"candidate-{order}-{verifyGas}-{signatures}"); + byte[] hash = tx.Hash!.BytesToArray(); + hash[0] = order; + tx.Hash = new Hash256(hash); + tx.FrameSignatures = new TxFrameSignature[signatures]; + for (int i = 0; i < signatures; i++) + tx.FrameSignatures[i] = new TxFrameSignature(TxFrameSignature.SchemeSecp256k1, TestItem.AddressA, ReadOnlyMemory.Empty, new byte[65]); + return tx; + } + + /// Gives a hash whose leading byte is . + private static Transaction Ordered(Transaction tx, byte order) + { + byte[] hash = Keccak.Compute($"ordered-{order}-{tx.Frames![0].ExecutionGasLimit}-{tx.Frames[0].Mode}-{tx.Frames[0].Value}").BytesToArray(); + hash[0] = order; + tx.Hash = new Hash256(hash); + return tx; + } + + private static Transaction WithChainId(Transaction tx, ulong chainId) + { + tx.ChainId = chainId; + return tx; + } + + private static Transaction WithHash(Transaction tx, string id) + { + tx.Hash = Keccak.Compute(id); + return tx; + } + + // A self-relay prefix: the sender approves its own execution and payment, so it pays for itself. + private static TxFrame SelfVerify(ulong gasLimit = 100_000, UInt256 value = default) => + new(FrameMode.Verify, FrameFlags.ApproveExecutionAndPayment, target: null, gasLimit, value, default); + + private static TxFrame Body(ulong gasLimit) => + new(FrameMode.Default, FrameFlags.None, TestItem.AddressC, gasLimit, UInt256.Zero, default); + + private static TxFrame Verify(ulong gasLimit) => + new(FrameMode.Verify, FrameFlags.None, TestItem.AddressC, gasLimit, UInt256.Zero, default); + + // An `only_verify | pay` prefix nominating AddressB as the payer. + private static TxFrame[] SponsoredFrames => + [ + new(FrameMode.Verify, FrameFlags.ApproveExecution, target: null, 100_000, UInt256.Zero, default), + new(FrameMode.Verify, FrameFlags.ApprovePayment, TestItem.AddressB, 100_000, UInt256.Zero, default), + ]; + + private static Transaction BuildFrameTx(TxFrame[]? frames = null, int blobCount = 0, UInt256? maxFeePerGas = null) + { + frames ??= [SelfVerify()]; + return new Transaction + { + Type = TxType.FrameTx, + ChainId = TestBlockchainIds.ChainId, + SenderAddress = TestItem.AddressA, + Nonce = 0, + NonceKeys = [], + Frames = frames, + FrameSignatures = [], + GasLimit = FrameTxValidation.TotalGasLimit(frames), + GasPrice = 1.GWei, + DecodedMaxFeePerGas = maxFeePerGas ?? 10.GWei, + MaxFeePerBlobGas = blobCount == 0 ? null : 1.GWei, + BlobVersionedHashes = blobCount == 0 ? null : Build.A.Transaction.WithBlobVersionedHashes(blobCount).TestObject.BlobVersionedHashes, + }; + } [Test] public void When_il_disabled_by_spec_then_accept_even_if_excluded() @@ -149,10 +674,9 @@ public void When_il_disabled_by_spec_then_accept_even_if_excluded() Block block = Build.A.Block .WithGasLimit(30_000_000) .WithGasUsed(1_000_000) - .WithInclusionListTransactions([_validTx]) .TestObject; - Assert.That(InclusionListValidator.IsSatisfied(block, StateWith(TestItem.AddressA, 10.Ether, 0), Prague.Instance, _txValidator), Is.True); + Assert.That(IsSatisfied(block, [_validTx], StateWith(TestItem.AddressA, 10.Ether, 0), Prague.Instance), Is.True); } // EIP-3607: a sender that has deployed (non-delegation) code cannot send a tx. @@ -174,10 +698,9 @@ public bool Sender_with_code_appendability_depends_on_delegation(bool isDelegate Block block = Build.A.Block .WithGasLimit(30_000_000) .WithGasUsed(1_000_000) - .WithInclusionListTransactions([_validTx]) .TestObject; - return InclusionListValidator.IsSatisfied(block, state, _specProvider.GetSpec(block.Header), _txValidator); + return IsSatisfied(block, [_validTx], state, _specProvider.GetSpec(block.Header)); } private static Transaction BuildTx(ulong gasLimit = 100_000, ulong nonce = 0, UInt256? gasPrice = null, UInt256? value = null, Address? to = null) => @@ -230,6 +753,21 @@ private static Transaction BuildBlobTx(UInt256? maxFeePerBlobGas = null) => .SignedAndResolved(TestItem.PrivateKeyA) .TestObject; + private static IReadOnlyStateProvider StateWith(params (Address Address, UInt256 Balance, ulong Nonce)[] accounts) + { + IReadOnlyStateProvider state = Substitute.For(); + foreach ((Address address, UInt256 balance, ulong nonce) in accounts) + { + state.TryGetAccount(address, out Arg.Any()).Returns(call => + { + call[1] = new AccountStruct(nonce, balance); + return true; + }); + } + + return state; + } + private static IReadOnlyStateProvider StateWith(Address sender, UInt256 balance, ulong nonce) { IReadOnlyStateProvider state = Substitute.For(); diff --git a/src/Nethermind/Nethermind.Config/BlocksConfig.cs b/src/Nethermind/Nethermind.Config/BlocksConfig.cs index 2743b00ad5cf..9183583c63d0 100644 --- a/src/Nethermind/Nethermind.Config/BlocksConfig.cs +++ b/src/Nethermind/Nethermind.Config/BlocksConfig.cs @@ -131,5 +131,7 @@ public string ExtraData public long SlowBlockPerTxThresholdMs { get; set; } = -1; public ulong MaxGasLimit { get; set; } = 1_000_000_000; + + public ulong FocilProfile2MaxVerifyGas { get; set; } = Eip8369Constants.MaxVerifyGasPerTx; } } diff --git a/src/Nethermind/Nethermind.Config/IBlocksConfig.cs b/src/Nethermind/Nethermind.Config/IBlocksConfig.cs index a58bd7312c77..cc875cdc563f 100644 --- a/src/Nethermind/Nethermind.Config/IBlocksConfig.cs +++ b/src/Nethermind/Nethermind.Config/IBlocksConfig.cs @@ -148,4 +148,11 @@ public interface IBlocksConfig : IConfig DefaultValue = "1000000000", HiddenFromDocs = true)] ulong MaxGasLimit { get; set; } + + [ConfigItem( + Description = "The max VERIFY budget cost, in gas, of an EIP-8141 frame transaction this node lists when " + + "building an inclusion list. It does not affect block validity: newPayload judges inclusion " + + "lists under the fork's `MAX_VERIFY_GAS_PER_TX`. `0` to lift the limit.", + DefaultValue = "262144")] + ulong FocilProfile2MaxVerifyGas { get; set; } } diff --git a/src/Nethermind/Nethermind.Consensus.Test/BlockCachePreWarmerTests.cs b/src/Nethermind/Nethermind.Consensus.Test/BlockCachePreWarmerTests.cs index 81a3d685cc74..14febe51c0dd 100644 --- a/src/Nethermind/Nethermind.Consensus.Test/BlockCachePreWarmerTests.cs +++ b/src/Nethermind/Nethermind.Consensus.Test/BlockCachePreWarmerTests.cs @@ -353,20 +353,6 @@ public void SortUnique_KeepsEachAccountOnce([Values(0, 1, 5)] int repeats) Assert.That(unique.ToArray(), Is.EqualTo(expected)); } - /// Inclusion-list transactions are scanned after the block's own, as the sender and recipient pass covers them. - [Test] - public void CollectCalldataAddresses_ScansInclusionListTransactionsAfterTheBlocks() - { - Block block = BuildCalldataAddressBlock(out Address first, out Address second, out _); - Address third = new("0x5a52e96bacdabb82fd05763e25335261b270efcb"); - byte[] data = new byte[4 + BlockCachePreWarmer.MinCalldataWordsForAddressWarm * 32]; - third.Bytes.CopyTo(data.AsSpan(4 + 12)); - block.InclusionListTransactions = [Build.A.Transaction.WithData(data).WithTo(TestItem.AddressE).SignedAndResolved(TestItem.PrivateKeyD).TestObject]; - - using ArrayPoolList
? collected = BlockCachePreWarmer.CollectCalldataAddresses(block); - Assert.That(collected, Is.EqualTo(new[] { first, second, third })); - } - [Test] public void CollectCalldataAddresses_Cancelled_ScansNothing() { diff --git a/src/Nethermind/Nethermind.Consensus.Test/InclusionListBlockProducerTxSourceFactoryTests.cs b/src/Nethermind/Nethermind.Consensus.Test/InclusionListBlockProducerTxSourceFactoryTests.cs index 677c0e45b01a..7bfc43911aea 100644 --- a/src/Nethermind/Nethermind.Consensus.Test/InclusionListBlockProducerTxSourceFactoryTests.cs +++ b/src/Nethermind/Nethermind.Consensus.Test/InclusionListBlockProducerTxSourceFactoryTests.cs @@ -46,10 +46,10 @@ public void IL_transactions_precede_mempool_transactions_in_pipeline() new CustomSpecProvider(((ForkActivation)0, Bogota.Instance)), new TxValidator(MainnetSpecProvider.Instance.ChainId), LimboLogs.Instance); - byte[][] ilBytes = [TxDecoder.Instance.Encode(ilTx, RlpBehaviors.SkipTypedWrapping)]; + byte[][][] ilBytes = [[TxDecoder.Instance.Encode(ilTx, RlpBehaviors.SkipTypedWrapping)], .. Enumerable.Repeat([], Eip7805Constants.InclusionListCommitteeSize - 1)]; il.Set(ilBytes, Bogota.Instance); // IL is keyed by the build's PayloadAttributes array. - PayloadAttributes payloadAttributes = new() { InclusionListTransactions = ilBytes }; + PayloadAttributes payloadAttributes = new() { InclusionLists = ilBytes }; ITxSource txSource = new InclusionListBlockProducerTxSourceFactory(baseFactory, il).Create(); diff --git a/src/Nethermind/Nethermind.Consensus.Test/InclusionListTxSourceTests.cs b/src/Nethermind/Nethermind.Consensus.Test/InclusionListTxSourceTests.cs index 70a90cf4ffe9..e940572541c6 100644 --- a/src/Nethermind/Nethermind.Consensus.Test/InclusionListTxSourceTests.cs +++ b/src/Nethermind/Nethermind.Consensus.Test/InclusionListTxSourceTests.cs @@ -3,6 +3,7 @@ using System.Collections.Generic; using System.Linq; +using Nethermind.Config; using Nethermind.Consensus.Producers; using Nethermind.Consensus.Transactions; using Nethermind.Consensus.Validators; @@ -34,7 +35,11 @@ public class InclusionListTxSourceTests txValidator, LimboLogs.Instance); - private static PayloadAttributes Attributes(byte[][] inclusionList) => new() { InclusionListTransactions = inclusionList }; + private static PayloadAttributes Attributes(byte[][][] inclusionLists) => new() { InclusionLists = inclusionLists }; + + /// One list per committee position, at position 0 and the rest empty. + private static byte[][][] AtPosition0(byte[][] inclusionList) => + [inclusionList, .. Enumerable.Repeat([], Eip7805Constants.InclusionListCommitteeSize - 1)]; private static IEnumerable GetTransactions( InclusionListTxSource source, @@ -58,7 +63,7 @@ public void Empty_until_Set_is_called_for_the_build() { InclusionListTxSource source = CreateSource(); Transaction tx = Build.A.Transaction.WithNonce(1).SignedAndResolved(TestItem.PrivateKeyA).TestObject; - byte[][] il = [Encode(tx)]; + byte[][][] il = AtPosition0([Encode(tx)]); PayloadAttributes attrs = Attributes(il); Assert.That(GetTransactions(source, attrs), Is.Empty); @@ -76,8 +81,8 @@ public void Inclusion_list_is_scoped_per_build() InclusionListTxSource source = CreateSource(); Transaction txA = Build.A.Transaction.WithNonce(1).SignedAndResolved(TestItem.PrivateKeyA).TestObject; Transaction txB = Build.A.Transaction.WithNonce(2).SignedAndResolved(TestItem.PrivateKeyB).TestObject; - byte[][] ilA = [Encode(txA)]; - byte[][] ilB = [Encode(txB)]; + byte[][][] ilA = AtPosition0([Encode(txA)]); + byte[][][] ilB = AtPosition0([Encode(txB)]); PayloadAttributes attrsA = Attributes(ilA); PayloadAttributes attrsB = Attributes(ilB); @@ -96,7 +101,7 @@ public void Inclusion_list_is_scoped_per_build() public void Set_with_empty_array_yields_empty() { InclusionListTxSource source = CreateSource(); - byte[][] il = []; + byte[][][] il = AtPosition0([]); PayloadAttributes attrs = Attributes(il); source.Set(il, Bogota.Instance); @@ -112,7 +117,7 @@ public void Set_defers_sender_recovery_to_the_first_request() InclusionListTxSource source = new(ecdsa, new CustomSpecProvider(((ForkActivation)0, Bogota.Instance)), new TxValidator(MainnetSpecProvider.Instance.ChainId), LimboLogs.Instance); // A fresh signer, so the process-wide sender cache cannot answer before the counting ecdsa. Transaction tx = Build.A.Transaction.WithNonce(1).SignedAndResolved(Build.A.PrivateKey.TestObject).TestObject; - byte[][] il = [Encode(tx)]; + byte[][][] il = AtPosition0([Encode(tx)]); source.Set(il, Bogota.Instance); using (Assert.EnterMultipleScope()) @@ -124,6 +129,24 @@ public void Set_defers_sender_recovery_to_the_first_request() Assert.That(ecdsa.Recoveries, Is.EqualTo(1)); } + // A validator at several committee positions has the same list at each: production takes each entry once, and + // its sender is recovered once however many positions carry it. + [Test] + public void Entries_repeated_across_positions_are_produced_and_recovered_once() + { + CountingEcdsa ecdsa = new(new EthereumEcdsa(MainnetSpecProvider.Instance.ChainId)); + InclusionListTxSource source = new(ecdsa, new CustomSpecProvider(((ForkActivation)0, Bogota.Instance)), new TxValidator(MainnetSpecProvider.Instance.ChainId), LimboLogs.Instance); + Transaction tx = Build.A.Transaction.WithNonce(1).SignedAndResolved(Build.A.PrivateKey.TestObject).TestObject; + byte[][][] il = [.. Enumerable.Repeat([Encode(tx), Encode(tx)], Eip7805Constants.InclusionListCommitteeSize)]; + + source.Set(il, Bogota.Instance); + using (Assert.EnterMultipleScope()) + { + Assert.That(GetTransactions(source, Attributes(il)).Select(t => t.Nonce), Is.EqualTo([1ul])); + Assert.That(ecdsa.Recoveries, Is.EqualTo(1)); + } + } + // Per spec, blob (EIP-4844) transactions are excluded from the inclusion list. [Test] public void SupportsBlobs_is_false() => Assert.That(CreateSource().SupportsBlobs, Is.False); @@ -147,7 +170,7 @@ public void Blob_transactions_are_filtered_out() .WithTo(TestItem.AddressB) .SignedAndResolved(TestItem.PrivateKeyB) .TestObject; - byte[][] il = [Encode(normal), Encode(blob)]; + byte[][][] il = AtPosition0([Encode(normal), Encode(blob)]); PayloadAttributes attrs = Attributes(il); source.Set(il, Bogota.Instance); @@ -173,7 +196,7 @@ public void Ill_formed_transactions_are_filtered_out([Values] IllFormedChange ch .WithTo(TestItem.AddressB) .SignedAndResolved(TestItem.PrivateKeyB) .TestObject; - byte[][] il = [Encode(normal), Encode(illFormed)]; + byte[][][] il = AtPosition0([Encode(normal), Encode(illFormed)]); PayloadAttributes attrs = Attributes(il); source.Set(il, Bogota.Instance); @@ -188,13 +211,11 @@ public void Ill_formed_transactions_are_filtered_out([Values] IllFormedChange ch [Test] public void Blob_carrying_frame_transactions_are_filtered_out() { - ITxValidator acceptAll = Substitute.For(); - acceptAll.IsWellFormed(Arg.Any(), Arg.Any()).Returns(ValidationResult.Success); - InclusionListTxSource source = CreateSource(acceptAll); + InclusionListTxSource source = CreateSource(AcceptAll()); Transaction normal = Build.A.Transaction.WithNonce(1).SignedAndResolved(TestItem.PrivateKeyA).TestObject; Transaction blobFrameTx = FrameTx(nonce: 2, blobVersionedHashes: [new byte[32]]); Transaction plainFrameTx = FrameTx(nonce: 3, blobVersionedHashes: null!); - byte[][] il = [Encode(normal), Encode(blobFrameTx), Encode(plainFrameTx)]; + byte[][][] il = AtPosition0([Encode(normal), Encode(blobFrameTx), Encode(plainFrameTx)]); PayloadAttributes attrs = Attributes(il); source.Set(il, Bogota.Instance); @@ -203,6 +224,86 @@ public void Blob_carrying_frame_transactions_are_filtered_out() Is.EquivalentTo([1ul, 3ul])); } + [Test] + public void Frame_transactions_past_the_verify_budget_are_not_offered() + { + Transaction legacy = Build.A.Transaction.WithNonce(1).SignedAndResolved(TestItem.PrivateKeyA).TestObject; + Transaction[] frameTxs = [.. TestItem.Addresses.Skip(1).Take(5).Select(sender => Profile2FrameTx(sender, 250_000))]; + Hash256 overBudget = frameTxs.Select(tx => tx.CalculateHash()).Max()!; + InclusionListTxSource source = CreateProfile2Source(); + byte[][][] il = AtPosition0([Encode(legacy), .. frameTxs.Select(Encode)]); + + source.Set(il, Eip8369Prototype.Instance); + List offered = [.. GetTransactions(source, Attributes(il))]; + + using (Assert.EnterMultipleScope()) + { + Assert.That(offered.Select(tx => tx.Hash), Does.Not.Contain(overBudget)); + Assert.That(offered, Has.Count.EqualTo(5)); + Assert.That(offered.Count(tx => tx.Hash == legacy.CalculateHash()), Is.EqualTo(1), "Profile 1 entries are still offered"); + } + } + + [Test] + public void Frame_transaction_admitted_at_another_position_is_offered() + { + Transaction[] frameTxs = [.. TestItem.Addresses.Skip(1).Take(5).Select(sender => Profile2FrameTx(sender, 250_000))]; + Transaction overBudget = frameTxs.MaxBy(tx => tx.CalculateHash())!; + InclusionListTxSource source = CreateProfile2Source(); + byte[][][] il = [[.. frameTxs.Select(Encode)], [Encode(overBudget)], .. Enumerable.Repeat([], Eip7805Constants.InclusionListCommitteeSize - 2)]; + + source.Set(il, Eip8369Prototype.Instance); + + Assert.That(GetTransactions(source, Attributes(il)).Select(tx => tx.Hash), Is.EquivalentTo(frameTxs.Select(tx => tx.CalculateHash()))); + } + + [TestCase(0UL, 2, TestName = "Lifting MAX_VERIFY_GAS_PER_TX admits the costlier entry")] + [TestCase(Eip8369Constants.MaxVerifyGasPerTx, 1, TestName = "An entry over MAX_VERIFY_GAS_PER_TX is not offered")] + public void Frame_transaction_over_the_per_tx_cap_is_not_offered(ulong maxVerifyGasPerTx, int expected) + { + Transaction admitted = Profile2FrameTx(TestItem.AddressB, 100_000); + Transaction overCap = Profile2FrameTx(TestItem.AddressC, Eip8369Constants.MaxVerifyGasPerTx + 1); + InclusionListTxSource source = CreateProfile2Source(new BlocksConfig { FocilProfile2MaxVerifyGas = maxVerifyGasPerTx }); + byte[][][] il = AtPosition0([Encode(overCap), Encode(admitted)]); + + source.Set(il, Eip8369Prototype.Instance); + List offered = [.. GetTransactions(source, Attributes(il))]; + + using (Assert.EnterMultipleScope()) + { + Assert.That(offered, Has.Count.EqualTo(expected)); + Assert.That(offered.Select(tx => tx.Hash), Does.Contain(admitted.CalculateHash())); + } + } + + private static InclusionListTxSource CreateProfile2Source(IBlocksConfig blocksConfig = null) => new( + new EthereumEcdsa(MainnetSpecProvider.Instance.ChainId), + new CustomSpecProvider(((ForkActivation)0, Eip8369Prototype.Instance)), + AcceptAll(), + LimboLogs.Instance, + blocksConfig: blocksConfig); + + private static ITxValidator AcceptAll() + { + ITxValidator acceptAll = Substitute.For(); + acceptAll.IsWellFormed(Arg.Any(), Arg.Any()).Returns(ValidationResult.Success); + return acceptAll; + } + + private static Transaction Profile2FrameTx(Address sender, ulong verifyGas) => new() + { + Type = TxType.FrameTx, + ChainId = MainnetSpecProvider.Instance.ChainId, + Nonce = 0, + SenderAddress = sender, + NonceKeys = [UInt256.Zero], + Frames = [new TxFrame(FrameMode.Verify, FrameFlags.ApproveExecutionAndPayment, target: null, verifyGas, UInt256.Zero, default)], + FrameSignatures = [], + GasPrice = 2.GWei, + MaxFee = (UInt256)verifyGas * 10.GWei, + DecodedMaxFeePerGas = 10.GWei, + }; + private static Transaction FrameTx(ulong nonce, byte[][] blobVersionedHashes) => new() { Type = TxType.FrameTx, @@ -224,7 +325,7 @@ public void Sender_nonces_are_ordered_ascending() InclusionListTxSource source = CreateSource(); Transaction nonce1 = Build.A.Transaction.WithNonce(1).SignedAndResolved(TestItem.PrivateKeyA).TestObject; Transaction nonce0 = Build.A.Transaction.WithNonce(0).SignedAndResolved(TestItem.PrivateKeyA).TestObject; - byte[][] il = [Encode(nonce1), Encode(nonce0)]; + byte[][][] il = AtPosition0([Encode(nonce1), Encode(nonce0)]); PayloadAttributes attrs = Attributes(il); source.Set(il, Bogota.Instance); @@ -241,7 +342,7 @@ public void Sender_order_of_first_appearance_is_preserved() Transaction b1 = Build.A.Transaction.WithNonce(1).SignedAndResolved(TestItem.PrivateKeyB).TestObject; Transaction a1 = Build.A.Transaction.WithNonce(1).SignedAndResolved(TestItem.PrivateKeyA).TestObject; Transaction b0 = Build.A.Transaction.WithNonce(0).SignedAndResolved(TestItem.PrivateKeyB).TestObject; - byte[][] il = [Encode(b1), Encode(a1), Encode(b0)]; + byte[][][] il = AtPosition0([Encode(b1), Encode(a1), Encode(b0)]); PayloadAttributes attrs = Attributes(il); source.Set(il, Bogota.Instance); diff --git a/src/Nethermind/Nethermind.Consensus.Test/MempoolStatePrewarmerTests.cs b/src/Nethermind/Nethermind.Consensus.Test/MempoolStatePrewarmerTests.cs index f88a26ff8a4c..84cd9322c966 100644 --- a/src/Nethermind/Nethermind.Consensus.Test/MempoolStatePrewarmerTests.cs +++ b/src/Nethermind/Nethermind.Consensus.Test/MempoolStatePrewarmerTests.cs @@ -453,7 +453,7 @@ public void NewHead_CancelsThePreviousSession() /// [Test] public void RemovedBlock_WithoutSuccess_StartsWarmingAgain( - [Values(ProcessingResult.Success, ProcessingResult.InclusionListUnsatisfied, ProcessingResult.QueueException, ProcessingResult.MissingBlock)] ProcessingResult result) + [Values(ProcessingResult.Success, ProcessingResult.QueueException, ProcessingResult.MissingBlock)] ProcessingResult result) { BlockHeader headHeader = Build.A.BlockHeader.WithNumber(10).WithTimestamp(100).WithGasLimit(30_000_000).TestObject; Block head = new(headHeader); @@ -467,7 +467,7 @@ public void RemovedBlock_WithoutSuccess_StartsWarmingAgain( queue.BlockAdded += Raise.EventWith(new BlockEventArgs(child)); queue.BlockRemoved += Raise.EventWith(new BlockRemovedEventArgs(child.Hash!, result)); - bool expectRestart = result is not (ProcessingResult.Success or ProcessingResult.InclusionListUnsatisfied or ProcessingResult.QueueException); + bool expectRestart = result is not (ProcessingResult.Success or ProcessingResult.QueueException); bool restarted = preWarmer.TryNextSession(expectRestart ? TimeSpan.FromSeconds(5) : TimeSpan.FromMilliseconds(200), out CancellationToken second); using (Assert.EnterMultipleScope()) diff --git a/src/Nethermind/Nethermind.Consensus.Test/PayloadAttributesPayloadIdTests.cs b/src/Nethermind/Nethermind.Consensus.Test/PayloadAttributesPayloadIdTests.cs index 6c874f3479ab..ee093bc3cbc4 100644 --- a/src/Nethermind/Nethermind.Consensus.Test/PayloadAttributesPayloadIdTests.cs +++ b/src/Nethermind/Nethermind.Consensus.Test/PayloadAttributesPayloadIdTests.cs @@ -15,7 +15,7 @@ public class PayloadAttributesPayloadIdTests { private static BlockHeader Parent() => Build.A.BlockHeader.WithHash(TestItem.KeccakA).TestObject; - private static PayloadAttributes BaseAttrs(byte[][]? il) => new() + private static PayloadAttributes BaseAttrs(byte[][][]? inclusionLists) => new() { Timestamp = 1234, PrevRandao = TestItem.KeccakB, @@ -23,25 +23,29 @@ public class PayloadAttributesPayloadIdTests Withdrawals = [], ParentBeaconBlockRoot = TestItem.KeccakC, SlotNumber = 42, - InclusionListTransactions = il, + InclusionLists = inclusionLists, }; + /// One list per committee position, from position 0 and the rest empty. + private static byte[][][] Lists(params byte[][][] lists) => + [.. lists, .. Enumerable.Repeat([], Eip7805Constants.InclusionListCommitteeSize - lists.Length)]; + [Test] public void Different_inclusion_lists_yield_different_payload_ids() { BlockHeader parent = Parent(); - string idA = BaseAttrs([[0x01, 0x02]]).GetPayloadId(parent); - string idB = BaseAttrs([[0x03, 0x04]]).GetPayloadId(parent); + string idA = BaseAttrs(Lists([[0x01, 0x02]])).GetPayloadId(parent); + string idB = BaseAttrs(Lists([[0x03, 0x04]])).GetPayloadId(parent); Assert.That(idA, Is.Not.EqualTo(idB)); } [Test] - public void Empty_inclusion_list_differs_from_nonempty() + public void Empty_inclusion_lists_differ_from_nonempty() { BlockHeader parent = Parent(); - string idEmpty = BaseAttrs([]).GetPayloadId(parent); - string idOne = BaseAttrs([[0x01]]).GetPayloadId(parent); + string idEmpty = BaseAttrs(Lists()).GetPayloadId(parent); + string idOne = BaseAttrs(Lists([[0x01]])).GetPayloadId(parent); Assert.That(idEmpty, Is.Not.EqualTo(idOne)); } @@ -50,45 +54,52 @@ public void Empty_inclusion_list_differs_from_nonempty() public void Inclusion_list_order_affects_payload_id() { BlockHeader parent = Parent(); - string idAB = BaseAttrs([[0x01], [0x02]]).GetPayloadId(parent); - string idBA = BaseAttrs([[0x02], [0x01]]).GetPayloadId(parent); + string idAB = BaseAttrs(Lists([[0x01], [0x02]])).GetPayloadId(parent); + string idBA = BaseAttrs(Lists([[0x02], [0x01]])).GetPayloadId(parent); Assert.That(idAB, Is.Not.EqualTo(idBA)); } + // Each list's entries decide its own budget fill, so neither which position carries an entry nor where one list + // ends and the next begins may collapse into the same build. [Test] - public void Same_inclusion_list_yields_same_payload_id() + public void Committee_positions_and_list_boundaries_affect_payload_id() { BlockHeader parent = Parent(); - string id1 = BaseAttrs([[0x01, 0x02, 0x03]]).GetPayloadId(parent); - string id2 = BaseAttrs([[0x01, 0x02, 0x03]]).GetPayloadId(parent); + string atFirst = BaseAttrs(Lists([[0x01]])).GetPayloadId(parent); + string atSecond = BaseAttrs(Lists([], [[0x01]])).GetPayloadId(parent); + string oneList = BaseAttrs(Lists([[0x01], [0x02]])).GetPayloadId(parent); + string twoLists = BaseAttrs(Lists([[0x01]], [[0x02]])).GetPayloadId(parent); + string oneEntry = BaseAttrs(Lists([[0x01, 0x02]])).GetPayloadId(parent); - Assert.That(id1, Is.EqualTo(id2)); + using (Assert.EnterMultipleScope()) + { + Assert.That(atFirst, Is.Not.EqualTo(atSecond)); + Assert.That(oneList, Is.Not.EqualTo(twoLists)); + Assert.That(oneList, Is.Not.EqualTo(oneEntry)); + } } - // The streaming path for oversized lists must agree with the pooled path byte for byte. [Test] - public void Streaming_and_pooled_inclusion_list_digests_agree([Values(0, 1, 7, 64)] int entryCount) + public void Same_inclusion_lists_yield_same_payload_id() { - byte[][] il = new byte[entryCount][]; - for (int i = 0; i < entryCount; i++) - il[i] = i % 3 == 0 ? [] : [.. Enumerable.Repeat((byte)i, i)]; + BlockHeader parent = Parent(); + string id1 = BaseAttrs(Lists([[0x01, 0x02, 0x03]])).GetPayloadId(parent); + string id2 = BaseAttrs(Lists([[0x01, 0x02, 0x03]])).GetPayloadId(parent); - Assert.That( - PayloadAttributes.ComputeInclusionListDigestStreaming(il), - Is.EqualTo(PayloadAttributes.ComputeInclusionListDigest(il))); + Assert.That(id1, Is.EqualTo(id2)); } [Test] public void Oversized_inclusion_list_still_yields_a_stable_distinct_payload_id() { - // Well past the aggregate bound, so the streaming path runs. - byte[] oversized = new byte[Eip7805Constants.MaxAggregateInclusionListBytes * 2]; + // Far past one list's byte cap, which forkchoiceUpdated rejects before a build, so only the digest runs. + byte[] oversized = new byte[Eip7805Constants.InclusionListCommitteeSize * Eip7805Constants.MaxBytesPerInclusionList * 2]; - string id1 = BaseAttrs([oversized]).GetPayloadId(Parent()); - string id2 = BaseAttrs([oversized]).GetPayloadId(Parent()); + string id1 = BaseAttrs(Lists([oversized])).GetPayloadId(Parent()); + string id2 = BaseAttrs(Lists([oversized])).GetPayloadId(Parent()); oversized[0] = 0xff; - string idChanged = BaseAttrs([oversized]).GetPayloadId(Parent()); + string idChanged = BaseAttrs(Lists([oversized])).GetPayloadId(Parent()); using (Assert.EnterMultipleScope()) { @@ -100,10 +111,10 @@ public void Oversized_inclusion_list_still_yields_a_stable_distinct_payload_id() [Test] public void Null_vs_empty_inclusion_list_yields_different_payload_ids() { - // null = V4 (IL omitted from digest); [] = V5 with empty IL — different fork versions. + // null = V4 (lists omitted from digest); empty lists = V5 — different fork versions. BlockHeader parent = Parent(); string idNull = BaseAttrs(null).GetPayloadId(parent); - string idEmpty = BaseAttrs([]).GetPayloadId(parent); + string idEmpty = BaseAttrs(Lists()).GetPayloadId(parent); Assert.That(idNull, Is.Not.EqualTo(idEmpty)); } diff --git a/src/Nethermind/Nethermind.Consensus.Test/PayloadAttributesValidateTests.cs b/src/Nethermind/Nethermind.Consensus.Test/PayloadAttributesValidateTests.cs index 1436ccc28641..af57e0566d21 100644 --- a/src/Nethermind/Nethermind.Consensus.Test/PayloadAttributesValidateTests.cs +++ b/src/Nethermind/Nethermind.Consensus.Test/PayloadAttributesValidateTests.cs @@ -1,6 +1,7 @@ // SPDX-FileCopyrightText: 2026 Demerzel Solutions Limited // SPDX-License-Identifier: LGPL-3.0-only +using System.Linq; using Nethermind.Consensus.Producers; using Nethermind.Core; using Nethermind.Core.Crypto; @@ -71,8 +72,8 @@ public void Validate_returns_expected_result( } } - // bogota.md PayloadAttributesV5 appends inclusionListTransactions unconditionally: an empty list is - // valid, an absent one leaves the attributes V4-shaped and earns -38003 from FCUv5. + // bogota.md PayloadAttributesV5 appends inclusionLists unconditionally: sixteen empty lists are valid, + // absent ones leave the attributes V4-shaped and earn -38003 from FCUv5. [TestCase(PayloadAttributesVersions.V5, false, PayloadAttributesValidationResult.InvalidPayloadAttributes)] [TestCase(PayloadAttributesVersions.V5, true, PayloadAttributesValidationResult.Success)] [TestCase(PayloadAttributesVersions.V4, false, PayloadAttributesValidationResult.UnsupportedFork)] @@ -88,7 +89,7 @@ public void Validate_requires_an_inclusion_list_at_Bogota( sp.GetSpec(Arg.Any()).Returns(spec); PayloadAttributes attrs = BuildAttrs(withSlotNumber: true); - attrs.InclusionListTransactions = withInclusionList ? [] : null; + attrs.InclusionLists = withInclusionList ? [.. Enumerable.Repeat([], Eip7805Constants.InclusionListCommitteeSize)] : null; PayloadAttributesValidationResult result = attrs.Validate(sp, fcuVersion, out string error); @@ -96,7 +97,7 @@ public void Validate_requires_an_inclusion_list_at_Bogota( { Assert.That(result, Is.EqualTo(expected)); if (expected == PayloadAttributesValidationResult.InvalidPayloadAttributes) - Assert.That(error, Does.Contain(nameof(PayloadAttributes.InclusionListTransactions))); + Assert.That(error, Does.Contain("Inclusion lists")); } } diff --git a/src/Nethermind/Nethermind.Consensus.Test/Processing/BranchProcessorVerdictTests.cs b/src/Nethermind/Nethermind.Consensus.Test/Processing/BranchProcessorVerdictTests.cs index 7b82bc6c209f..79a1ffca2856 100644 --- a/src/Nethermind/Nethermind.Consensus.Test/Processing/BranchProcessorVerdictTests.cs +++ b/src/Nethermind/Nethermind.Consensus.Test/Processing/BranchProcessorVerdictTests.cs @@ -9,12 +9,9 @@ using Autofac; using Nethermind.Blockchain; using Nethermind.Blockchain.Tracing; -using Nethermind.Consensus.ExecutionRequests; using Nethermind.Consensus.Processing; -using Nethermind.Consensus.Validators; using Nethermind.Core; using Nethermind.Core.Exceptions; -using Nethermind.Core.Extensions; using Nethermind.Core.Container; using Nethermind.Core.Specs; using Nethermind.Core.Test.Builders; @@ -25,9 +22,6 @@ using Nethermind.Evm.Tracing; using Nethermind.Logging; using Nethermind.Specs.Forks; -using Nethermind.TxPool; -using Nethermind.State; -using Nethermind.Specs.Test; using NSubstitute; using NUnit.Framework; using Nethermind.Core.Test; @@ -36,137 +30,6 @@ namespace Nethermind.Consensus.Test.Processing; public class BranchProcessorVerdictTests { - [Test] - public void Inclusion_list_without_bal_uses_state_before_post_execution_credits([Values] bool fundedBeforeTransactions, [Values] bool withdrawal, [Values(0UL, 1UL)] ulong nonce) - { - IReleaseSpec spec = new OverridableReleaseSpec(Bogota.Instance) { IsEip7928Enabled = false }; - Transaction tx = Build.A.Transaction.WithNonce(nonce).WithGasLimit(100_000).WithGasPrice(1).WithValue(0) - .WithTo(TestItem.AddressB).SignedAndResolved(TestItem.PrivateKeyA).TestObject; - Block block = Build.A.Block.WithNumber(0).WithGasLimit(30_000_000).WithBaseFeePerGas(0) - .WithTransactions([]) - .WithWithdrawals(withdrawal ? [Build.A.Withdrawal.WithRecipient(TestItem.AddressA).WithAmount(1).TestObject] : []) - .WithInclusionListTransactions([tx]).TestObject; - IExecutionRequestsProcessor requests = Substitute.For(); - requests.When(processor => processor.ProcessExecutionRequests(Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any())) - .Do(call => - { - if (!withdrawal) call.Arg().AddToBalanceAndCreateIfNotExists(TestItem.AddressA, 1.GWei, spec); - }); - IBlockValidator validator = Substitute.For(); - validator.ValidateProcessedBlock(Arg.Any(), Arg.Any(), Arg.Any(), out Arg.Any()).Returns(true); - using IContainer container = new ContainerBuilder() - .AddModule(new TestNethermindModule(spec)) - .AddSingleton(validator) - .AddSingleton(requests) - .Build(); - IMainProcessingContext context = container.Resolve(); - using IDisposable scope = context.WorldState.BeginScope(IWorldState.PreGenesis); - if (fundedBeforeTransactions || nonce != 0) - context.WorldState.CreateAccount(TestItem.AddressA, fundedBeforeTransactions ? 1.GWei : 0, nonce); - context.WorldState.Commit(spec); - ValidationResult txValidation = container.Resolve().IsWellFormed(tx, spec, block.GasLimit); - using (Assert.EnterMultipleScope()) - { - Assert.That((bool)txValidation, Is.True, txValidation.ToString()); - Assert.That(InclusionListValidator.IsSatisfied(block, context.WorldState, spec, container.Resolve()), Is.EqualTo(!fundedBeforeTransactions), "Before processing"); - } - - Block[] processed = context.BranchProcessor.Process(null, [block], ProcessingOptions.None, NullBlockTracer.Instance); - - using (Assert.EnterMultipleScope()) - { - Assert.That(processed[0].IsInclusionListSatisfied, Is.EqualTo(!fundedBeforeTransactions)); - Assert.That(block.IsInclusionListSatisfied, Is.EqualTo(!fundedBeforeTransactions)); - Assert.That(context.WorldState.GetBalance(TestItem.AddressA), Is.GreaterThanOrEqualTo(1.GWei)); - } - } - - [Test] - public void Inclusion_list_preserves_parallel_execution_options([Values] bool nonemptyList) - { - Block block = Build.A.Block.WithNumber(0).WithInclusionListTransactions(nonemptyList ? [Build.A.Transaction.TestObject] : []).TestObject; - IBlockProcessor processor = Substitute.For(); - ProcessingOptions actualOptions = ProcessingOptions.None; - processor.ProcessOne(Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any()) - .Returns(call => - { - actualOptions = call.Arg(); - processor.TransactionsExecuted += Raise.Event>(block); - return (block, Array.Empty()); - }); - using IContainer container = new ContainerBuilder() - .AddModule(new TestNethermindModule(Bogota.Instance)) - .AddSingleton(processor) - .Build(); - - container.Resolve().BranchProcessor.Process(null, [block], ProcessingOptions.None, NullBlockTracer.Instance); - - Assert.That(actualOptions.ContainsFlag(ProcessingOptions.ForceSequentialBlockAccessList), Is.False); - } - - [Test] - public void Inclusion_list_shortcuts_do_not_read_sender_accounts([Values] bool fullBlock) - { - Transaction tx = Build.A.Transaction.SignedAndResolved(TestItem.PrivateKeyA).TestObject; - Block block = Build.A.Block.WithNumber(0).WithGasLimit(30_000_000).WithGasUsed(fullBlock ? 30_000_000UL : 0) - .WithTransactions(fullBlock ? [] : [tx]).WithInclusionListTransactions([tx]).TestObject; - IBlockProcessor processor = Substitute.For(); - processor.ProcessOne(Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any()) - .Returns(_ => - { - processor.TransactionsExecuted += Raise.Event>(block); - return (block, Array.Empty()); - }); - using IContainer container = new ContainerBuilder() - .AddModule(new TestNethermindModule(Bogota.Instance)) - .AddSingleton(processor) - .AddDecorator((_, state) => new CountingWorldState(state)) - .Build(); - IMainProcessingContext context = container.Resolve(); - - context.BranchProcessor.Process(null, [block], ProcessingOptions.None, NullBlockTracer.Instance); - - Assert.That(((CountingWorldState)context.WorldState).AccountReads, Is.Zero); - } - - [Test] - public void Custom_inclusion_list_checker_can_read_accounts_outside_the_list() - { - Block block = Build.A.Block.WithNumber(0).WithInclusionListTransactions([Build.A.Transaction.TestObject]).TestObject; - IInclusionListSatisfactionChecker checker = Substitute.For(); - checker.IsSatisfied(Arg.Any(), Arg.Any(), Arg.Any()).Returns(call => - { - IReadOnlyStateProvider state = call.Arg(); - state.TryGetAccount(TestItem.AddressB, out _); - state.GetCode(TestItem.AddressB); - state.Get(new StorageCell(TestItem.AddressB, 0), out _); - return true; - }); - IBlockProcessor processor = Substitute.For(); - processor.ProcessOne(Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any()) - .Returns(_ => - { - processor.TransactionsExecuted += Raise.Event>(block); - return (block, Array.Empty()); - }); - using IContainer container = new ContainerBuilder().AddModule(new TestNethermindModule(Bogota.Instance)) - .AddSingleton(processor).AddSingleton(checker).Build(); - - container.Resolve().BranchProcessor.Process(null, [block], ProcessingOptions.None, NullBlockTracer.Instance); - - checker.Received(1).IsSatisfied(Arg.Any(), Arg.Any(), Arg.Any()); - } - - private sealed class CountingWorldState(IWorldState inner) : WorldStateDecorator(inner) - { - public int AccountReads { get; private set; } - public override bool TryGetAccount(Address address, out AccountStruct account) - { - AccountReads++; - return base.TryGetAccount(address, out account); - } - } - [Test] public async Task Concurrent_processing_uses_invocation_worker_groups([Values] bool readOnly, [Values] bool ambient) { @@ -357,6 +220,33 @@ public void Process_failure_after_the_verdict_is_a_commit_failure_only_once_answ Assert.That(thrown, Is.TypeOf(expected)); } + /// EIP-7805 fits an omission claim against the gas used before its index, which only execution + /// records, so it is kept on the suggested block for a deferred inclusion check once Profile 2 is active. + [Test] + public void Process_records_the_gas_used_before_each_transaction_once_profile_2_is_active([Values] bool profile2Active) + { + BlockHeader parent = Build.A.BlockHeader.WithNumber(0).TestObject; + Transaction[] txs = [Build.A.Transaction.WithNonce(0).TestObject, Build.A.Transaction.WithNonce(1).TestObject]; + Block suggested = Build.A.Block.WithParent(parent).WithTransactions(txs).TestObject; + Block processed = Build.A.Block.WithParent(parent).WithTransactions(txs).WithGasUsed(30_000).TestObject; + processed.Header.GasUsedPerDimension = (30_000, 5_000); + TxReceipt[] receipts = [new() { BlockGasUsed = 21_000, StorageGasUsed = 5_000 }, new() { BlockGasUsed = 9_000 }]; + + IBlockProcessor blockProcessor = Substitute.For(); + blockProcessor.ProcessOne(Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any()) + .Returns((processed, receipts)); + IWorldState worldState = Substitute.For(); + worldState.TryBeginScopeAtTarget(Arg.Any(), out Arg.Any()) + .Returns(call => call.Succeed(1, Substitute.For())); + ISpecProvider specProvider = Substitute.For(); + specProvider.GetSpec(Arg.Any()).Returns(profile2Active ? Eip8369Prototype.Instance : Bogota.Instance); + + BranchProcessor branchProcessor = new(blockProcessor, specProvider, worldState, Substitute.For(), LimboLogs.Instance); + branchProcessor.Process(parent, [suggested], ProcessingOptions.None, NullBlockTracer.Instance); + + Assert.That(suggested.GasUsedBeforeTransactions, profile2Active ? Is.EqualTo(new (ulong, ulong)[] { (0, 0), (21_000, 5_000) }) : Is.Null); + } + [TestCase(0UL, 0, TestName = "Process_BeforeEip7709_PrefetchesEveryBlock")] [TestCase(1UL, 2, TestName = "Process_WithEip7709_SkipsBlockhashPrefetch")] [TestCase(2UL, 1, TestName = "Process_BranchCrossingEip7709_PrefetchesOnlyBeforeTheFork")] @@ -388,6 +278,6 @@ private static BranchProcessor CreateBranchProcessor(ISpecProvider specProvider .Returns(call => call.Succeed(1, Substitute.For())); return new BranchProcessor(blockProcessor, specProvider ?? Substitute.For(), worldState, blockhashProvider ?? Substitute.For(), - Substitute.For(), LimboLogs.Instance, Substitute.For()); + LimboLogs.Instance); } } diff --git a/src/Nethermind/Nethermind.Consensus.Test/Processing/FinalizedBlockAccessListTests.cs b/src/Nethermind/Nethermind.Consensus.Test/Processing/FinalizedBlockAccessListTests.cs index 7e743b2cf4ac..fafbac20fb9e 100644 --- a/src/Nethermind/Nethermind.Consensus.Test/Processing/FinalizedBlockAccessListTests.cs +++ b/src/Nethermind/Nethermind.Consensus.Test/Processing/FinalizedBlockAccessListTests.cs @@ -140,102 +140,6 @@ public void Replay_production_and_engine_validation_execute(ProcessingOptions op Assert.That(env.Recording.Calls, Is.EqualTo(1)); } - [TestCase(0UL, false, true, 0)] - [TestCase(21_000UL, true, true, 0)] - [TestCase(21_000UL, false, true, 1)] - [TestCase(21_000UL, false, false, 0)] - public void Inclusion_list_reconstruction_requires_gas_dimensions(ulong gasUsed, bool dimensionsKnown, bool nonemptyList, int executions) - { - using TestEnvironment env = new(useFlatDb); - Block block = env.CreateBlock(gasUsed: gasUsed); - block.InclusionListTransactions = nonemptyList ? [Build.A.Transaction.TestObject] : []; - if (dimensionsKnown) block.Header.GasUsedPerDimension = (gasUsed, 0); - env.Beacon.GetFinalizedHash().Returns(block.Hash); - using IDisposable scope = env.State.BeginScope(env.Genesis.Header); - env.Processor.ProcessOne(block, ProcessingOptions.None, NullBlockTracer.Instance, Bogota.Instance); - using (Assert.EnterMultipleScope()) - { - Assert.That(env.Recording.Calls, Is.EqualTo(executions)); - Assert.That(env.Recording.LastOptions.HasFlag(ProcessingOptions.ForceSequentialBlockAccessList), Is.False); - } - } - - [Test] - public void Inclusion_list_releases_parent_scope_after_verdict_or_read_failure([Values] bool readFails) - { - IWorldStateScopeProvider.IScope parentScope = Substitute.For(); - parentScope.Get(TestItem.AddressA).Returns(_ => readFails - ? throw new InvalidOperationException("Injected parent read failure") : new Account(0, 100)); - IWorldStateScopeProvider parentProvider = Substitute.For(); - parentProvider.TryBeginScope(Arg.Any(), Arg.Any(), out Arg.Any()) - .Returns(call => { call[2] = parentScope; return true; }); - IWorldStateManager parentReader = Substitute.For(); - parentReader.CreateResettableWorldState().Returns(parentProvider); - using TestEnvironment env = new(useFlatDb, releaseSpec: Bogota.Instance, parentReader: parentReader); - Block block = env.CreateBlock(); - block.InclusionListTransactions = [Build.A.Transaction.WithNonce(0).WithGasPrice(0).WithGasLimit(100_000) - .WithValue(50).WithTo(TestItem.AddressB).SignedAndResolved(TestItem.PrivateKeyA).TestObject]; - env.Beacon.GetFinalizedHash().Returns(block.Hash); - - try - { - if (readFails) - Assert.Throws(() => env.Branch.Process(env.Genesis.Header, [block], ProcessingOptions.None, NullBlockTracer.Instance)); - else - Assert.That(env.Branch.Process(env.Genesis.Header, [block], ProcessingOptions.None, NullBlockTracer.Instance)[0].IsInclusionListSatisfied, Is.False); - - parentScope.Received(1).Get(TestItem.AddressA); - parentScope.Received(1).Dispose(); - } - finally - { - block.DisposeAccountChanges(); - } - } - - [Test] - public void Inclusion_list_uses_generated_bal_without_reading_unchanged_parent() - { - IWorldStateManager parentReader = Substitute.For(); - using TestEnvironment env = new(useFlatDb, releaseSpec: Bogota.Instance, parentReader: parentReader); - Block block = env.CreateBlock(); - block.BlockAccessList = null; - block.EncodedBlockAccessList = null; - block.GeneratedBlockAccessList = new GeneratedBlockAccessList(); - block.InclusionListTransactions = [Build.A.Transaction.WithNonce(0).WithGasPrice(0).WithGasLimit(100_000) - .WithValue(50).WithTo(TestItem.AddressB).SignedAndResolved(TestItem.PrivateKeyA).TestObject]; - - Block[] processed = env.Branch.Process(env.Genesis.Header, [block], ProcessingOptions.None, NullBlockTracer.Instance); - - Assert.That(processed[0].IsInclusionListSatisfied, Is.False); - parentReader.DidNotReceive().CreateResettableWorldState(); - } - - [Test] - public void Inclusion_list_uses_each_parent_inside_an_uncommitted_branch() - { - using TestEnvironment env = new(useFlatDb, releaseSpec: Bogota.Instance); - Block first = env.CreateBlock(balance: 25); - Block second = env.CreateBlock(parent: first, balance: 75); - Block third = env.CreateBlock(parent: second, balance: 25); - Transaction omitted = Build.A.Transaction.WithNonce(0).WithGasPrice(0).WithGasLimit(100_000) - .WithValue(50).WithTo(TestItem.AddressB).SignedAndResolved(TestItem.PrivateKeyA).TestObject; - first.InclusionListTransactions = [omitted]; - second.InclusionListTransactions = [omitted]; - third.InclusionListTransactions = [Build.A.Transaction.WithNonce(0).WithGasPrice(0).WithGasLimit(100_000) - .WithValue(90).WithTo(TestItem.AddressB).SignedAndResolved(TestItem.PrivateKeyA).TestObject]; - env.Beacon.GetFinalizedHash().Returns(third.Hash); - - Block[] processed = env.Branch.Process(env.Genesis.Header, [first, second, third], ProcessingOptions.None, NullBlockTracer.Instance); - - using (Assert.EnterMultipleScope()) - { - Assert.That(env.Recording.Calls, Is.Zero, "IL checks must preserve finalized BAL reconstruction"); - Assert.That(processed.Select(block => block.IsInclusionListSatisfied), Is.EqualTo(new[] { false, true, true })); - } - foreach (Block block in processed) block.DisposeAccountChanges(); - } - [Test] public void Reconstruction_needs_and_returns_stored_receipts([Values] bool stored) { diff --git a/src/Nethermind/Nethermind.Consensus.Test/RecoverSignaturesTest.cs b/src/Nethermind/Nethermind.Consensus.Test/RecoverSignaturesTest.cs index e71c4007b4d8..3695af4a282e 100644 --- a/src/Nethermind/Nethermind.Consensus.Test/RecoverSignaturesTest.cs +++ b/src/Nethermind/Nethermind.Consensus.Test/RecoverSignaturesTest.cs @@ -84,20 +84,14 @@ public void RecoverData_with_a_range_recovers_only_the_transactions_in_it(int st } [Test] - public void RecoverDataForTransactionTrace_leaves_the_block_senders_and_recovers_the_inclusion_list() + public void RecoverDataForTransactionTrace_leaves_the_block_senders() { Transaction[] txs = SignedTransactions(5); - Transaction included = Signed(TestItem.PrivateKeyB, 0); Block block = Build.A.Block.WithTransactions(txs).TestObject; - block.InclusionListTransactions = [included]; CreateRangeSut().RecoverDataForTransactionTrace(block); - using (Assert.EnterMultipleScope()) - { - Assert.That(txs.Select(static tx => tx.SenderAddress), Is.All.Null); - Assert.That(included.SenderAddress, Is.EqualTo(TestItem.AddressB)); - } + Assert.That(txs.Select(static tx => tx.SenderAddress), Is.All.Null); } private static RecoverSignatures CreateRangeSut() diff --git a/src/Nethermind/Nethermind.Consensus/Decoders/InclusionListDecoder.cs b/src/Nethermind/Nethermind.Consensus/Decoders/InclusionListDecoder.cs index 4dc95d5d5c3d..e2c409341462 100644 --- a/src/Nethermind/Nethermind.Consensus/Decoders/InclusionListDecoder.cs +++ b/src/Nethermind/Nethermind.Consensus/Decoders/InclusionListDecoder.cs @@ -1,9 +1,11 @@ // SPDX-FileCopyrightText: 2026 Demerzel Solutions Limited // SPDX-License-Identifier: LGPL-3.0-only +using System.Collections.Generic; using Nethermind.Consensus.Processing; using Nethermind.Core; using Nethermind.Core.Collections; +using Nethermind.Core.Crypto; using Nethermind.Core.Specs; using Nethermind.Crypto; using Nethermind.Logging; @@ -35,6 +37,37 @@ public Transaction[] DecodeAndRecover(byte[][] txBytes, IReleaseSpec spec) return txs; } + /// Decodes each committee position's list and recovers the senders, tolerating entries that are neither. + /// As , list by list, so each decoded list can be + /// shorter than its input. Envelopes repeated across positions share one decoded transaction, whose sender is + /// recovered and whose signatures are verified once however many lists carry it. + public Transaction[][] DecodeAndRecover(byte[][][] inclusionLists, IReleaseSpec spec) + { + Transaction[][] decoded = DecodeLists(inclusionLists); + _recoverSignatures.RecoverData(InclusionLists.Distinct(decoded), spec, skipErrors: true); + return decoded; + } + + /// Decodes each committee position's list, dropping undecodable entries and sharing one transaction + /// per hash across positions. + public static Transaction[][] DecodeLists(byte[][][] inclusionLists) + { + Dictionary byHash = []; + Transaction[][] decoded = new Transaction[inclusionLists.Length][]; + for (int position = 0; position < inclusionLists.Length; position++) + { + Transaction[] transactions = TxsDecoder.DecodeTxs(inclusionLists[position] ?? [], skipErrors: true).Transactions; + for (int i = 0; i < transactions.Length; i++) + { + if (transactions[i].Hash is not { } hash) continue; + if (byHash.TryGetValue(hash, out Transaction? shared)) transactions[i] = shared; + else byHash[hash] = transactions[i]; + } + decoded[position] = transactions; + } + return decoded; + } + private static byte[] Encode(Transaction transaction) { TxDecoder decoder = TxDecoder.Instance; diff --git a/src/Nethermind/Nethermind.Consensus/Processing/BlockCachePreWarmer.cs b/src/Nethermind/Nethermind.Consensus/Processing/BlockCachePreWarmer.cs index aed98f99df8c..2f0a2550077e 100644 --- a/src/Nethermind/Nethermind.Consensus/Processing/BlockCachePreWarmer.cs +++ b/src/Nethermind/Nethermind.Consensus/Processing/BlockCachePreWarmer.cs @@ -2064,7 +2064,6 @@ internal static Span SortUnique(Span items, TComparer compar /// /// Words are deduplicated as they are: an ABI address word is the address left-padded to 32 bytes, the /// that builds, so a repeated word allocates nothing. - /// Inclusion-list transactions are scanned after the block's own, as the sender and recipient pass covers them. /// Once is cancelled, the scan stops and returns what it has collected. /// internal static ArrayPoolList
? CollectCalldataAddresses(Block block, CancellationToken cancellationToken = default) @@ -2073,11 +2072,10 @@ internal static Span SortUnique(Span items, TComparer compar ArrayPoolList
? addresses = null; try { - int count = block.Transactions.Length + (block.InclusionListTransactions?.Length ?? 0); - for (int i = 0; i < count; i++) + foreach (Transaction tx in block.Transactions) { if (cancellationToken.IsCancellationRequested) return addresses; - ReadOnlySpan data = AddressWarmer.TransactionAt(block, i).Data.Span; + ReadOnlySpan data = tx.Data.Span; if (data.Length < 4 + MinCalldataWordsForAddressWarm * 32) continue; for (int offset = 4; offset + 32 <= data.Length; offset += 32) { @@ -2237,7 +2235,7 @@ private void WarmupAddresses(ParallelOptions parallelOptions, Block block) // increment per transaction on the fan-out's shared index, which on a dense block is thousands of // contended writes to one cache line for a few nanoseconds of work each. _fanOutReleased?.Wait(parallelOptions.CancellationToken); - int count = block.Transactions.Length + (block.InclusionListTransactions?.Length ?? 0); + int count = block.Transactions.Length; int rangeSize = Math.Max(16, count / (parallelOptions.MaxDegreeOfParallelism * 4)); WarmingState<(Block Block, int RangeSize, int Count)> baseState = new(envPool, (block, rangeSize, count), block.Header); ParallelUnbalancedWork.For( @@ -2252,7 +2250,7 @@ private void WarmupAddresses(ParallelOptions parallelOptions, Block block) int end = Math.Min((range + 1) * rangeSize, count); for (int i = range * rangeSize; i < end; i++) { - Transaction tx = TransactionAt(block, i); + Transaction tx = block.Transactions[i]; WarmupSender(tx.SenderAddress, tx.To, worldState); } @@ -2276,12 +2274,12 @@ private void WarmupAddresses(ParallelOptions parallelOptions, Block block) /// private void PrefetchKnownState(Block block, IWorldState worldState, CancellationToken token) { - int count = block.Transactions.Length + (block.InclusionListTransactions?.Length ?? 0); + int count = block.Transactions.Length; int accountCapacity = 2 * count + 1 + (WarmWithdrawals ? block.Withdrawals!.Length : 0); int slotCapacity = 0; for (int i = 0; i < count; i++) { - if (TransactionAt(block, i).AccessList is { IsEmpty: false } accessList) + if (block.Transactions[i].AccessList is { IsEmpty: false } accessList) { (int addresses, int storageKeys) = accessList.Count; accountCapacity += addresses; @@ -2299,7 +2297,7 @@ private void PrefetchKnownState(Block block, IWorldState worldState, Cancellatio for (int i = 0; i < count; i++) { if ((i & 0x3F) == 0 && token.IsCancellationRequested) return; - Transaction tx = TransactionAt(block, i); + Transaction tx = block.Transactions[i]; if (tx.SenderAddress is { } sender) accounts[accountCount++] = sender; if (tx.To is { } recipient) accounts[accountCount++] = recipient; if (tx.AccessList is { IsEmpty: false } accessList) @@ -2336,13 +2334,6 @@ private void PrefetchKnownState(Block block, IWorldState worldState, Cancellatio } } - /// Indexes past the block transactions address inclusion-list ones, which may be promoted into the block. - internal static Transaction TransactionAt(Block block, int i) - { - Transaction[] txs = block.Transactions; - return i < txs.Length ? txs[i] : block.InclusionListTransactions![i - txs.Length]; - } - /// Warms every system-contract hint. /// Whether all of them landed. /// diff --git a/src/Nethermind/Nethermind.Consensus/Processing/BlockHashEventArgs.cs b/src/Nethermind/Nethermind.Consensus/Processing/BlockHashEventArgs.cs index a83fcd0ce9ea..65f95d5f9fc5 100644 --- a/src/Nethermind/Nethermind.Consensus/Processing/BlockHashEventArgs.cs +++ b/src/Nethermind/Nethermind.Consensus/Processing/BlockHashEventArgs.cs @@ -38,10 +38,5 @@ public enum ProcessingResult /// /// Processing failed /// - ProcessingError, - - /// - /// Invalid inclusion list - /// - InclusionListUnsatisfied + ProcessingError } diff --git a/src/Nethermind/Nethermind.Consensus/Processing/BlockProcessor.BlockProductionTransactionPicker.cs b/src/Nethermind/Nethermind.Consensus/Processing/BlockProcessor.BlockProductionTransactionPicker.cs index c234149ce519..4d897a86b3f6 100644 --- a/src/Nethermind/Nethermind.Consensus/Processing/BlockProcessor.BlockProductionTransactionPicker.cs +++ b/src/Nethermind/Nethermind.Consensus/Processing/BlockProcessor.BlockProductionTransactionPicker.cs @@ -109,7 +109,7 @@ public virtual AddingTxEventArgs CanAddTransaction( { if (!KeyedNonceManager.IsNonceSetValid(stateProvider, currentTx.SenderAddress, currentTx.NonceKeys!, currentTx.Nonce)) { - return NewArgs(block, currentTx, transactionsInBlock).Set(TxAction.Skip, KeyedNonceSkipReason(stateProvider, currentTx)); + return NewArgs(block, currentTx, transactionsInBlock).SetInvalid(KeyedNonceSkipReason(stateProvider, currentTx)); } } else @@ -219,7 +219,7 @@ public DeferredSkipArgs(Block block, Transaction currentTx, IReadOnlySet _kind switch diff --git a/src/Nethermind/Nethermind.Consensus/Processing/BlockProcessor.BlockProductionTransactionsExecutor.cs b/src/Nethermind/Nethermind.Consensus/Processing/BlockProcessor.BlockProductionTransactionsExecutor.cs index aa66de27fcdd..0f8d7a04e0c5 100644 --- a/src/Nethermind/Nethermind.Consensus/Processing/BlockProcessor.BlockProductionTransactionsExecutor.cs +++ b/src/Nethermind/Nethermind.Consensus/Processing/BlockProcessor.BlockProductionTransactionsExecutor.cs @@ -86,14 +86,24 @@ public TxReceipt[] ProcessTransactions(Block block, ProcessingOptions processing HashSet consideredTx = [with(ByHashTxComparer.Instance)]; HashSet? executedAndSkippedTx = null; + IReadOnlySet? claimable = blockToProduce?.InclusionListCandidates; + List? claims = null; BlockAccessListItemBudget itemBudget = CreateItemBudget(block); foreach (Transaction currentTx in transactions) { // Check if we have gone over time or the payload has been requested if (token.IsCancellationRequested) break; - TxAction action = ProcessTransaction(block, currentTx, includedTx.Count, receiptsTracer, processingOptions, consideredTx, ref itemBudget, out bool executed); + // EIP-7805: only the first attempt is where the builder tried; a later offer is a duplicate. + bool claimOnSkip = claimable is not null && currentTx.Hash is { } hash + && claimable.Contains(hash) && !consideredTx.Contains(currentTx); + TxAction action = ProcessTransaction(block, currentTx, includedTx.Count, receiptsTracer, processingOptions, consideredTx, ref itemBudget, out bool executed, out bool invalidHere); if (action == TxAction.Stop) break; + // A claim binds the builder: the omission is judged at the claimed index alone, so claim only where the + // candidate is invalid there, never where it was skipped for a reason of the builder's own. + if (action == TxAction.Skip && claimOnSkip && (claims?.Count ?? 0) < Eip8369Constants.MaxOmissionClaims + && invalidHere) + (claims ??= []).Add(new OmissionClaim(currentTx.Hash!, (ulong)includedTx.Count)); consideredTx.Add(currentTx); if (action == TxAction.Add) @@ -161,7 +171,7 @@ public TxReceipt[] ProcessTransactions(Block block, ProcessingOptions processing continue; } - TxAction action = ProcessTransaction(block, currentTx, includedTx.Count, receiptsTracer, processingOptions, consideredTx, ref itemBudget, out bool executed); + TxAction action = ProcessTransaction(block, currentTx, includedTx.Count, receiptsTracer, processingOptions, consideredTx, ref itemBudget, out bool executed, out _); if (action == TxAction.Stop) { added = false; @@ -212,6 +222,7 @@ public TxReceipt[] ProcessTransactions(Block block, ProcessingOptions processing if (blockToProduce is not null) { blockToProduce.Transactions = includedTx.ToArray(); + blockToProduce.OmissionClaims = claims?.ToArray(); } return receiptsTracer.TxReceipts.ToArray(); } @@ -246,7 +257,8 @@ private TxAction ProcessTransaction( ProcessingOptions processingOptions, HashSet transactionsInBlock, ref BlockAccessListItemBudget itemBudget, - out bool executed) + out bool executed, + out bool invalidHere) { executed = false; AddingTxEventArgs args = txPicker.CanAddTransaction( @@ -290,11 +302,12 @@ private TxAction ProcessTransaction( // gas is not reset here, but the next receipt rewrites the header's gas used from receipts kept. receiptsTracer.Restore(receiptsSnapshot); balManager.Rollback(); - args.Set(TxAction.Skip, result.ErrorDescription!); + args.SetInvalid(result.ErrorDescription!); EvictUnpaidFrameTx(currentTx, result); } } + invalidHere = args.IsInvalidHere; return args.Action; [MethodImpl(MethodImplOptions.NoInlining)] diff --git a/src/Nethermind/Nethermind.Consensus/Processing/BlockProcessor.IBlockProductionTransactionsExecutor.cs b/src/Nethermind/Nethermind.Consensus/Processing/BlockProcessor.IBlockProductionTransactionsExecutor.cs index f09cd1cb2eb9..df616cd35a62 100644 --- a/src/Nethermind/Nethermind.Consensus/Processing/BlockProcessor.IBlockProductionTransactionsExecutor.cs +++ b/src/Nethermind/Nethermind.Consensus/Processing/BlockProcessor.IBlockProductionTransactionsExecutor.cs @@ -33,15 +33,32 @@ public class AddingTxEventArgs(int index, Transaction transaction, Block block, public TxAction Action { get; private set; } = TxAction.Add; public string Reason => ReferenceEquals(_reason, DeferredReason) ? _reason = FormatDeferredReason() : _reason; + /// Whether the transaction is skipped because it is invalid at this index, rather than by the builder's + /// policy; an omission claim is made only for such a skip. + public bool IsInvalidHere { get; private set; } + public AddingTxEventArgs Set(TxAction action, string reason) { Action = action; _reason = reason; + IsInvalidHere = false; + return this; + } + + /// Skips the transaction as invalid at this index. + public AddingTxEventArgs SetInvalid(string reason) + { + Set(TxAction.Skip, reason); + IsInvalidHere = true; return this; } /// Sets with a reason builds on the first read of . - private protected void SetDeferred(TxAction action) => Set(action, DeferredReason); + private protected void SetDeferred(TxAction action, bool invalidHere = false) + { + Set(action, DeferredReason); + IsInvalidHere = invalidHere; + } private protected virtual string FormatDeferredReason() => throw new InvalidOperationException("No deferred reason to format."); } diff --git a/src/Nethermind/Nethermind.Consensus/Processing/BlockchainProcessor.cs b/src/Nethermind/Nethermind.Consensus/Processing/BlockchainProcessor.cs index 26a6bd29a63a..15fc5490b920 100644 --- a/src/Nethermind/Nethermind.Consensus/Processing/BlockchainProcessor.cs +++ b/src/Nethermind/Nethermind.Consensus/Processing/BlockchainProcessor.cs @@ -167,7 +167,7 @@ private void OnBlockExecuted(object? sender, BlockExecutedEventArgs e) Hash256 hash = block.Hash!; if (_inFlight.TryGetValue(hash, out InFlightBlock? inFlight)) inFlight.MarkExecuted(); - BlockVerdictEventArgs verdict = new(hash, block.IsInclusionListSatisfied ? ProcessingResult.Success : ProcessingResult.InclusionListUnsatisfied); + BlockVerdictEventArgs verdict = new(hash, ProcessingResult.Success); try { BlockExecuted?.Invoke(this, verdict); @@ -388,9 +388,7 @@ private async ValueTask Enqueue(Block block, ProcessingOptions processingOptions if (_logger.IsTrace) _logger.Trace($"Enqueuing a new block {block.ToString(Block.Format.Short)} for processing."); Hash256? blockHash = block.Hash!; - // InclusionListTransactions aren't in RLP, so a hash-only ref re-resolved from the DB would drop - // them and pass a censoring payload. - BlockRef blockRef = _currentRecoveryQueueSize >= SoftMaxRecoveryQueueSizeInTx && block.InclusionListTransactions is null + BlockRef blockRef = _currentRecoveryQueueSize >= SoftMaxRecoveryQueueSizeInTx ? new BlockRef(blockHash, processingOptions) : new BlockRef(block, processingOptions); ProcessingWork work = new(blockRef, ParallelUnbalancedWork.GetCurrentGroup(), allowSynchronousProcessing); @@ -705,11 +703,6 @@ private void ProcessBlocks() { NotifyFailedOrSkipped(blockRef, block, error); } - else if (!processedBlock.IsInclusionListSatisfied) - { - // The block was committed normally; signal the CL via newPayload status only. - NotifyInclusionListUnsatisfied(blockRef, processedBlock); - } else { if (isTrace) TraceProcessed(block); @@ -762,13 +755,6 @@ void NotifyFailedOrSkipped(BlockRef blockRef, Block block, string error) OnBlockRemoved(new BlockRemovedEventArgs(blockRef.BlockHash, ProcessingResult.ProcessingError, error), processed: true); } - [MethodImpl(MethodImplOptions.NoInlining)] - void NotifyInclusionListUnsatisfied(BlockRef blockRef, Block block) - { - if (_logger.IsTrace) _logger.Trace($"Inclusion list unsatisfied for block {block.ToString(Block.Format.Full)}"); - OnBlockRemoved(new BlockRemovedEventArgs(blockRef.BlockHash, ProcessingResult.InclusionListUnsatisfied), processed: true); - } - // Reported by the catch below, which every other failure here goes through too: reporting twice would take a // second copy off whatever entry the hash names by then, and after a re-enqueue that is a live one. [DoesNotReturn] diff --git a/src/Nethermind/Nethermind.Consensus/Processing/BranchProcessor.cs b/src/Nethermind/Nethermind.Consensus/Processing/BranchProcessor.cs index 97b10165dec5..a6d4933a0b0a 100644 --- a/src/Nethermind/Nethermind.Consensus/Processing/BranchProcessor.cs +++ b/src/Nethermind/Nethermind.Consensus/Processing/BranchProcessor.cs @@ -17,9 +17,6 @@ using Nethermind.Evm.State; using Nethermind.Evm.Tracing; using Nethermind.Logging; -using Nethermind.Serialization.Rlp.Eip7928; -using Nethermind.Serialization.Rlp; -using Nethermind.State; namespace Nethermind.Consensus.Processing; @@ -28,16 +25,12 @@ public class BranchProcessor( ISpecProvider specProvider, IWorldState stateProvider, IBlockhashProvider blockhashProvider, - IInclusionListSatisfactionChecker inclusionListSatisfactionChecker, ILogManager logManager, - IWorldStateManager worldStateManager, IBlockCachePreWarmer? preWarmer = null) : IBranchProcessor { private readonly ILogger _logger = logManager.GetClassLogger(); - private readonly Lazy _inclusionListParentState = new(worldStateManager.CreateResettableWorldState); - private const int MaxUncommittedBlocks = 64; public event EventHandler? BlockExecuted; @@ -58,10 +51,6 @@ private void PreCommitBlock(BlockHeader block) private IDisposable BeginTargetScope(Block targetBlock) => stateProvider.BeginScopeAtTarget(targetBlock.Header); - private IWorldStateScopeProvider.IScope OpenInclusionListParentScope(BlockHeader? parent) - => _inclusionListParentState.Value.TryBeginScope(parent, new LocalMetrics(), out IWorldStateScopeProvider.IScope? scope) - ? scope : throw new StateNotRetainedException("Parent state is unavailable for inclusion-list validation"); - public Block[] Process(BlockHeader? baseBlock, IReadOnlyList suggestedBlocks, ProcessingOptions options, IBlockTracer blockTracer, CancellationToken token = default) { if (suggestedBlocks.Count == 0) return []; @@ -101,21 +90,11 @@ public Block[] Process(BlockHeader? baseBlock, IReadOnlyList suggestedBlo Exception? processingException = null; bool verdictGiven = false; - bool useBalForInclusionList = false; - bool? boundaryInclusionListSatisfied = null; - // Production, tracing and simulation do not report inclusion-list compliance. - bool checkInclusionList = !options.ContainsFlag(ProcessingOptions.NoValidation); - // Subscribe to cancel background work (prewarmer, prefetch) once transactions finish, // freeing the thread pool for parallel post-tx work (blooms, receipts root, state root). // The handler captures backgroundCancellation by reference, so it always cancels the current CTS. - void OnTransactionsExecuted(Block processedBlock) - { - backgroundCancellation?.Cancel(); - if (checkInclusionList && !useBalForInclusionList && suggestedBlock.InclusionListTransactions is { Length: > 0 }) - boundaryInclusionListSatisfied = inclusionListSatisfactionChecker.IsSatisfied(processedBlock, suggestedBlock, stateProvider); - } - blockProcessor.TransactionsExecuted += OnTransactionsExecuted; + void CancelBackgroundWork(Block _) => backgroundCancellation?.Cancel(); + blockProcessor.TransactionsExecuted += CancelBackgroundWork; try { @@ -133,13 +112,14 @@ void OnTransactionsExecuted(Block processedBlock) BlockHeader? preBlockBaseBlock = baseBlock; bool notReadOnly = !options.ContainsFlag(ProcessingOptions.ReadOnlyChain); + // Production, tracing and eth_simulate are never put to an inclusion check. + bool recordGasUsedBefore = !options.ContainsFlag(ProcessingOptions.NoValidation); int blocksCount = suggestedBlocks.Count; Block[] processedBlocks = new Block[blocksCount]; for (int i = 0; i < blocksCount; i++) { suggestedBlock = suggestedBlocks[i]; - boundaryInclusionListSatisfied = null; using ParallelUnbalancedWork.WorkerScope workers = workerGroup.Enter(); if (i > 0) { @@ -161,8 +141,6 @@ void OnTransactionsExecuted(Block processedBlock) BlockProcessing?.Invoke(this, new BlockEventArgs(suggestedBlock)); } - useBalForInclusionList = checkInclusionList && suggestedBlock.InclusionListTransactions is { Length: > 0 } - && spec.BlockLevelAccessListsEnabled && !suggestedBlock.IsGenesis; ProcessingOptions blockOptions = blockTracer == NullBlockTracer.Instance ? options : options | ProcessingOptions.ForceSequentialBlockAccessList; @@ -197,36 +175,16 @@ worldStateCloser is not null && if (processedBlock.GasUsed == 0) processedBlock.Header.GasUsedPerDimension ??= (0, 0); suggestedBlock.Header.GasUsedPerDimension = processedBlock.Header.GasUsedPerDimension; - // Finalized BAL values include post-execution credits; reverse them only for accounts the checker reads. - bool inclusionListSatisfied = true; - if (useBalForInclusionList) - { - IWorldStateScopeProvider.IScope? parentScope = null; - try - { - InclusionListCommittedState boundaryState = new(stateProvider, (uint)processedBlock.Transactions.Length + 1, - () => processedBlock.BlockAccessList ?? (processedBlock.EncodedBlockAccessList is { } encoded - ? BlockAccessListDecoder.Instance.Decode(encoded) - : processedBlock.GeneratedBlockAccessList is { } generated - ? BlockAccessListDecoder.Instance.Decode(BlockAccessListDecoder.EncodeToBytes(generated), RlpBehaviors.TrustedInput) : null), - () => new ScopeReadOnlyStateProvider(parentScope ??= OpenInclusionListParentScope(preBlockBaseBlock))); - inclusionListSatisfied = inclusionListSatisfactionChecker.IsSatisfied(processedBlock, suggestedBlock, boundaryState); - if (!boundaryState.Available) throw new InvalidOperationException("Inclusion-list transaction-boundary state is unavailable"); - } - finally - { - parentScope?.Dispose(); - } - } - else if (checkInclusionList && suggestedBlock.InclusionListTransactions is { Length: > 0 }) + // EIP-7805 fits an omission claim before the end of the payload against the gas used before its + // index, which only execution records. A deferred inclusion check reads it off the suggested block. + if (recordGasUsedBefore) { - inclusionListSatisfied = boundaryInclusionListSatisfied - ?? throw new InvalidOperationException("Inclusion list was not checked after transactions"); + suggestedBlock.GasUsedBeforeTransactions = Eip8369Profile2.IsActive(spec) + ? InclusionListValidator.GasUsedBeforeEachTransaction(processedBlock, receipts) + : null; } - processedBlock.IsInclusionListSatisfied = inclusionListSatisfied; - suggestedBlock.IsInclusionListSatisfied = inclusionListSatisfied; - // The verdict is final here: the roots matched and the inclusion list is judged. The prewarm join, + // The verdict is final here: the roots matched. The prewarm join, // the commit and the chain update below are what the block's readers need, not its validity, so // whoever only waits for the verdict is told now rather than after them. Only the last block of the // branch: an earlier one can still be discarded with the branch if a later one is invalid, and it @@ -292,7 +250,7 @@ worldStateCloser is not null && { try { - blockProcessor.TransactionsExecuted -= OnTransactionsExecuted; + blockProcessor.TransactionsExecuted -= CancelBackgroundWork; worldStateCloser?.Dispose(); } finally diff --git a/src/Nethermind/Nethermind.Consensus/Processing/IBlockProcessingQueue.cs b/src/Nethermind/Nethermind.Consensus/Processing/IBlockProcessingQueue.cs index 97b900dae7c3..a58a31c9b7ac 100644 --- a/src/Nethermind/Nethermind.Consensus/Processing/IBlockProcessingQueue.cs +++ b/src/Nethermind/Nethermind.Consensus/Processing/IBlockProcessingQueue.cs @@ -45,9 +45,8 @@ public interface IBlockProcessingQueue event EventHandler BlockAdded; /// /// Raised when a queued block has been executed and validated, before it is committed and before - /// . The result is or - /// ; every other outcome arrives through - /// alone. + /// . The result is ; every other outcome + /// arrives through alone. /// /// /// Defaulted so an implementation outside this repository keeps compiling. One that does not raise it leaves diff --git a/src/Nethermind/Nethermind.Consensus/Processing/IInclusionListSatisfactionChecker.cs b/src/Nethermind/Nethermind.Consensus/Processing/IInclusionListSatisfactionChecker.cs deleted file mode 100644 index 9fc63bb9bdc3..000000000000 --- a/src/Nethermind/Nethermind.Consensus/Processing/IInclusionListSatisfactionChecker.cs +++ /dev/null @@ -1,15 +0,0 @@ -// SPDX-FileCopyrightText: 2026 Demerzel Solutions Limited -// SPDX-License-Identifier: LGPL-3.0-only - -using Nethermind.Core; -using Nethermind.Evm.State; - -namespace Nethermind.Consensus.Processing; - -/// Reports whether a processed block honoured the inclusion list it was suggested with (EIP-7805). -/// Not block validation: an unsatisfied inclusion list leaves the block valid and committed. Runs -/// inside block processing because appendability is judged before withdrawals and request system calls. -public interface IInclusionListSatisfactionChecker -{ - bool IsSatisfied(Block processedBlock, Block suggestedBlock, IReadOnlyStateProvider worldState); -} diff --git a/src/Nethermind/Nethermind.Consensus/Processing/IProfile2EligibilityReplayer.cs b/src/Nethermind/Nethermind.Consensus/Processing/IProfile2EligibilityReplayer.cs new file mode 100644 index 000000000000..a524148917f0 --- /dev/null +++ b/src/Nethermind/Nethermind.Consensus/Processing/IProfile2EligibilityReplayer.cs @@ -0,0 +1,28 @@ +// SPDX-FileCopyrightText: 2026 Demerzel Solutions Limited +// SPDX-License-Identifier: LGPL-3.0-only + +using System.Collections.Generic; +using Nethermind.Core; +using Nethermind.Core.Specs; + +namespace Nethermind.Consensus.Processing; + +/// Decides the state-dependent half of EIP-8369 Profile 2 for an omitted inclusion-list entry. +public interface IProfile2EligibilityReplayer +{ + /// Whether 's protocol-validated frame signatures verify, as the + /// EIP-8369 budget fill needs before it debits the validation prefix cost. + bool AreSignaturesValid(Transaction transaction, IReleaseSpec spec); + + /// Whether each Profile 2 candidate is eligible when inserted at its index of . + /// + /// A verdict is false only when the replay proves the candidate ineligible. A replay this node cannot + /// run answers null: EIP-8369 makes local data availability no omission excuse, so the caller must + /// neither excuse the omission nor settle on a verdict, and asks again once the state is available. The block's + /// state is reconstructed once for the whole batch, so callers should pass every request for a block together. + /// + /// Each candidate with the number of 's transactions that + /// precede its insertion point, in [0, len(block.transactions)]. + /// One verdict per request, in order; null where the replay could not run. + bool?[] AreEligible(Block block, IReadOnlyList<(Transaction Transaction, int Index)> requests, IReleaseSpec spec); +} diff --git a/src/Nethermind/Nethermind.Consensus/Processing/InclusionListSatisfactionChecker.cs b/src/Nethermind/Nethermind.Consensus/Processing/InclusionListSatisfactionChecker.cs deleted file mode 100644 index b0db3e35294f..000000000000 --- a/src/Nethermind/Nethermind.Consensus/Processing/InclusionListSatisfactionChecker.cs +++ /dev/null @@ -1,22 +0,0 @@ -// SPDX-FileCopyrightText: 2026 Demerzel Solutions Limited -// SPDX-License-Identifier: LGPL-3.0-only - -using Nethermind.Consensus.Validators; -using Nethermind.Core; -using Nethermind.Core.Specs; -using Nethermind.Evm.State; -using Nethermind.TxPool; - -namespace Nethermind.Consensus.Processing; - -/// -public sealed class InclusionListSatisfactionChecker(ISpecProvider specProvider, ITxValidator txValidator) - : IInclusionListSatisfactionChecker -{ - public bool IsSatisfied(Block processedBlock, Block suggestedBlock, IReadOnlyStateProvider worldState) - { - IReleaseSpec spec = specProvider.GetSpec(processedBlock.Header); - // P2P-decoded blocks legitimately have null IL; IsSatisfied treats null as "not applicable". - return InclusionListValidator.IsSatisfied(processedBlock, suggestedBlock.InclusionListTransactions, worldState, spec, txValidator); - } -} diff --git a/src/Nethermind/Nethermind.Consensus/Processing/MempoolStatePrewarmer.cs b/src/Nethermind/Nethermind.Consensus/Processing/MempoolStatePrewarmer.cs index 6b619a9458ad..a0668c083429 100644 --- a/src/Nethermind/Nethermind.Consensus/Processing/MempoolStatePrewarmer.cs +++ b/src/Nethermind/Nethermind.Consensus/Processing/MempoolStatePrewarmer.cs @@ -113,7 +113,7 @@ private void OnBlockQueued(object? sender, BlockEventArgs e) private void OnBlockRemoved(object? sender, BlockRemovedEventArgs e) { // Processed and committed, so a new head, if any, starts the next session; or the queue itself failed, as at shutdown. - if (e.ProcessingResult is ProcessingResult.Success or ProcessingResult.InclusionListUnsatisfied or ProcessingResult.QueueException) return; + if (e.ProcessingResult is ProcessingResult.Success or ProcessingResult.QueueException) return; // Read before the head: a head published after this read must win, so the restart claims the next generation // only if none has been taken since, and a newer head's session is never displaced by the old head's. diff --git a/src/Nethermind/Nethermind.Consensus/Processing/Profile2EligibilityReplayer.cs b/src/Nethermind/Nethermind.Consensus/Processing/Profile2EligibilityReplayer.cs new file mode 100644 index 000000000000..e76d878b4ae4 --- /dev/null +++ b/src/Nethermind/Nethermind.Consensus/Processing/Profile2EligibilityReplayer.cs @@ -0,0 +1,236 @@ +// SPDX-FileCopyrightText: 2026 Demerzel Solutions Limited +// SPDX-License-Identifier: LGPL-3.0-only + +using System; +using System.Collections.Generic; +using System.Linq; +using System.IO; +using System.Threading; +using Nethermind.Blockchain; +using Nethermind.Core; +using Nethermind.Core.BlockAccessLists; +using Nethermind.Core.Caching; +using Nethermind.Core.Crypto; +using Nethermind.Core.Exceptions; +using Nethermind.Core.Specs; +using Nethermind.Crypto; +using Nethermind.Evm.Precompiles; +using Nethermind.Evm.State; +using Nethermind.Evm.Tracing; +using Nethermind.Evm.TransactionProcessing; +using Nethermind.Int256; +using Nethermind.Logging; +using Nethermind.State; + +namespace Nethermind.Consensus.Processing; + +/// +/// +/// EIP-7805 § Profile 2 predicates: state at the evaluation index is the parent state plus the EIP-7928 access list's +/// changes before that index, pre-execution system updates included. The changes are written into a +/// throwaway env opened at the parent, then the validation prefix runs under the Profile 2 trace rules. +/// is not reused: it rejects every account the list omits, +/// and an omitted transaction's sender and payer usually are such accounts. +/// The prefix runs under MAX_VERIFY_GAS_PER_TX rather than EIP-8141's mempool MAX_VERIFY_GAS, +/// against the block's own header, so an EIP-8272 recent_root_verify frame reads the block's slot. +/// +public sealed class Profile2EligibilityReplayer( + IReadOnlyTxProcessingEnvFactory envFactory, + IEthereumEcdsa ecdsa, + ILogManager logManager) : IProfile2EligibilityReplayer, IDisposable +{ + private readonly ILogger _logger = logManager.GetClassLogger(); + private readonly Lock _lock = new(); + private IReadOnlyTxProcessorSource? _source; + + // A verdict is a function of the envelope bytes the hash commits to, and of whether P256VERIFY exists, so the + // builder's fill and the validation of the block it built share one verification per entry. + private readonly LruCache _signaturesWithP256 = new(SignatureCacheSize, "Profile2SignaturesWithP256"); + private readonly LruCache _signaturesWithoutP256 = new(SignatureCacheSize, "Profile2SignaturesWithoutP256"); + private const int SignatureCacheSize = 4096; + private bool _disposed; + + public bool AreSignaturesValid(Transaction transaction, IReleaseSpec spec) + { + if (transaction.FrameSignatures is not { Length: > 0 }) return true; + if (transaction.Hash is not { } hash) return AreSignaturesValid(transaction, ecdsa, spec); + + LruCache cache = spec.IsPrecompile(FrameTxSignatureValidator.P256VerifyPrecompileAddress) + ? _signaturesWithP256 + : _signaturesWithoutP256; + if (cache.TryGet(hash, out bool valid)) return valid; + + valid = AreSignaturesValid(transaction, ecdsa, spec); + cache.Set(hash, valid); + return valid; + } + + /// + public static bool AreSignaturesValid(Transaction transaction, IEthereumEcdsa ecdsa, IReleaseSpec spec) + { + if (transaction.FrameSignatures is not { Length: > 0 }) return true; + + IPrecompile? p256Precompile = spec.IsPrecompile(FrameTxSignatureValidator.P256VerifyPrecompileAddress) + ? SecP256r1Precompile.Instance + : null; + return FrameTxSignatureValidator.Validate(transaction, ecdsa, p256Precompile, spec, out _); + } + + public bool?[] AreEligible(Block block, IReadOnlyList<(Transaction Transaction, int Index)> requests, IReleaseSpec spec) + { + bool?[] eligible = new bool?[requests.Count]; + if (requests.Count == 0) return eligible; + if (block.BlockAccessList is not { } blockAccessList) return Undecided(eligible, 0, "the block carries no access list"); + + // Ascending index, so the state advances through the access list once for the whole batch. + int[] order = new int[requests.Count]; + for (int i = 0; i < order.Length; i++) order[i] = i; + Array.Sort(order, (x, y) => requests[x].Index != requests[y].Index ? requests[x].Index.CompareTo(requests[y].Index) : x.CompareTo(y)); + + lock (_lock) + { + if (_disposed) return Undecided(eligible, 0, "the replayer is disposed"); + + int next = 0; + try + { + IReadOnlyTxProcessorSource source = _source ??= envFactory.Create(); + if (!source.TryBuildAtTarget(block.Header, out IReadOnlyTxProcessingScope? scope)) + return Undecided(eligible, 0, "the parent state is unavailable"); + + using (scope) + { + IWorldState state = scope.WorldState; + ITransactionProcessor processor = scope.TransactionProcessor; + processor.SetBlockExecutionContext(block.Header); + AccessListCursor cursor = new(blockAccessList); + for (; next < order.Length; next++) + { + (Transaction transaction, int index) = requests[order[next]]; + cursor.ApplyBefore(state, (uint)index + 1, spec); + eligible[order[next]] = Replay(state, processor, transaction, spec); + } + } + } + catch (Exception e) when (e is IInternalNethermindException or StateUnavailableException or ObjectDisposedException or IOException) + { + // A fault this node is answerable for leaves every verdict not yet reached undecided. + for (int i = next; i < order.Length; i++) eligible[order[i]] = null; + if (_logger.IsDebug) _logger.Debug($"EIP-8369 replay undecided: {e.Message}."); + } + } + return eligible; + } + + /// Runs one candidate's checks against , which it leaves as found. + private bool Replay(IWorldState state, ITransactionProcessor processor, Transaction transaction, IReleaseSpec spec) + { + if (transaction.SenderAddress is not { } sender) return false; + if (!IsNonceValid(state, transaction, sender)) return false; + + FrameTxValidationTracer tracer = new(sender, Eip8141Constants.ExpiryVerifierAddress, state, spec, + maxVerifyGas: Eip8369Constants.MaxVerifyGasPerTx, + payer: sender, storageSlotBound: Eip8369Constants.AaVopsSlotCount, createInDeployFrame: true, + maxCodeBodies: Eip8369Constants.MaxReplayCodeBodies, maxCodeBytes: Eip8369Constants.MaxReplayCodeBytes); + try + { + // Prefix-only simulation restores its own snapshot, so the reconstructed state serves the next candidate. + TransactionResult result = processor.Process(transaction, tracer, ExecutionOptions.FrameValidationPrefixOnly | ExecutionOptions.FramePrefixAtBlockBaseFee); + return !tracer.Violated && result && tracer.Payer is not null; + } + catch (OperationCanceledException) when (tracer.Violated) + { + return false; + } + catch (Exception e) when (e is not OperationCanceledException and not OutOfMemoryException + and not IInternalNethermindException and not StateUnavailableException and not ObjectDisposedException and not IOException) + { + // The prefix is the expected source of a throw, as in FrameTxPrefixSimulator. + if (_logger.IsDebug) _logger.Debug($"EIP-8369 replay of {transaction.Hash} threw; judging it ineligible. {e}"); + return false; + } + } + + /// Writes an access list's changes into a state in block-access-index order, each exactly once. + /// Anything the list omits is unchanged by the block, so the parent state already holds it, and + /// advancing from one evaluation index to the next applies only the changes between them. + private sealed class AccessListCursor + { + private List<(uint Index, int Kind, int Item, int Change, ReadOnlyAccountChanges Account)> _changes = []; + private int _next; + + private const int Balance = 0, Nonce = 1, Code = 2, Storage = 3; + + public AccessListCursor(ReadOnlyBlockAccessList blockAccessList) + { + foreach (ReadOnlyAccountChanges account in blockAccessList.AccountChanges.AsSpan()) + { + for (int i = 0; i < account.BalanceChanges.Length; i++) _changes.Add((account.BalanceChanges[i].Index, Balance, i, 0, account)); + for (int i = 0; i < account.NonceChanges.Length; i++) _changes.Add((account.NonceChanges[i].Index, Nonce, i, 0, account)); + for (int i = 0; i < account.CodeChanges.Length; i++) _changes.Add((account.CodeChanges[i].Index, Code, i, 0, account)); + for (int slot = 0; slot < account.StorageChanges.Length; slot++) + { + StorageChange[] changes = account.StorageChanges[slot].Changes; + for (int i = 0; i < changes.Length; i++) _changes.Add((changes[i].Index, Storage, slot, i, account)); + } + } + // OrderBy is stable, so a field changed twice at one index keeps the list's own order. + _changes = [.. _changes.OrderBy(static c => c.Index)]; + } + + /// Applies every change recorded before not yet applied. + public void ApplyBefore(IWorldState state, uint blockAccessIndex, IReleaseSpec spec) + { + for (; _next < _changes.Count && _changes[_next].Index < blockAccessIndex; _next++) + { + (_, int kind, int item, int change, ReadOnlyAccountChanges account) = _changes[_next]; + Address address = account.Address; + state.CreateAccountIfNotExists(address, UInt256.Zero); + switch (kind) + { + case Balance: + UInt256 target = account.BalanceChanges[item].Value; + UInt256 current = state.GetBalance(address); + if (target > current) state.AddToBalance(address, target - current, spec, out _); + else if (target < current) state.SubtractFromBalance(address, current - target, spec, out _); + break; + case Nonce: + state.SetNonce(address, account.NonceChanges[item].Value); + break; + case Code: + CodeChange code = account.CodeChanges[item]; + state.InsertCode(address, code.CodeHash, code.Code ?? [], spec); + break; + default: + ReadOnlySlotChanges slot = account.StorageChanges[item]; + state.Set(new StorageCell(address, slot.Key), slot.Changes[change].Value); + break; + } + } + } + } + + /// The EIP-8141 account nonce or EIP-8250 keyed nonce check, which prefix simulation leaves to its caller. + private static bool IsNonceValid(IWorldState state, Transaction transaction, Address sender) => + transaction.NonceKeys is { } nonceKeys + ? KeyedNonceManager.IsNonceSetValid(state, sender, nonceKeys, transaction.Nonce) + : state.GetNonce(sender) == transaction.Nonce; + + private bool?[] Undecided(bool?[] eligible, int from, string reason) + { + if (_logger.IsDebug) _logger.Debug($"EIP-8369 replay undecided: {reason}."); + Array.Fill(eligible, null, from, eligible.Length - from); + return eligible; + } + + public void Dispose() + { + lock (_lock) + { + if (_disposed) return; + _disposed = true; + _source?.Dispose(); + _source = null; + } + } +} diff --git a/src/Nethermind/Nethermind.Consensus/Processing/RecoverSignatures.cs b/src/Nethermind/Nethermind.Consensus/Processing/RecoverSignatures.cs index dd323354f811..6b173915157e 100644 --- a/src/Nethermind/Nethermind.Consensus/Processing/RecoverSignatures.cs +++ b/src/Nethermind/Nethermind.Consensus/Processing/RecoverSignatures.cs @@ -46,10 +46,6 @@ public class RecoverSignatures(IEthereumEcdsa? ecdsa, ISpecProvider? specProvide /// public void RecoverDataForTransactionTrace(Block block) { - if (block.InclusionListTransactions is not null) - { - RecoverData(block.InclusionListTransactions, _specProvider.GetSpec(block.Header), skipErrors: true); - } } /// @@ -73,11 +69,6 @@ private void RecoverData(Block block, bool mayDeferToRecoveryInFlight) { RecoverData(txs, AlignedEncodings(txs, block.EncodedTransactions), releaseSpec, skipErrors: false, 0, txs.Length); } - - if (block.InclusionListTransactions is not null) - { - RecoverData(block.InclusionListTransactions, releaseSpec, skipErrors: true); - } } private static bool AllSendersRecovered(ReadOnlySpan txs, bool checkAuthorities) diff --git a/src/Nethermind/Nethermind.Consensus/Producers/BlockToProduce.cs b/src/Nethermind/Nethermind.Consensus/Producers/BlockToProduce.cs index e6f357435aef..5cf10dbb52e3 100644 --- a/src/Nethermind/Nethermind.Consensus/Producers/BlockToProduce.cs +++ b/src/Nethermind/Nethermind.Consensus/Producers/BlockToProduce.cs @@ -7,6 +7,7 @@ using System.Runtime.CompilerServices; using System.Threading; using Nethermind.Core; +using Nethermind.Core.Crypto; //TODO: Redo clique block producer [assembly: InternalsVisibleTo("Nethermind.Consensus.Clique")] @@ -53,12 +54,17 @@ public BlockToProduce(BlockHeader blockHeader, public Transaction[]? InclusionList { get; set; } public CancellationToken AbandonToken { get; internal set; } + /// Hashes of the Profile 2 candidates in the build's inclusion lists that some position admits, each of which the + /// build answers with a claim when it fails to append one; null when there are none. + public IReadOnlySet? InclusionListCandidates { get; set; } + public override Block WithReplacedHeader(BlockHeader newHeader) => new BlockToProduce(newHeader, Transactions, Uncles, Withdrawals) { TransactionsExemptFromByteLimit = TransactionsExemptFromByteLimit, RequiredTransactions = RequiredTransactions, InclusionList = InclusionList, AbandonToken = AbandonToken, + InclusionListCandidates = InclusionListCandidates, }; } } diff --git a/src/Nethermind/Nethermind.Consensus/Producers/PayloadAttributes.cs b/src/Nethermind/Nethermind.Consensus/Producers/PayloadAttributes.cs index fd37a1bc3ba1..b01b282dc57f 100644 --- a/src/Nethermind/Nethermind.Consensus/Producers/PayloadAttributes.cs +++ b/src/Nethermind/Nethermind.Consensus/Producers/PayloadAttributes.cs @@ -6,7 +6,6 @@ using System.Diagnostics.CodeAnalysis; using System.Text; using Nethermind.Core; -using Nethermind.Core.Buffers; using Nethermind.Core.Crypto; using Nethermind.Core.Extensions; using Nethermind.Core.Specs; @@ -26,7 +25,8 @@ public class PayloadAttributes public Hash256? ParentBeaconBlockRoot { get; set; } - public byte[][]? InclusionListTransactions { get; set; } + /// EIP-7805 separate inclusion lists for the build, one per committee position (). + public byte[][][]? InclusionLists { get; set; } public ulong? SlotNumber { get; set; } @@ -95,7 +95,7 @@ protected virtual int ComputePayloadIdMembersSize() => + (ParentBeaconBlockRoot is null ? 0 : Keccak.Size) // parent beacon block root + (SlotNumber is null ? 0 : sizeof(ulong)) // slot number + (TargetGasLimit is null ? 0 : sizeof(ulong)) // target gas limit - + (InclusionListTransactions is null ? 0 : Keccak.Size); // inclusion list digest + + (InclusionLists is null ? 0 : Keccak.Size); // inclusion lists digest protected static string ComputePayloadId(Span inputSpan) { @@ -144,58 +144,38 @@ protected virtual int WritePayloadIdMembers(BlockHeader parentHeader, Span position += sizeof(ulong); } - if (InclusionListTransactions is not null) + // The lists decide what the build must include and, through each position's VERIFY budget fill, what it may + // claim, so builds of the same block under different lists must not share a payload. + if (InclusionLists is not null) { - ComputeInclusionListDigest(InclusionListTransactions).BytesAsSpan.CopyTo(inputSpan.Slice(position, Keccak.Size)); + ComputeInclusionListsDigest(InclusionLists).BytesAsSpan.CopyTo(inputSpan.Slice(position, Keccak.Size)); position += Keccak.Size; } return position; } - /// Largest buffer any inclusion list within the EIP-7805 aggregate bounds can need. - private const long MaxPooledInclusionListDigestBuffer = - Eip7805Constants.MaxAggregateInclusionListBytes - + (long)Eip7805Constants.MaxAggregateInclusionListTransactions * sizeof(uint); - - internal static ValueHash256 ComputeInclusionListDigest(byte[][] inclusionListTransactions) - { - // Length-prefix each entry so [empty, tx1] and [tx1] don't collide on the same payload-id. - long totalLength = 0; - for (int i = 0; i < inclusionListTransactions.Length; i++) - totalLength += sizeof(uint) + (long)(inclusionListTransactions[i]?.Length ?? 0); - - // forkchoiceUpdated keeps an oversized list rather than rejecting it, so stream anything past - // the aggregate bounds instead of renting a buffer sized by the engine body cap. - if (totalLength > MaxPooledInclusionListDigestBuffer) - return ComputeInclusionListDigestStreaming(inclusionListTransactions); - - using ArrayPoolDisposableReturn _ = ArrayPoolDisposableReturn.Rent((int)totalLength, out byte[] buffer); - Span span = buffer.AsSpan(0, (int)totalLength); - int position = 0; - for (int i = 0; i < inclusionListTransactions.Length; i++) - { - byte[] entry = inclusionListTransactions[i] ?? []; - BinaryPrimitives.WriteUInt32BigEndian(span.Slice(position, sizeof(uint)), (uint)entry.Length); - position += sizeof(uint); - entry.CopyTo(span[position..]); - position += entry.Length; - } - - return ValueKeccak.Compute(span); - } - - /// Same byte sequence and digest as the pooled path, assembled incrementally. - internal static ValueHash256 ComputeInclusionListDigestStreaming(byte[][] inclusionListTransactions) + /// A digest of that keeps list boundaries, positions and entry order. + /// Every list and entry is length-prefixed, so [[a], []] and [[], [a]] cannot collide. + /// Streamed: forkchoiceUpdated validates the lists' structure, not their total size. + internal static ValueHash256 ComputeInclusionListsDigest(byte[][][] inclusionLists) { Span lengthPrefix = stackalloc byte[sizeof(uint)]; KeccakHash hash = KeccakHash.Create(); - for (int i = 0; i < inclusionListTransactions.Length; i++) + BinaryPrimitives.WriteUInt32BigEndian(lengthPrefix, (uint)inclusionLists.Length); + hash.Update(lengthPrefix); + foreach (byte[][]? inclusionList in inclusionLists) { - byte[] entry = inclusionListTransactions[i] ?? []; - BinaryPrimitives.WriteUInt32BigEndian(lengthPrefix, (uint)entry.Length); + byte[][] entries = inclusionList ?? []; + BinaryPrimitives.WriteUInt32BigEndian(lengthPrefix, (uint)entries.Length); hash.Update(lengthPrefix); - if (entry.Length > 0) hash.Update(entry); + foreach (byte[]? entry in entries) + { + byte[] bytes = entry ?? []; + BinaryPrimitives.WriteUInt32BigEndian(lengthPrefix, (uint)bytes.Length); + hash.Update(lengthPrefix); + if (bytes.Length > 0) hash.Update(bytes); + } } return hash.GenerateValueHash(); @@ -302,9 +282,8 @@ public virtual PayloadAttributesValidationResult Validate( >= PayloadAttributesVersions.V3 when ParentBeaconBlockRoot is null => $"{nameof(ParentBeaconBlockRoot)} must be provided", >= PayloadAttributesVersions.V4 when SlotNumber is null => $"{nameof(SlotNumber)} must be provided", >= PayloadAttributesVersions.V4 when TargetGasLimit is null => $"{nameof(TargetGasLimit)} must be provided", - // bogota.md PayloadAttributesV5 appends this field unconditionally; an empty array is valid, - // an absent one is not. - >= PayloadAttributesVersions.V5 when InclusionListTransactions is null => $"{nameof(InclusionListTransactions)} must be provided", + // bogota.md PayloadAttributesV5 appends this field unconditionally, as one list per committee position. + >= PayloadAttributesVersions.V5 => Core.InclusionLists.Validate(InclusionLists), _ => null }; } @@ -317,7 +296,7 @@ public static class PayloadAttributesExtensions public static int GetVersion(this PayloadAttributes executionPayload) => executionPayload switch { - { InclusionListTransactions: not null } => PayloadAttributesVersions.V5, + { InclusionLists: not null } => PayloadAttributesVersions.V5, { SlotNumber: not null } or { TargetGasLimit: not null } => PayloadAttributesVersions.V4, { ParentBeaconBlockRoot: not null } => PayloadAttributesVersions.V3, { Withdrawals: not null } => PayloadAttributesVersions.V2, diff --git a/src/Nethermind/Nethermind.Consensus/Transactions/IInclusionListTxSource.cs b/src/Nethermind/Nethermind.Consensus/Transactions/IInclusionListTxSource.cs index 33002681033a..b544e6c468f2 100644 --- a/src/Nethermind/Nethermind.Consensus/Transactions/IInclusionListTxSource.cs +++ b/src/Nethermind/Nethermind.Consensus/Transactions/IInclusionListTxSource.cs @@ -1,14 +1,22 @@ // SPDX-FileCopyrightText: 2026 Demerzel Solutions Limited // SPDX-License-Identifier: LGPL-3.0-only +using System.Collections.Generic; +using Nethermind.Consensus.Producers; +using Nethermind.Core.Crypto; using Nethermind.Core.Specs; namespace Nethermind.Consensus.Transactions; -/// Feeds the inclusion list supplied by engine_forkchoiceUpdatedV5 into block production (EIP-7805). +/// Feeds the inclusion lists supplied by engine_forkchoiceUpdatedV5 into block production (EIP-7805). public interface IInclusionListTxSource : ITxSource { - /// Retains the list for the build identified by the - /// array instance, which is the key GetTransactions looks it up by. - void Set(byte[][] inclusionListTransactions, IReleaseSpec spec); + /// Retains the separate lists for the build identified by the + /// array instance, which is the key GetTransactions looks them up by. + /// One structurally valid list per committee position (). + void Set(byte[][][] inclusionLists, IReleaseSpec spec); + + /// The build's Profile 2 candidates that some committee position's VERIFY budget fill admits, so the + /// build answers each it fails to append with an omission claim; null when there are none. + IReadOnlySet? GetProfile2Candidates(PayloadAttributes? payloadAttributes, ulong maxVerifyGasPerTx); } diff --git a/src/Nethermind/Nethermind.Consensus/Transactions/InclusionListTxSource.cs b/src/Nethermind/Nethermind.Consensus/Transactions/InclusionListTxSource.cs index 5f9f5ffae0d0..ff906cc64475 100644 --- a/src/Nethermind/Nethermind.Consensus/Transactions/InclusionListTxSource.cs +++ b/src/Nethermind/Nethermind.Consensus/Transactions/InclusionListTxSource.cs @@ -3,10 +3,16 @@ using System; using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; using System.Runtime.CompilerServices; +using Nethermind.Config; using Nethermind.Consensus.Decoders; +using Nethermind.Consensus.Processing; using Nethermind.Consensus.Producers; +using Nethermind.Consensus.Validators; using Nethermind.Core; +using Nethermind.Core.Crypto; using Nethermind.Core.Specs; using Nethermind.Crypto; using Nethermind.Logging; @@ -19,46 +25,100 @@ public class InclusionListTxSource( IEthereumEcdsa ecdsa, ISpecProvider specProvider, ITxValidator txValidator, - ILogManager logManager) : IInclusionListTxSource + ILogManager logManager, + IProfile2EligibilityReplayer? profile2Replayer = null, + IBlocksConfig? blocksConfig = null) : IInclusionListTxSource { // Lazy defaults to ExecutionAndPublication: constructed once even under racing FCUs. private readonly Lazy _decoder = new(() => new InclusionListDecoder(ecdsa, specProvider, logManager)); private readonly ILogger _logger = logManager.GetClassLogger(); - // Keyed by the build's PayloadAttributes array so a concurrent FCU can't leak another build's IL; + // Keyed by the build's PayloadAttributes array so a concurrent FCU can't leak another build's lists; // weak keys collect with the build. - private readonly ConditionalWeakTable> _decodedByAttributes = []; + private readonly ConditionalWeakTable> _decodedByAttributes = []; + /// A build's lists decoded twice over: as one deduplicated sequence ordered for production, and + /// position by position for the per-IL VERIFY budget fill. + private sealed record DecodedInclusionLists(Transaction[] ForProduction, Transaction[][] ByPosition, IReleaseSpec Spec) + { + /// The fill under the cap it ran with; every improvement of one build asks again. + public (ulong MaxVerifyGasPerTx, IReadOnlySet? Candidates)? Profile2Candidates; + } + + private readonly ulong _maxVerifyGasPerTx = blocksConfig?.FocilProfile2MaxVerifyGas ?? Eip8369Constants.MaxVerifyGasPerTx; + + /// + /// Once Profile 2 is active, a frame transaction no committee position's VERIFY budget fill admits is + /// not offered: its omission is excused (EIP-8369 § Profile 2 omission claims), so the build never runs its VERIFY. // gasLimit is ignored: the downstream tx selection pipeline enforces it. public IEnumerable GetTransactions(BlockHeader parent, BlockHeader targetBlock, ulong gasLimit, PayloadAttributes? payloadAttributes = null, bool filterSource = false) { - if (payloadAttributes?.InclusionListTransactions is not { Length: > 0 } il) return []; - if (!_decodedByAttributes.TryGetValue(il, out Lazy? decoded)) + if (!TryGetDecoded(payloadAttributes, out DecodedInclusionLists? decoded)) return []; + if (!Eip8369Profile2.IsActive(decoded.Spec)) return decoded.ForProduction; + + IReadOnlySet? admitted = GetProfile2Candidates(payloadAttributes, _maxVerifyGasPerTx); + return decoded.ForProduction.Where(tx => !tx.SupportsFrames || (admitted is not null && tx.Hash is not null && admitted.Contains(tx.Hash))); + } + + public IReadOnlySet? GetProfile2Candidates(PayloadAttributes? payloadAttributes, ulong maxVerifyGasPerTx) + { + if (!TryGetDecoded(payloadAttributes, out DecodedInclusionLists? decoded)) return null; + if (decoded.Profile2Candidates is { } cached && cached.MaxVerifyGasPerTx == maxVerifyGasPerTx) return cached.Candidates; + + IReleaseSpec spec = decoded.Spec; + // EIP-7805: before Profile 2 is active no entry is a candidate, so the build claims nothing. + if (!Eip8369Profile2.IsActive(spec)) return null; + Func signaturesValid = profile2Replayer is not null + ? tx => profile2Replayer.AreSignaturesValid(tx, spec) + : tx => Profile2EligibilityReplayer.AreSignaturesValid(tx, ecdsa, spec); + HashSet admitted = Eip8369Profile2.AdmitByVerifyBudget(InclusionLists.InFillOrder(decoded.ByPosition), maxVerifyGasPerTx, signaturesValid, + tx => InclusionListValidator.Profile2StaticChecks.IsWellFormed(tx, spec)); + IReadOnlySet? candidates = admitted.Count > 0 ? admitted : null; + decoded.Profile2Candidates = (maxVerifyGasPerTx, candidates); + return candidates; + } + + private bool TryGetDecoded(PayloadAttributes? payloadAttributes, [NotNullWhen(true)] out DecodedInclusionLists? decoded) + { + decoded = null; + if (payloadAttributes?.InclusionLists is not { } inclusionLists || IsEmpty(inclusionLists)) return false; + if (!_decodedByAttributes.TryGetValue(inclusionLists, out Lazy? lazy)) { - // A miss means Set was never called for these attributes, e.g. an oversized IL that - // engine_forkchoiceUpdatedV5 already warned about; debug-level as this runs once per improvement. - if (_logger.IsDebug) _logger.Debug($"No inclusion list for this build ({il.Length} entries) — building without it."); - return []; + // A miss means Set was never called for these attributes; debug-level as this runs once per improvement. + if (_logger.IsDebug) _logger.Debug("No inclusion lists for this build — building without them."); + return false; } try { - return decoded.Value; + decoded = lazy.Value; + return true; } catch (Exception ex) when (ex is RlpReaderException or ArgumentException) { - // Lazy caches the failure, so a malformed list is reported once per build, not per improvement. - if (_logger.IsWarn) _logger.Warn($"Discarding malformed inclusion list ({ex.GetType().Name}: {ex.Message}); building without it."); - return []; + // Lazy caches the failure, so malformed lists are reported once per build, not per improvement. + if (_logger.IsWarn) _logger.Warn($"Discarding malformed inclusion lists ({ex.GetType().Name}: {ex.Message}); building without them."); + return false; } } + private static bool IsEmpty(byte[][][] inclusionLists) + { + foreach (byte[][]? inclusionList in inclusionLists) + if (inclusionList is { Length: > 0 }) return false; + return true; + } + /// /// Decoding and sender recovery are deferred to the first call, so /// a forkchoice update that never starts a build pays nothing. - public void Set(byte[][] inclusionListTransactions, IReleaseSpec spec) - => _decodedByAttributes.AddOrUpdate(inclusionListTransactions, - new Lazy(() => OrderForProduction(FilterUnusable(_decoder.Value.DecodeAndRecover(inclusionListTransactions, spec), spec)))); + public void Set(byte[][][] inclusionLists, IReleaseSpec spec) + => _decodedByAttributes.AddOrUpdate(inclusionLists, + new Lazy(() => + { + Transaction[][] byPosition = _decoder.Value.DecodeAndRecover(inclusionLists, spec); + return new DecodedInclusionLists(OrderForProduction(FilterUnusable(InclusionLists.Distinct(byPosition), spec)), byPosition, spec); + })); // Nonce order within a sender lets a shuffled IL go in on the first pass. // Ordering by first-appearance rather than address avoids favouring low-address senders. diff --git a/src/Nethermind/Nethermind.Consensus/Validators/InclusionListValidator.cs b/src/Nethermind/Nethermind.Consensus/Validators/InclusionListValidator.cs index 26112669a7ac..8f8ad05a04cc 100644 --- a/src/Nethermind/Nethermind.Consensus/Validators/InclusionListValidator.cs +++ b/src/Nethermind/Nethermind.Consensus/Validators/InclusionListValidator.cs @@ -5,6 +5,7 @@ using System.Buffers; using System.Collections.Generic; using System.Runtime.InteropServices; +using Nethermind.Consensus.Processing; using Nethermind.Core; using Nethermind.Core.Crypto; using Nethermind.Core.Specs; @@ -19,19 +20,50 @@ public static class InclusionListValidator { private const int StackAllocEntries = 256; - public static bool IsSatisfied(Block block, IReadOnlyStateProvider state, IReleaseSpec spec, ITxValidator txValidator) - => IsSatisfied(block, block.InclusionListTransactions, state, spec, txValidator); + /// EIP-7805 is_profile_2_candidate condition 1: a frame transaction's noncryptographic static + /// checks, as registers them for frame transactions less the chain ID, which the + /// replay checks instead, so a wrong chain ID still costs its list's budget. + internal static ITxValidator Profile2StaticChecks { get; } = new CompositeTxValidator( + new ReleaseSpecTxValidator(static spec => spec.IsEip8141Enabled), + NonceCapTxValidator.Instance, + FrameTxFieldsTxValidator.Instance, + FrameTxNonceKeysTxValidator.Instance); - /// Checks appendability against state after transactions, before withdrawals and request system calls. - public static bool IsSatisfied(Block block, Transaction[]? il, IReadOnlyStateProvider state, IReleaseSpec spec, ITxValidator txValidator) + /// Whether honours EIP-7805's separate inclusion lists under the builder's + /// omission claims, an undecided check counting as not honoured. + /// + public static bool IsSatisfied(Block block, IReadOnlyList inclusionLists, IReadOnlyStateProvider state, IReleaseSpec spec, ITxValidator txValidator, + ulong maxVerifyGasPerTx, OmissionClaim[]? claims, IProfile2EligibilityReplayer? replayer = null, IReadOnlyList<(ulong Execution, ulong State)>? gasUsedBefore = null) => + Evaluate(block, inclusionLists, state, spec, txValidator, maxVerifyGasPerTx, claims, replayer, gasUsedBefore) is true; + + /// Whether honours EIP-7805's separate inclusion lists under the builder's + /// omission claims. + /// null when the replayer could not decide a candidate and no other omission already condemns the block. + /// Checks appendability against state after transactions, before withdrawals and request system calls. + /// One decoded list per committee position, each in its original order with its + /// duplicates; the per-IL VERIFY budget is filled over each independently. + /// EIP-7805 MAX_VERIFY_GAS_PER_TX, above which a frame transaction is + /// no Profile 2 candidate and its omission is excused; 0 lifts the cap. + /// The builder's committed omission claims, in order and with their duplicates. + /// Decides Profile 2 eligibility; null enforces every omitted candidate that + /// passes the determinate checks. + /// EIP-8037 execution and state gas the block used before each transaction index, + /// one entry per transaction, which a Profile 2 candidate claimed before the end of the payload must fit; + /// null judges that fit against the whole block's gas, which only excuses more. + public static bool? Evaluate(Block block, IReadOnlyList inclusionLists, IReadOnlyStateProvider state, IReleaseSpec spec, ITxValidator txValidator, + ulong maxVerifyGasPerTx, OmissionClaim[]? claims, IProfile2EligibilityReplayer? replayer = null, IReadOnlyList<(ulong Execution, ulong State)>? gasUsedBefore = null) { if (!spec.InclusionListsEnabled) return true; - // No IL attached = non-engine-API path (genesis, RLP import); IL doesn't apply. - if (il is null) return true; + Transaction[] il = InclusionLists.Distinct(inclusionLists); + + // EIP-7805: before Profile 2 is active, committee positions and claims are carried but have no effect. + bool profile2Active = Eip8369Profile2.IsActive(spec); + if (!profile2Active) claims = null; - // No room for even the cheapest possible tx → nothing is appendable. + // No room for even the cheapest possible tx → nothing is appendable, unless a claim moves an + // evaluation before the end of the payload. ulong minIntrinsicGas = spec.IsEip2780Enabled ? GasCostOf.TransactionEip2780 : GasCostOf.Transaction; - if (block.GasUsed + minIntrinsicGas > block.GasLimit) return true; + if (!spec.IsEip8037Enabled && claims is not { Length: > 0 } && block.GasUsed + minIntrinsicGas > block.GasLimit) return true; // A conforming aggregate runs to tens of thousands of entries, far past what the stack can hold. bool[]? rented = il.Length > StackAllocEntries @@ -41,7 +73,10 @@ public static bool IsSatisfied(Block block, Transaction[]? il, IReadOnlyStatePro { Span included = rented is null ? stackalloc bool[il.Length] : rented.AsSpan(0, il.Length); included.Clear(); - return IsSatisfied(block, il, included, state, spec, txValidator); + if (gasUsedBefore is not null && gasUsedBefore.Count != block.Transactions.Length) gasUsedBefore = null; + Profile2Inputs profile2 = new(profile2Active, maxVerifyGasPerTx, inclusionLists, + ClaimedIndices(claims, block.Transactions.Length), replayer, gasUsedBefore); + return Evaluate(block, il, included, state, spec, txValidator, in profile2); } finally { @@ -49,9 +84,9 @@ public static bool IsSatisfied(Block block, Transaction[]? il, IReadOnlyStatePro } } - private static bool IsSatisfied(Block block, Transaction[] il, Span included, IReadOnlyStateProvider state, IReleaseSpec spec, ITxValidator txValidator) + private static bool? Evaluate(Block block, Transaction[] il, Span included, IReadOnlyStateProvider state, IReleaseSpec spec, ITxValidator txValidator, in Profile2Inputs profile2) { - // Duplicate IL entries stay unmarked but fail the appendability check (nonce advanced). + // Index the first copy of each hash; included copies satisfy every occurrence in the IL. Dictionary ilByHash = [with(il.Length)]; for (int i = 0; i < il.Length; i++) { @@ -65,32 +100,116 @@ private static bool IsSatisfied(Block block, Transaction[] il, Span includ included[idx] = true; } - Dictionary? senderCache = null; + Dictionary? accountCache = null; + HashSet? admitted = null; + List<(Transaction Transaction, int Index)>? toReplay = null; for (int i = 0; i < il.Length; i++) { if (included[i]) continue; + if (il[i].Hash is { } hash && ilByHash.TryGetValue(hash, out int first) && included[first]) continue; + if (il[i].SupportsFrames && profile2.Active) + { + // EIP-8369: a frame transaction outside Profile 2 is enforced by no profile, so its omission is excused. + if (Eip8369Profile2.Classify(il[i], profile2.MaxVerifyGasPerTx) != Profile2Exclusion.None) continue; + // Eligibility is a property of the bytes, so the first occurrence answers for every copy. + if (il[i].Hash is not { } frameHash || ilByHash[frameHash] != i) continue; + // EIP-7805 § Evaluation index: the builder's claim, if it is the hash's only one, else the end of the payload. + int index = profile2.ClaimedIndices?.TryGetValue(frameHash, out int? claimed) == true && claimed is { } at ? at : block.Transactions.Length; + if (!IsReplayableOmission(il[i], index, block, spec, txValidator, in profile2, ref admitted)) continue; + if (profile2.Replayer is null) return false; + (toReplay ??= []).Add((il[i], index)); + continue; + } + // Before Profile 2 is active a frame transaction is excused, as the end-of-payload rule cannot judge its + // programmable validation. + if (il[i].SupportsFrames) continue; // EIP-7805 excludes blob transactions from the appendability check. if (il[i].SupportsBlobs) continue; - // The rules below judge appendability on the account nonce, which a frame transaction does not - // use (EIP-8369 Profile 2), so reading one through them reports an honest payload as censoring. - if (il[i].SupportsFrames) continue; - if (CouldIncludeTx(il[i], block, state, spec, txValidator, ref senderCache)) return false; + if (CouldIncludeTx(il[i], block, state, spec, txValidator, ref accountCache)) return false; + } + if (toReplay is null) return true; + return AnyUnjustified(block, toReplay, spec, in profile2) switch { true => false, false => true, null => null }; + } + + /// The inputs EIP-8369 Profile 2 enforcement takes beyond the list itself. + private readonly record struct Profile2Inputs(bool Active, ulong MaxVerifyGasPerTx, IReadOnlyList InclusionLists, + Dictionary? ClaimedIndices, IProfile2EligibilityReplayer? Replayer, IReadOnlyList<(ulong Execution, ulong State)>? GasUsedBefore); + + /// Whether an omitted Profile 2 candidate passes every check but the replay at its evaluation index: + /// the static, fee and gas-fit conditions, and admission by some committee position's VERIFY budget fill. + /// Only these reach the replay, so replay work is bounded by the per-IL budgets. The payer's balance is + /// left to the replay, which collects the maximum cost from the state at . + private static bool IsReplayableOmission( + Transaction tx, + int index, + Block block, + IReleaseSpec spec, + ITxValidator txValidator, + in Profile2Inputs profile2, + ref HashSet? admitted) + { + if (tx.Hash is null || tx.SenderAddress is null) return false; + if (!FitsRemainingBlockGas(tx, block, spec, GasUsedBefore(block, index, profile2.GasUsedBefore))) return false; + if (!txValidator.IsWellFormed(tx, spec, block.GasLimit)) return false; + if (tx.MaxFeePerGas < block.BaseFeePerGas) return false; + if (!FrameTxValidation.TryCalculateGasBudget(tx, spec, out _, out _, out _) || !FrameTxValidation.TryCalculateMaxCost(tx, spec, out _)) return false; + + admitted ??= Eip8369Profile2.AdmitByVerifyBudget(InclusionLists.InFillOrder(profile2.InclusionLists), profile2.MaxVerifyGasPerTx, + profile2.Replayer is { } signatures ? occurrence => signatures.AreSignaturesValid(occurrence, spec) : null, + entry => Profile2StaticChecks.IsWellFormed(entry, spec)); + return admitted.Contains(tx.Hash); + } + + /// EIP-7805 § VERIFY budget: whether omitting any of , each admitted by some position, is unjustified. + /// null when none is proved unjustified and the replayer could not decide some. + /// + /// Each is replayed once, at its evaluation index: EIP-7805 judges a claimed candidate at its claim alone, so a + /// claim at an index where the candidate is valid condemns the omission even if it is invalid at the end. Every + /// replay goes to the replayer in one batch, so it reconstructs the block's state once. + /// + private static bool? AnyUnjustified(Block block, List<(Transaction Transaction, int Index)> candidates, IReleaseSpec spec, in Profile2Inputs profile2) + { + bool undecided = false; + foreach (bool? eligible in profile2.Replayer!.AreEligible(block, candidates, spec)) + { + if (eligible is true) return true; + if (eligible is null) undecided = true; + } + return undecided ? null : false; + } + + /// The index each claimed hash commits to, built once per check; null for a hash claimed more than once. + /// EIP-7805 § Evaluation index: an index past the end of the payload is clamped to it. A hash claimed + /// more than once has no single commitment, so every claim for it is ignored. + private static Dictionary? ClaimedIndices(OmissionClaim[]? claims, int transactionCount) + { + if (claims is not { Length: > 0 }) return null; + + Dictionary indices = [with(claims.Length)]; + foreach (OmissionClaim claim in claims) + { + if (claim.TransactionHash is not { } hash) continue; + ref int? index = ref CollectionsMarshal.GetValueRefOrAddDefault(indices, hash, out bool exists); + index = exists ? null : claim.EvaluationIndex < (ulong)transactionCount ? (int)claim.EvaluationIndex : transactionCount; } - return true; + return indices; } - private static bool CouldIncludeTx(Transaction tx, Block block, IReadOnlyStateProvider state, IReleaseSpec spec, ITxValidator txValidator, ref Dictionary? senderCache) + /// Whether an omitted non-frame inclusion-list entry could have been appended to , + /// judged at the end of the payload. + private static bool CouldIncludeTx(Transaction tx, Block block, IReadOnlyStateProvider state, IReleaseSpec spec, ITxValidator txValidator, ref Dictionary? accountCache) { if (tx.SenderAddress is null) return false; - if (!FitsRemainingBlockGas(tx, block, spec)) return false; + if (!FitsRemainingBlockGas(tx, block, spec, GasUsedBefore(block, block.Transactions.Length, null))) return false; // Appendability must match normal execution, so reuse the full well-formedness check, not a subset. if (!txValidator.IsWellFormed(tx, spec, block.GasLimit)) return false; if (tx.MaxFeePerGas < block.BaseFeePerGas) return false; - senderCache ??= []; - ref AccountStruct account = ref CollectionsMarshal.GetValueRefOrAddDefault(senderCache, tx.SenderAddress, out bool cached); + Address payer = tx.SenderAddress; + accountCache ??= []; + ref AccountStruct account = ref CollectionsMarshal.GetValueRefOrAddDefault(accountCache, payer, out bool cached); // Cache the negative result too (default struct = balance 0, nonce 0, empty codehash). - if (!cached) state.TryGetAccount(tx.SenderAddress, out account); + if (!cached) state.TryGetAccount(payer, out account); // EIP-3607: a sender with non-delegated code cannot send a tx. if (account.HasCode && !state.IsDelegatedCode(account.CodeHash)) return false; @@ -108,16 +227,44 @@ private static bool CouldIncludeTx(Transaction tx, Block block, IReadOnlyStatePr /// matching dimension, so measuring it against the header's max(execution, state) rejects transactions the /// spec judges includable. Callers whose block carries no dimensions must not put an EIP-8037 block to this /// check — the max alone under-reports censorship — which is why the engine API declines to answer instead. - private static bool FitsRemainingBlockGas(Transaction tx, Block block, IReleaseSpec spec) + private static bool FitsRemainingBlockGas(Transaction tx, Block block, IReleaseSpec spec, (ulong Execution, ulong State) gasUsed) { - // Subtract on the block side: GasUsed <= GasLimit is invariant, so this cannot underflow the + (ulong execution, ulong state) = gasUsed; + // Subtract on the block side: gas used <= GasLimit is invariant, so this cannot underflow the // way GasLimit - tx.GasLimit would for an oversized tx. - if (!spec.IsEip8037Enabled) return tx.GasLimit <= block.GasLimit - block.GasUsed; + if (!spec.IsEip8037Enabled) + { + ulong limit = tx.SupportsFrames && FrameTxValidation.TryCalculateGasBudget(tx, spec, out _, out _, out ulong maxGas) ? maxGas : tx.GasLimit; + return execution <= block.GasLimit && limit <= block.GasLimit - execution; + } - (ulong execution, ulong state) = block.Header.GasUsedPerDimension ?? (block.GasUsed, block.GasUsed); return Eip8037BlockGasInclusionCheck.TryGetBlockGasReservations(tx, spec, out ulong executionReservation, out ulong stateReservation) && Eip8037BlockGasInclusionCheck.Validate(block.GasLimit, execution, state, executionReservation, stateReservation) == Eip8037BlockGasInclusionCheck.Outcome.Ok; } + /// The block's gas used before transaction , in each EIP-8037 dimension. + /// Without per-transaction totals an index before the end is charged the whole block's gas, which only + /// excuses more; callers that need the exact answer supply them or bound it. + private static (ulong Execution, ulong State) GasUsedBefore(Block block, int index, IReadOnlyList<(ulong Execution, ulong State)>? gasUsedBefore) => + index < block.Transactions.Length && gasUsedBefore is not null + ? gasUsedBefore[index] + : block.Header.GasUsedPerDimension ?? (block.GasUsed, block.GasUsed); + + /// The EIP-8037 gas the block used before each of its transactions, from the receipts its execution produced. + /// null unless the receipts' per-transaction gas adds up to the block's recorded totals. + public static (ulong Execution, ulong State)[]? GasUsedBeforeEachTransaction(Block block, IReadOnlyList receipts) + { + if (receipts.Count != block.Transactions.Length || block.Header.GasUsedPerDimension is not { } total) return null; + + (ulong Execution, ulong State)[] before = new (ulong, ulong)[receipts.Count]; + ulong execution = 0, state = 0; + for (int i = 0; i < receipts.Count; i++) + { + before[i] = (execution, state); + execution += receipts[i].BlockGasUsed; + state += receipts[i].StorageGasUsed; + } + return (execution, state) == total ? before : null; + } } diff --git a/src/Nethermind/Nethermind.Core.Test/Builders/BlockBuilder.cs b/src/Nethermind/Nethermind.Core.Test/Builders/BlockBuilder.cs index 7b18e96de5da..331964aea9e1 100644 --- a/src/Nethermind/Nethermind.Core.Test/Builders/BlockBuilder.cs +++ b/src/Nethermind/Nethermind.Core.Test/Builders/BlockBuilder.cs @@ -296,12 +296,6 @@ public BlockBuilder WithParentBeaconBlockRoot(Hash256? parentBeaconBlockRoot) return this; } - public BlockBuilder WithInclusionListTransactions(params Transaction[]? inclusionListTransactions) - { - TestObjectInternal.InclusionListTransactions = inclusionListTransactions; - return this; - } - public BlockBuilder WithEncodedSize(int? encodedSize) { TestObjectInternal.EncodedSize = encodedSize; diff --git a/src/Nethermind/Nethermind.Core.Test/Eip8369Profile2Tests.cs b/src/Nethermind/Nethermind.Core.Test/Eip8369Profile2Tests.cs new file mode 100644 index 000000000000..95614e931728 --- /dev/null +++ b/src/Nethermind/Nethermind.Core.Test/Eip8369Profile2Tests.cs @@ -0,0 +1,153 @@ +// SPDX-FileCopyrightText: 2026 Demerzel Solutions Limited +// SPDX-License-Identifier: LGPL-3.0-only + +using System; +using System.Collections.Generic; +using Nethermind.Core.Test.Builders; +using Nethermind.Int256; +using NUnit.Framework; + +namespace Nethermind.Core.Test; + +/// One case per EIP-8369 Profile 2 candidate condition, each failing on its own so that no case +/// would still pass if a different condition were the one being checked. +public class Eip8369Profile2Tests +{ + private const ulong Budget = Eip8369Constants.MaxVerifyGasPerTx; + + [TestCaseSource(nameof(CandidacyCases))] + public Profile2Exclusion Classify_CandidateConditionMatrix(Action mutate, ulong maxVerifyGasPerTx) + => Eip8369Profile2.Classify(FrameTx(mutate), maxVerifyGasPerTx); + + private static IEnumerable CandidacyCases() + { + // Condition 2: the two admitted self-paid prefix shapes. + yield return Case("SelfVerify_IsCandidate", + static tx => tx.Frames = [SelfVerify()], Profile2Exclusion.None); + yield return Case("DeployThenSelfVerify_IsCandidate", + static tx => tx.Frames = [Deploy(), SelfVerify()], Profile2Exclusion.None); + yield return Case("OnlyVerifyThenPay_UnrecognizedPrefix", + static tx => tx.Frames = [OnlyVerify(), Pay()], Profile2Exclusion.UnrecognizedPrefix); + yield return Case("DeployThenOnlyVerifyThenPay_UnrecognizedPrefix", + static tx => tx.Frames = [Deploy(), OnlyVerify(), Pay()], Profile2Exclusion.UnrecognizedPrefix); + // A body frame behind the prefix is outside the prefix, so it does not affect the shape. + yield return Case("SelfVerifyThenBodyFrame_IsCandidate", + static tx => tx.Frames = [SelfVerify(), Body()], Profile2Exclusion.None); + + // Shape matching ignores the optional expiry verifier frame. + yield return Case("ExpiryThenSelfVerify_IsCandidate", + static tx => tx.Frames = [Expiry(), SelfVerify()], Profile2Exclusion.None); + yield return Case("ExpiryThenDeployThenSelfVerify_IsCandidate", + static tx => tx.Frames = [Expiry(), Deploy(), SelfVerify()], Profile2Exclusion.None); + // Only a leading expiry frame is stepped over; behind the prefix it is an ordinary VERIFY frame. + yield return Case("SelfVerifyThenExpiry_VerifyFrameAfterPrefix", + static tx => tx.Frames = [SelfVerify(), Expiry()], Profile2Exclusion.VerifyFrameAfterPrefix); + + // Condition 2 failures. + yield return Case("NoFrames_UnrecognizedPrefix", + static tx => tx.Frames = null, Profile2Exclusion.UnrecognizedPrefix); + yield return Case("BodyFrameOnly_UnrecognizedPrefix", + static tx => tx.Frames = [Body()], Profile2Exclusion.UnrecognizedPrefix); + // An execution-only approval that no payment frame follows nominates no payer. + yield return Case("OnlyVerifyWithoutPay_UnrecognizedPrefix", + static tx => tx.Frames = [OnlyVerify(), Body()], Profile2Exclusion.UnrecognizedPrefix); + // The prefix VERIFY frame must target the sender. + yield return Case("VerifyTargetingThirdParty_UnrecognizedPrefix", + static tx => tx.Frames = [new TxFrame(FrameMode.Verify, FrameFlags.ApproveExecutionAndPayment, TestItem.AddressB, 50_000, UInt256.Zero, default)], + Profile2Exclusion.UnrecognizedPrefix); + + // Condition 3, batch half: a prefix frame carrying ATOMIC_BATCH_FLAG matches no admitted shape. + yield return Case("AtomicBatchOnDeployFrame_UnrecognizedPrefix", + static tx => tx.Frames = [Deploy(FrameFlags.AtomicBatch), SelfVerify(), Body()], Profile2Exclusion.UnrecognizedPrefix); + + // Condition 3, VERIFY half. + yield return Case("VerifyFrameBehindTheSelfVerifyPrefix_VerifyFrameAfterPrefix", + static tx => tx.Frames = [SelfVerify(), Body(), Verify()], Profile2Exclusion.VerifyFrameAfterPrefix); + + // Condition 4: the budget spans the prefix's execution limits plus signature verification. + yield return Case("PrefixWithinBudget_IsCandidate", + static tx => tx.Frames = [SelfVerify(gasLimit: Budget)], Profile2Exclusion.None); + yield return Case("PrefixOverBudget_VerifyBudgetExceeded", + static tx => tx.Frames = [SelfVerify(gasLimit: Budget + 1)], Profile2Exclusion.VerifyBudgetExceeded); + // EIP-7805 verify_cost counts limits.execution only, so limits.state is outside the budget, however large. + yield return Case("PrefixStateGasOutsideTheBudget_IsCandidate", + static tx => tx.Frames = [new TxFrame(FrameMode.Verify, FrameFlags.ApproveExecutionAndPayment, target: null, Budget, ulong.MaxValue, UInt256.Zero, default)], + Profile2Exclusion.None); + // A body frame behind the prefix is not part of the budget, however large. + yield return Case("BodyFrameOutsideTheBudget_IsCandidate", + static tx => tx.Frames = [SelfVerify(gasLimit: Budget), Body(gasLimit: Budget)], Profile2Exclusion.None); + // The expiry frame is stepped over for shape matching but still counts toward the budget. + yield return Case("ExpiryFrameCountsTowardTheBudget_VerifyBudgetExceeded", + static tx => tx.Frames = [Expiry(gasLimit: 1), SelfVerify(gasLimit: Budget)], Profile2Exclusion.VerifyBudgetExceeded); + yield return Case("SignatureVerificationCountsTowardTheBudget_VerifyBudgetExceeded", + static tx => + { + tx.Frames = [SelfVerify(gasLimit: Budget - Eip8141Constants.Secp256k1VerificationGasCost + 1)]; + tx.FrameSignatures = [Secp256k1Signature()]; + }, + Profile2Exclusion.VerifyBudgetExceeded); + // Saturating arithmetic: a prefix that would overflow the sum must not wrap under the cap. + yield return Case("PrefixGasSaturates_VerifyBudgetExceeded", + static tx => + { + tx.Frames = [SelfVerify(gasLimit: ulong.MaxValue)]; + tx.FrameSignatures = [Secp256k1Signature()]; + }, + Profile2Exclusion.VerifyBudgetExceeded); + // A zero cap lifts the limit, as ITxPoolConfig.FrameTxMaxVerifyGas does. + yield return Case("ZeroCapLiftsTheBudget_IsCandidate", + static tx => tx.Frames = [SelfVerify(gasLimit: ulong.MaxValue)], Profile2Exclusion.None, maxVerifyGasPerTx: 0); + + // Outside both profiles: blob gas has its own budget, over which EIP-8369 defines no omission check. + yield return Case("BlobCarryingFrameTx_CarriesBlobs", + static tx => tx.BlobVersionedHashes = [new byte[32]], Profile2Exclusion.CarriesBlobs); + // The blob check comes first: a blob carrier is outside the profiles whatever its shape. + yield return Case("BlobCarryingBodyOnlyFrameTx_CarriesBlobs", + static tx => + { + tx.Frames = [Body()]; + tx.BlobVersionedHashes = [new byte[32]]; + }, + Profile2Exclusion.CarriesBlobs); + } + + private static TestCaseData Case(string name, Action mutate, Profile2Exclusion expected, ulong maxVerifyGasPerTx = Budget) => + new(mutate, maxVerifyGasPerTx) { TestName = name, ExpectedResult = expected }; + + private static Transaction FrameTx(Action mutate) + { + Transaction tx = new() + { + Type = TxType.FrameTx, + SenderAddress = TestItem.AddressA, + Frames = [SelfVerify()], + FrameSignatures = [], + }; + mutate(tx); + return tx; + } + + private static TxFrame SelfVerify(ulong gasLimit = 50_000) => + new(FrameMode.Verify, FrameFlags.ApproveExecutionAndPayment, target: null, gasLimit, UInt256.Zero, default); + + private static TxFrame OnlyVerify(ulong gasLimit = 50_000) => + new(FrameMode.Verify, FrameFlags.ApproveExecution, target: null, gasLimit, UInt256.Zero, default); + + private static TxFrame Pay(FrameFlags flags = FrameFlags.ApprovePayment, ulong gasLimit = 50_000) => + new(FrameMode.Verify, flags, TestItem.AddressB, gasLimit, UInt256.Zero, default); + + private static TxFrame Deploy(FrameFlags flags = FrameFlags.None, ulong gasLimit = 50_000) => + new(FrameMode.Default, flags, target: null, gasLimit, UInt256.Zero, default); + + private static TxFrame Body(ulong gasLimit = 50_000) => + new(FrameMode.Default, FrameFlags.None, TestItem.AddressC, gasLimit, UInt256.Zero, default); + + private static TxFrame Verify(ulong gasLimit = 50_000) => + new(FrameMode.Verify, FrameFlags.None, TestItem.AddressC, gasLimit, UInt256.Zero, default); + + private static TxFrame Expiry(ulong gasLimit = 30_000) => + new(FrameMode.Verify, FrameFlags.None, Eip8141Constants.ExpiryVerifierAddress, gasLimit, UInt256.Zero, new byte[Eip8141Constants.ExpiryDataLength]); + + private static TxFrameSignature Secp256k1Signature() => + new(TxFrameSignature.SchemeSecp256k1, TestItem.AddressA, default, new byte[65]); +} diff --git a/src/Nethermind/Nethermind.Core/Block.cs b/src/Nethermind/Nethermind.Core/Block.cs index e4b05e98f357..1a356dd753b2 100644 --- a/src/Nethermind/Nethermind.Core/Block.cs +++ b/src/Nethermind/Nethermind.Core/Block.cs @@ -30,13 +30,11 @@ public Block(BlockHeader header, IEnumerable transactions, IEnumerable uncles, IEnumerable? withdrawals = null, - ReadOnlyBlockAccessList? blockAccessList = null, - IEnumerable? inclusionListTransactions = null) + ReadOnlyBlockAccessList? blockAccessList = null) { Header = header ?? throw new ArgumentNullException(nameof(header)); Body = new(transactions.ToArray(), uncles.ToArray(), withdrawals?.ToArray()); BlockAccessList = blockAccessList; - InclusionListTransactions = inclusionListTransactions?.ToArray(); } public Block(BlockHeader header) : this( @@ -136,13 +134,14 @@ public Transaction[] Transactions [JsonIgnore] public byte[][]? ExecutionRequests { get; set; } + /// The EIP-7805 omission claims a build committed to for the inclusion-list entries it omitted. [JsonIgnore] - public Transaction[]? InclusionListTransactions { get; set; } + public OmissionClaim[]? OmissionClaims { get; set; } - // Set after the post-execution check: false means the block is valid and executable but did not - // honour its inclusion list (EIP-7805). + /// The EIP-8037 execution and state gas the block used before each of its transactions, as its execution + /// recorded them, so a later inclusion check can fit an omission claim exactly; null when not recorded. [JsonIgnore] - public bool IsInclusionListSatisfied { get; set; } = true; + public (ulong Execution, ulong State)[]? GasUsedBeforeTransactions { get; set; } [JsonIgnore] public ArrayPoolList? AccountChanges { get; set; } diff --git a/src/Nethermind/Nethermind.Core/Eip7805Constants.cs b/src/Nethermind/Nethermind.Core/Eip7805Constants.cs index 0744100d0d98..28386878967b 100644 --- a/src/Nethermind/Nethermind.Core/Eip7805Constants.cs +++ b/src/Nethermind/Nethermind.Core/Eip7805Constants.cs @@ -5,13 +5,13 @@ namespace Nethermind.Core; /// Transport bounds on the inclusion lists an EIP-7805 committee can produce. /// -/// The engine API receives the committee's lists already flattened into one aggregate, so every aggregate -/// bound is a per-member bound times . They exist to cap decode -/// work on untrusted input; none of them is a consensus rule. +/// The engine API receives one list per committee position, so every aggregate bound is a per-member bound +/// times . They exist to cap decode work on untrusted input; none of +/// them is a consensus rule. /// public static class Eip7805Constants { - /// IL_COMMITTEE_SIZE: members whose lists one aggregate spans. + /// INCLUSION_LIST_COMMITTEE_SIZE: committee positions, each with a list of its own. public const int InclusionListCommitteeSize = 16; /// MAX_TRANSACTIONS_BYTES_PER_INCLUSION_LIST: byte cap on one member's list. @@ -24,9 +24,6 @@ public static class Eip7805Constants /// public const int MaxTransactionsPerInclusionList = MaxBytesPerInclusionList; - /// Transaction bytes the flattened aggregate can carry. - public const int MaxAggregateInclusionListBytes = InclusionListCommitteeSize * MaxBytesPerInclusionList; - - /// Entries the flattened aggregate can carry. + /// Entries the committee's lists can carry together. public const int MaxAggregateInclusionListTransactions = InclusionListCommitteeSize * MaxTransactionsPerInclusionList; } diff --git a/src/Nethermind/Nethermind.Core/Eip8369Constants.cs b/src/Nethermind/Nethermind.Core/Eip8369Constants.cs new file mode 100644 index 000000000000..9ccad2983dc8 --- /dev/null +++ b/src/Nethermind/Nethermind.Core/Eip8369Constants.cs @@ -0,0 +1,37 @@ +// SPDX-FileCopyrightText: 2026 Demerzel Solutions Limited +// SPDX-License-Identifier: LGPL-3.0-only + +namespace Nethermind.Core; + +/// +/// Constants of EIP-8369 VOPS profiles for FOCIL eligibility. +/// https://eips.ethereum.org/EIPS/eip-8369 +/// +/// +/// EIP-8369 is Informational and leaves its budget caps to the Standards Track EIP that enforces them; EIP-7805 +/// § Profile 2 omission claims and per IL budgets fixes the values here. IBlocksConfig.FocilProfile2MaxVerifyGas +/// is the operator-facing mirror, as ITxPoolConfig.FrameTxMaxVerifyGas is for EIP-8141's own cap. +/// +public static class Eip8369Constants +{ + /// MAX_VERIFY_GAS_PER_IL: the VERIFY budget one inclusion list may spend across its + /// Profile 2 entries. + public const ulong MaxVerifyGasPerIl = 1UL << 20; + + /// MAX_VERIFY_GAS_PER_TX: the VERIFY budget cost above which a frame transaction is not a + /// Profile 2 candidate, so FOCIL never enforces its omission. + public const ulong MaxVerifyGasPerTx = 1UL << 18; + + /// AA_VOPS_SLOT_COUNT: the leading storage slots of sender and payer a Profile 2 + /// validation prefix may read. + public const ulong AaVopsSlotCount = 4; + + /// MAX_REPLAY_CODE_BODIES: the distinct code bodies one Profile 2 replay may load. + public const int MaxReplayCodeBodies = 16; + + /// MAX_REPLAY_CODE_BYTES: the combined size of the distinct code bodies one Profile 2 replay may load. + public const long MaxReplayCodeBytes = 1L << 17; + + /// MAX_OMISSION_CLAIMS: the omission claims one payload may carry. + public const int MaxOmissionClaims = 1 << 12; +} diff --git a/src/Nethermind/Nethermind.Core/Eip8369Profile2.cs b/src/Nethermind/Nethermind.Core/Eip8369Profile2.cs new file mode 100644 index 000000000000..646d34bc933f --- /dev/null +++ b/src/Nethermind/Nethermind.Core/Eip8369Profile2.cs @@ -0,0 +1,150 @@ +// SPDX-FileCopyrightText: 2026 Demerzel Solutions Limited +// SPDX-License-Identifier: LGPL-3.0-only + +using System; +using System.Collections.Generic; +using System.Runtime.InteropServices; +using Nethermind.Core.Crypto; +using Nethermind.Core.Specs; + +namespace Nethermind.Core; + +/// Why a frame transaction is not an EIP-8369 Profile 2 candidate, or when it is. +public enum Profile2Exclusion : byte +{ + /// The transaction meets every Profile 2 candidate condition. + None = 0, + + /// It carries blob hashes: blob gas has its own budget, over which EIP-8369 defines no omission check. + CarriesBlobs, + + /// Its validation prefix is not self-paid (self_verify or deploy | self_verify), or a prefix + /// frame carries ATOMIC_BATCH_FLAG. + UnrecognizedPrefix, + + /// A frame behind the validation prefix has mode VERIFY. + VerifyFrameAfterPrefix, + + /// Its VERIFY budget cost exceeds MAX_VERIFY_GAS_PER_TX. + VerifyBudgetExceeded, +} + +/// +/// The EIP-8369 Profile 2 (FOCIL AA-VOPS) candidate conditions, which decide whether FOCIL enforces the +/// omission of an EIP-8141 frame transaction from a block. +/// https://eips.ethereum.org/EIPS/eip-8369 +/// +/// +/// Candidacy is a pure function of the transaction: it reads no state and no release spec. Profile 2 +/// eligibility is the separate, state-dependent half — keyed nonces, recent roots, and a validation +/// prefix replayed within the AA-VOPS surface — and cannot be decided here. +/// +public static class Eip8369Profile2 +{ + /// Whether EIP-7805's Profile 2 is active: it needs EIP-8141, EIP-8250 and EIP-8272 beside inclusion lists. + /// EIP-7805 activates both profiles with FOCIL and requires these EIPs for that activation, so the + /// conjunction only matters for a chain that schedules inclusion lists without frames, which keeps the original + /// Profile 1 rule. Once Profile 2 is active, an omitted transaction outside both profiles, a blob transaction among + /// them, is excused. + public static bool IsActive(IReleaseSpec spec) => + spec.InclusionListsEnabled && spec.IsEip8141Enabled && spec.IsEip8250Enabled && spec.IsEip8272Enabled; + + /// Classifies against the EIP-8369 Profile 2 candidate conditions. + /// + /// Condition 1, static EIP-8141 validity, is the caller's: every caller already runs a well-formedness + /// check, and repeating it here would need the release spec this deliberately does not take. Condition 3's + /// batch half is folded into because the shape + /// predicates compare the whole flags byte, so a prefix frame carrying ATOMIC_BATCH_FLAG already + /// matches no admitted shape. + /// + /// The frame transaction to classify; a transaction without frames is + /// reported as rather than thrown on. + /// MAX_VERIFY_GAS_PER_TX; 0 lifts the cap. + /// when every candidate condition holds. + public static Profile2Exclusion Classify(Transaction transaction, ulong maxVerifyGasPerTx) + { + if (transaction.CarriesBlobs) return Profile2Exclusion.CarriesBlobs; + + if (!HasSelfPaidPrefix(transaction)) return Profile2Exclusion.UnrecognizedPrefix; + + if (FrameTxValidation.HasVerifyFrameAfterPrefix(transaction)) return Profile2Exclusion.VerifyFrameAfterPrefix; + + return maxVerifyGasPerTx != 0 && VerifyBudgetCost(transaction) > maxVerifyGasPerTx + ? Profile2Exclusion.VerifyBudgetExceeded + : Profile2Exclusion.None; + } + + private static bool HasSelfPaidPrefix(Transaction transaction) + { + TxFrame[] frames = transaction.Frames ?? []; + int approval = FrameTxValidation.ApprovalSearchStart(frames); + return approval < frames.Length && FrameTxValidation.IsSelfVerifyFrame(frames[approval], transaction.SenderAddress); + } + + /// + /// EIP-7805 verify_cost(T): "the EIP-8141 signature_verification_cost of T plus the + /// limits.execution of every frame of its validation prefix", the expiry verifier frame included. + /// + /// The prefix's limits.state does not count toward the VERIFY budget. + public static ulong VerifyBudgetCost(Transaction transaction) => FrameTxValidation.ValidationWorkGas(transaction); + + /// EIP-7805 § VERIFY budget: the Profile 2 entries the per-IL VERIFY budget fill admits. + /// + /// Each list starts from and takes its entries in order. An + /// entry that is no Profile 2 candidate, statically invalid or costlier than the remaining budget is skipped + /// without a debit; otherwise the signature cost is debited, and the prefix cost too once the signatures verify. + /// An entry is admitted when any list admits it, so one list exhausting its own budget cannot excuse another's. + /// An entry carried by several positions is verified once, however many lists carry it, but debited by each. + /// + /// Each committee member's occurrences, in the order the fill processes them. + /// MAX_VERIFY_GAS_PER_TX; 0 lifts the cap. + /// Verifies an occurrence's protocol signatures; null takes them as valid. + /// The active fork's noncryptographic static checks; null takes them as passed. + public static HashSet AdmitByVerifyBudget( + IEnumerable> inclusionLists, ulong maxVerifyGasPerTx, Func? signaturesValid, + Func? staticallyValid = null) + { + HashSet admitted = []; + Dictionary? verified = null; + Dictionary? valid = null; + foreach (IEnumerable inclusionList in inclusionLists) + { + ulong remaining = Eip8369Constants.MaxVerifyGasPerIl; + foreach (Transaction tx in inclusionList) + { + if (!tx.SupportsFrames || tx.Hash is null) continue; + // Step 1: the noncryptographic candidate conditions, failures skipped without a debit. + if (Classify(tx, maxVerifyGasPerTx) != Profile2Exclusion.None || !IsStaticallyValid(tx, tx.Hash, staticallyValid, ref valid)) continue; + + ulong cost = VerifyBudgetCost(tx); + if (cost > remaining) continue; + + ulong signatureCost = FrameTxValidation.SignatureVerificationWorkGas(tx); + remaining -= signatureCost; + // A failed signature keeps its debit but is not admitted. + if (signaturesValid is not null && !AreSignaturesValid(tx, tx.Hash, signaturesValid, ref verified)) continue; + + remaining -= cost - signatureCost; + admitted.Add(tx.Hash); + } + } + return admitted; + } + + private static bool IsStaticallyValid(Transaction tx, Hash256 hash, Func? staticallyValid, ref Dictionary? valid) + { + if (staticallyValid is null) return true; + valid ??= []; + ref bool result = ref CollectionsMarshal.GetValueRefOrAddDefault(valid, hash, out bool exists); + if (!exists) result = staticallyValid(tx); + return result; + } + + private static bool AreSignaturesValid(Transaction tx, Hash256 hash, Func signaturesValid, ref Dictionary? verified) + { + verified ??= []; + ref bool valid = ref CollectionsMarshal.GetValueRefOrAddDefault(verified, hash, out bool exists); + if (!exists) valid = signaturesValid(tx); + return valid; + } +} diff --git a/src/Nethermind/Nethermind.Core/EngineApiVersions.cs b/src/Nethermind/Nethermind.Core/EngineApiVersions.cs index e14cae5e524c..a85a530a4da1 100644 --- a/src/Nethermind/Nethermind.Core/EngineApiVersions.cs +++ b/src/Nethermind/Nethermind.Core/EngineApiVersions.cs @@ -43,7 +43,8 @@ public static class GetPayload public const int V4 = 4; // Prague public const int V5 = 5; // Osaka public const int V6 = 6; // Amsterdam - public const int Latest = V6; + public const int V7 = 7; // Bogota + public const int Latest = V7; } /// engine_getBlobs method versions. diff --git a/src/Nethermind/Nethermind.Core/FrameTxValidation.cs b/src/Nethermind/Nethermind.Core/FrameTxValidation.cs index 01a40d49e4b1..b81cbc41c791 100644 --- a/src/Nethermind/Nethermind.Core/FrameTxValidation.cs +++ b/src/Nethermind/Nethermind.Core/FrameTxValidation.cs @@ -448,6 +448,8 @@ public static bool HasMisplacedExpiryFrame(Transaction transaction) { // A non-VERIFY frame ends the prefix, so nothing past it can install a payer. if (frames[i].Mode != FrameMode.Verify) break; + // A mask, not the whole-byte equality the recognized shapes use: this walk deliberately also keys + // sponsors installed through layouts those shapes reject. if ((frames[i].Flags & FrameFlags.ApprovePayment) == 0) continue; Address? resolved = frames[i].Target ?? transaction.SenderAddress; @@ -525,7 +527,9 @@ public static bool HasRecognizedValidationPrefix(Transaction transaction) => /// The number of leading frames forming a validation prefix EIP-8141 recognizes for the public /// mempool, or null when the layout matches none of them. /// - private static int? RecognizedPrefixLength(TxFrame[] frames, Address? sender) + /// The count spans the optional expiry-verifier and deploy frames that + /// steps over. + public static int? RecognizedPrefixLength(TxFrame[] frames, Address? sender) { int next = ApprovalSearchStart(frames); diff --git a/src/Nethermind/Nethermind.Core/InclusionLists.cs b/src/Nethermind/Nethermind.Core/InclusionLists.cs new file mode 100644 index 000000000000..f158b1de7a73 --- /dev/null +++ b/src/Nethermind/Nethermind.Core/InclusionLists.cs @@ -0,0 +1,78 @@ +// SPDX-FileCopyrightText: 2026 Demerzel Solutions Limited +// SPDX-License-Identifier: LGPL-3.0-only + +using System.Collections.Generic; +using Nethermind.Core.Crypto; + +namespace Nethermind.Core; + +/// +/// EIP-7805 separate inclusion lists: exactly transaction +/// lists in committee-position order, an empty one where no applicable IL is available. A validator holding several +/// positions has the same list at each, and each list keeps its order and duplicates. +/// +public static class InclusionLists +{ + /// The engine API's structural checks on separate inclusion lists, or null when they pass. + /// bogota.md engine_newPayloadV6 point 2.1: exactly one list per committee position, every entry + /// a nonempty byte string, and no list over before + /// deduplication. Transaction contents are not judged here. + public static string? Validate(byte[]?[]?[]? inclusionLists) + { + if (inclusionLists is null) return "Inclusion lists must be set"; + if (inclusionLists.Length != Eip7805Constants.InclusionListCommitteeSize) + return $"Inclusion lists must have exactly {Eip7805Constants.InclusionListCommitteeSize} entries"; + + for (int position = 0; position < inclusionLists.Length; position++) + { + if (inclusionLists[position] is not { } list) return $"Inclusion list at committee position {position} must be a list"; + + long bytes = 0; + foreach (byte[]? transaction in list) + { + if (transaction is not { Length: > 0 }) return $"Inclusion list at committee position {position} has an empty transaction"; + bytes += transaction.Length; + } + + if (bytes > Eip7805Constants.MaxBytesPerInclusionList) + return $"Inclusion list at committee position {position} exceeds the maximum size"; + } + + return null; + } + + /// Each committee position's transactions, once each and in ascending hash order, the order EIP-7805's + /// per-IL VERIFY budget fill processes them in. + /// A transaction's hash is the Keccak-256 of its exact envelope, so deduplicating and ordering by it is + /// EIP-7805's (keccak256(envelope), envelope) order but for a hash collision. + public static IEnumerable> InFillOrder(IReadOnlyList inclusionLists) + { + foreach (Transaction[] inclusionList in inclusionLists) + { + List ordered = []; + HashSet seen = []; + foreach (Transaction transaction in inclusionList) + { + if (transaction.Hash is { } hash && seen.Add(hash)) ordered.Add(transaction); + } + ordered.Sort(static (a, b) => a.Hash!.CompareTo(b.Hash)); + yield return ordered; + } + } + + /// Every transaction across , the first occurrence of each hash only, + /// in committee-position and then list order. + public static Transaction[] Distinct(IReadOnlyList inclusionLists) + { + List distinct = []; + HashSet seen = []; + foreach (Transaction[] inclusionList in inclusionLists) + { + foreach (Transaction transaction in inclusionList) + { + if (transaction.Hash is not { } hash || seen.Add(hash)) distinct.Add(transaction); + } + } + return [.. distinct]; + } +} diff --git a/src/Nethermind/Nethermind.Core/JsonConverters/CanonicalQuantityConverter.cs b/src/Nethermind/Nethermind.Core/JsonConverters/CanonicalQuantityConverter.cs new file mode 100644 index 000000000000..2fe2a3cbeef0 --- /dev/null +++ b/src/Nethermind/Nethermind.Core/JsonConverters/CanonicalQuantityConverter.cs @@ -0,0 +1,31 @@ +// SPDX-FileCopyrightText: 2026 Demerzel Solutions Limited +// SPDX-License-Identifier: LGPL-3.0-only + +using System; +using System.Globalization; +using System.Text.Json; +using System.Text.Json.Serialization; + +namespace Nethermind.Serialization.Json; + +/// Reads a 64-bit QUANTITY only in its canonical form: a 0x-prefixed hex string without +/// leading zeros, 0x0 for zero (execution-apis common.md). +/// Applies whatever JsonRpc.StrictHexFormat is set to, for a field whose encoding identifies +/// something, as an omission claim's does an inclusion check. +public sealed class CanonicalQuantityConverter : JsonConverter +{ + private const int MaxDigits = sizeof(ulong) * 2; + + public override ulong Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) + { + string? text = reader.TokenType == JsonTokenType.String ? reader.GetString() : null; + ReadOnlySpan digits = text is not null && text.StartsWith("0x", StringComparison.Ordinal) ? text.AsSpan(2) : default; + if (digits.IsEmpty || digits.Length > MaxDigits || (digits.Length > 1 && digits[0] == '0') + || !ulong.TryParse(digits, NumberStyles.AllowHexSpecifier, CultureInfo.InvariantCulture, out ulong value)) + throw new JsonException("QUANTITY must be 0x-prefixed hex without leading zeros"); + return value; + } + + public override void Write(Utf8JsonWriter writer, ulong value, JsonSerializerOptions options) => + writer.WriteStringValue($"0x{value:x}"); +} diff --git a/src/Nethermind/Nethermind.Core/OmissionClaim.cs b/src/Nethermind/Nethermind.Core/OmissionClaim.cs new file mode 100644 index 000000000000..5fbfb7bc0fc5 --- /dev/null +++ b/src/Nethermind/Nethermind.Core/OmissionClaim.cs @@ -0,0 +1,19 @@ +// SPDX-FileCopyrightText: 2026 Demerzel Solutions Limited +// SPDX-License-Identifier: LGPL-3.0-only + +using System.Text.Json.Serialization; +using Nethermind.Core.Crypto; +using Nethermind.Serialization.Json; + +namespace Nethermind.Core; + +/// An EIP-7805 omission claim: the payload index at which the builder's omission of a Profile 2 +/// candidate is evaluated. +/// Both fields are required on the wire: a claim missing either, or whose index is not a canonical +/// QUANTITY, does not match OmissionClaimV1. +/// Keccak-256 of the inclusion-list entry's EIP-2718 bytes. +/// An index into the payload's transactions, 0 before the first and +/// len(payload.transactions) at the end; a larger value is clamped to the end. +public readonly record struct OmissionClaim( + [property: JsonRequired] Hash256 TransactionHash, + [property: JsonRequired, JsonConverter(typeof(CanonicalQuantityConverter))] ulong EvaluationIndex); diff --git a/src/Nethermind/Nethermind.Evm.Test/FrameTxValidationPrefixSimulationTests.cs b/src/Nethermind/Nethermind.Evm.Test/FrameTxValidationPrefixSimulationTests.cs index 063747ca83d7..2dc1487a59ed 100644 --- a/src/Nethermind/Nethermind.Evm.Test/FrameTxValidationPrefixSimulationTests.cs +++ b/src/Nethermind/Nethermind.Evm.Test/FrameTxValidationPrefixSimulationTests.cs @@ -328,6 +328,65 @@ public void Simulate_PrefixAboveTheSharedFloor_IsJudgedAgainstTheTracersBudget(u } } + // EIP-7805: the sender's code is one body and each helper it calls another; EXTCODESIZE loads its target too. + [TestCase(3, 0L, false, false, TestName = "Code bodies at the replay limit are allowed")] + [TestCase(2, 0L, false, true, TestName = "One code body over the replay limit is refused")] + [TestCase(0, 0L, true, true, TestName = "EXTCODESIZE loads its target as a code body")] + [TestCase(0, -1L, false, true, TestName = "One byte over the replay code byte limit is refused")] + [TestCase(0, 0L, false, false, TestName = "Code bytes at the replay limit are allowed")] + public void Simulate_ReplayCodeLimits_BoundBodiesAndBytes(int maxBodies, long byteSlack, bool extCodeSize, bool violates) + { + byte[] helperB = [(byte)Instruction.PUSH1, 1, (byte)Instruction.STOP]; + byte[] helperC = [(byte)Instruction.PUSH1, 2, (byte)Instruction.STOP]; + DeployContract(TestItem.AddressB, helperB); + DeployContract(TestItem.AddressC, helperC); + Prepare code = Prepare.EvmCode.StaticCall(TestItem.AddressB, 50_000).Op(Instruction.POP); + code = extCodeSize + ? code.PushData(TestItem.AddressC).Op(Instruction.EXTCODESIZE).Op(Instruction.POP) + : code.StaticCall(TestItem.AddressC, 50_000).Op(Instruction.POP); + byte[] senderCode = code.PushData((byte)FrameFlags.ApproveExecutionAndPayment).PushData(0).PushData(0).Op(Instruction.APPROVE).Done; + DeployContract(Sender, senderCode, 1.Ether); + Transaction tx = FrameTx(nonce: 0, SelfVerifyFrame()); + long maxBytes = maxBodies == 0 ? senderCode.Length + helperB.Length + helperC.Length + byteSlack : 0; + FrameTxValidationTracer tracer = new(Sender, Eip8141Constants.ExpiryVerifierAddress, _stateProvider, Spec, + maxCodeBodies: maxBodies == 0 && extCodeSize ? 2 : maxBodies, maxCodeBytes: maxBytes); + + try + { + Run(tx, tracer); + } + catch (OperationCanceledException) when (tracer.Violated) + { + } + + Assert.That(tracer.Violated, Is.EqualTo(violates), tracer.ViolationReason); + } + + // A body is counted once however often execution returns to its first instruction: a loop jumping back to + // offset 0, or the body re-entered through a self-call, must not rehash a large body per iteration. + [TestCase(false, TestName = "A loop back to offset 0 hashes a large body at most once")] + [TestCase(true, TestName = "A body re-entered through self-calls hashes at most once")] + public void Simulate_ReplayCodeLimits_HashEachBodyOnce(bool selfCall) + { + // JUMPDEST [STATICCALL(self)] PUSH0 JUMP, padded to 48 KiB; it loops until the frame runs out of gas. + Prepare code = Prepare.EvmCode.Op(Instruction.JUMPDEST); + if (selfCall) code = code.StaticCall(Sender, 5_000).Op(Instruction.POP); + byte[] loop = code.Op(Instruction.PUSH0).Op(Instruction.JUMP).Done; + byte[] body = new byte[48 * 1024]; + loop.CopyTo(body, 0); + DeployContract(Sender, body, 1.Ether); + FrameTxValidationTracer tracer = new(Sender, Eip8141Constants.ExpiryVerifierAddress, _stateProvider, Spec, + maxCodeBodies: Eip8369Constants.MaxReplayCodeBodies, maxCodeBytes: Eip8369Constants.MaxReplayCodeBytes); + + Run(FrameTx(nonce: 0, SelfVerifyFrame()), tracer); + + using (Assert.EnterMultipleScope()) + { + Assert.That(tracer.Violated, Is.False, tracer.ViolationReason); + Assert.That(tracer.CodeHashComputations, Is.LessThanOrEqualTo(1)); + } + } + [Test] public void Simulate_PrefixCallsCodelessTarget_RecordsViolation() { @@ -1366,6 +1425,49 @@ public void Simulate_DeployFrameUsingPlainCreate_RecordsViolation() Assert.That(tracer.ViolationReason, Does.Contain("banned opcode CREATE")); } + // EIP-7805's Profile 2 deployment bookkeeping includes the creator's nonce, so its replay admits plain CREATE + // in the deploy frame, still only to install code at tx.sender, and still nowhere else. + [TestCase(true, false, TestName = "Profile 2 replay admits a deploy frame installing tx.sender with CREATE")] + [TestCase(false, true, TestName = "Profile 2 replay refuses CREATE outside the deploy frame")] + public void Simulate_CreateInDeployFrame_IsAllowedWhenEnabled(bool fromDeployFrame, bool violates) + { + byte[] initCode = Prepare.EvmCode.ForInitOf(ApproveCode(FrameFlags.ApproveExecutionAndPayment)).Done; + byte[] create = Prepare.EvmCode.Create(initCode, 0).Done; + Address sender; + Transaction tx; + if (fromDeployFrame) + { + DeployContract(Factory, create); + sender = ContractAddress.From(Factory, 0); + FundAccount(sender, 1.Ether); + tx = DeployTx(sender); + } + else + { + // The sender's own VERIFY code runs the CREATE. + sender = TestItem.AddressE; + DeployContract(sender, [.. create, .. ApproveCode(FrameFlags.ApproveExecutionAndPayment)], 1.Ether); + tx = FrameTx(nonce: 0, SelfVerifyFrame()); + tx.SenderAddress = sender; + } + + FrameTxValidationTracer tracer = new(sender, Eip8141Constants.ExpiryVerifierAddress, _stateProvider, Spec, createInDeployFrame: true); + + try + { + Run(tx, tracer); + } + catch (OperationCanceledException) when (tracer.Violated) + { + } + + using (Assert.EnterMultipleScope()) + { + Assert.That(tracer.Violated, Is.EqualTo(violates), tracer.ViolationReason); + if (violates) Assert.That(tracer.ViolationReason, Does.Contain("banned opcode CREATE")); + } + } + // The endowment is the same one-bit dependency on the factory's balance that the funded-CALL ban closes: // underfunded, the create pushes zero and installs nothing, and anyone can drain the factory. [TestCase(0, false, TestName = "an unendowed CREATE2 is allowed")] diff --git a/src/Nethermind/Nethermind.Evm/Tracing/FrameTxValidationTracer.cs b/src/Nethermind/Nethermind.Evm/Tracing/FrameTxValidationTracer.cs index 571ce79e8107..bda02927bcb0 100644 --- a/src/Nethermind/Nethermind.Evm/Tracing/FrameTxValidationTracer.cs +++ b/src/Nethermind/Nethermind.Evm/Tracing/FrameTxValidationTracer.cs @@ -8,18 +8,35 @@ using Nethermind.Core.Caching; using Nethermind.Core.Crypto; using Nethermind.Core.Specs; +using Nethermind.Evm.CodeAnalysis; using Nethermind.Evm.State; using Nethermind.Int256; namespace Nethermind.Evm.Tracing; -/// Enforces the EIP-8141 validation-prefix opcode rules during mempool prefix simulation, -/// and captures the resolved payer. +/// Enforces the EIP-8141 validation-prefix opcode rules during prefix simulation, and captures the +/// resolved payer. +/// +/// The storage surface is parameterised because EIP-8141's mempool rule and EIP-8369's Profile 2 draw it +/// differently: EIP-8141 admits every slot of alone, Profile 2 admits the first +/// slots of and the payer. Defaults reproduce +/// the EIP-8141 rule exactly. +/// +/// A second account whose storage the prefix may read, or null for +/// only. +/// Slots below which a read is in surface, or 0 for no slot bound. +/// Whether the deploy frame may install code at tx.sender with CREATE as well as +/// CREATE2, as EIP-8141 and EIP-7805's Profile 2 deployment bookkeeping permit; the public mempool refuses it. +/// EIP-7805 MAX_REPLAY_CODE_BODIES: the distinct code bodies the prefix may load, or +/// 0 for no bound. A body is loaded when execution starts in it, after delegation is followed, or when +/// EXTCODESIZE or EXTCODECOPY reads it; empty code loads nothing. +/// EIP-7805 MAX_REPLAY_CODE_BYTES: their combined size, or 0 for no bound. /// Wall-clock bound on the simulation, or for none. /// The clock is measured against; the system clock by default. /// Cancels the simulation cooperatively; polled by the interpreter. /// Polled with ; once it returns true the simulation stops and /// stays set. +/// The prefix's VERIFY gas bound; EIP-8141's MAX_VERIFY_GAS by default. /// The most distinct accounts may hold; recording one /// more violates the prefix. public sealed class FrameTxValidationTracer( @@ -32,13 +49,18 @@ public sealed class FrameTxValidationTracer( CancellationToken token = default, Func? preempt = null, ulong maxVerifyGas = Eip8141Constants.MaxVerifyGas, - int maxCodeDependencies = int.MaxValue) + int maxCodeDependencies = int.MaxValue, + Address? payer = null, + UInt256 storageSlotBound = default, + bool createInDeployFrame = false, + int maxCodeBodies = 0, + long maxCodeBytes = 0) : TxTracer, ITxTracer, IFrameTxReceiptTracer, IFrameTxPrefixTracer, IInstructionTracingFilter { /// The opcodes that reach ; every other opcode runs untraced. /// Must cover every opcode the switch in handles, otherwise the rule for a missing opcode is silently skipped. /// is included only so _inRecentRootCode is current before LoadOperationStorage reads it. - public UInt256 InstructionMask => new(0x9C02_0000_0000_0000, 0x0000_0000_0430_0DBF, 0x0000_0080_0000_0000, 0xD477_0000_0000_0000); + public UInt256 InstructionMask => _codeBodies is not null ? UInt256.MaxValue : new(0x9C02_0000_0000_0000, 0x0000_0000_0430_0DBF, 0x0000_0080_0000_0000, 0xD477_0000_0000_0000); private readonly TimeProvider _time = timeProvider ?? TimeProvider.System; @@ -155,6 +177,20 @@ public override void StartOperation(int pc, Instruction opcode, ulong gas, in Ex SettleCreate(); if (Violated) return; + _codeReadPending = false; + // Execution starts in a body at its first instruction. Only a change of executing code can be such a + // start, so a loop jumping back to offset 0 costs one reference comparison, never a rehash. + if (_codeBodies is not null && !ReferenceEquals(env.CodeInfo, _executingCode)) + { + _executingCode = env.CodeInfo; + if (pc == 0 && _enteredCode!.Add(env.CodeInfo)) + { + ReadOnlySpan code = env.CodeInfo.CodeSpan; + if (!code.IsEmpty) LoadCode(env.CodeInfo.CodeHash != default ? env.CodeInfo.CodeHash : HashCode(code), code.Length); + if (Violated) return; + } + } + _inRecentRootCode = _recentRootKeys is not null && env.CallDepth == 0 && env.ExecutingAccount == Eip8272Constants.RecentRootAddress; switch (opcode) @@ -190,8 +226,11 @@ public override void StartOperation(int pc, Instruction opcode, ulong gas, in Ex _targetStackIndex = 1; // [gas, address, ...] break; case Instruction.EXTCODESIZE: - case Instruction.EXTCODEHASH: case Instruction.EXTCODECOPY: + _targetStackIndex = 0; // [address, ...] + _codeReadPending = _codeBodies is not null; + break; + case Instruction.EXTCODEHASH: _targetStackIndex = 0; // [address, ...] break; case Instruction.GASPRICE: @@ -214,15 +253,17 @@ public override void StartOperation(int pc, Instruction opcode, ulong gas, in Ex // holds at inclusion, which its owner can change with SETCODEFROM. Violate($"banned opcode {opcode} in validation prefix"); break; - case Instruction.CREATE: + case Instruction.CREATE when !createInDeployFrame || !_inDeployFrame: // Its address is f(factory, factory.nonce), which any third party can move by making the // factory create again; only CREATE2 makes the deployment a pure function of the transaction. + // Profile 2 replay judges one fixed state, so it takes the creator's nonce as given. Violate($"banned opcode {opcode} in validation prefix"); break; case Instruction.TCREATE when spec.IsEip8360Enabled: // EIP-8360: never installs code at tx.sender, the one creation the prefix admits. Violate($"banned opcode {opcode} in validation prefix"); break; + case Instruction.CREATE: case Instruction.CREATE2: // Allowed only in the deploy frame, and only to install code at tx.sender; the address is // checked when the creation frame opens. Slot 0 is the endowment, banned as a funded CALL is. @@ -256,6 +297,13 @@ public override void SetOperationStack(TraceStack stack) if (stack.Count <= index) return; Address target = stack.PeekAddress(index); + if (_codeReadPending) + { + ValueHash256 codeHash = state.GetCodeHash(target); + if (codeHash != Keccak.OfAnEmptyString.ValueHash256 && !_codeBodies!.Contains(codeHash)) LoadCode(codeHash, state.GetCode(in codeHash).Length); + if (Violated) return; + } + if (IsForbiddenCallTarget(target)) { Violate($"CALL*/EXTCODE* to disallowed target {target} in validation prefix"); @@ -280,19 +328,63 @@ public override void SetOperationStack(TraceStack stack) } } + /// Distinct code bodies loaded so far, by hash, or null when neither bound applies. + private readonly HashSet? _codeBodies = maxCodeBodies > 0 || maxCodeBytes > 0 ? [] : null; + + /// The code instances already counted, by reference: overrides equality. + private readonly HashSet? _enteredCode = maxCodeBodies > 0 || maxCodeBytes > 0 ? new(ReferenceEqualityComparer.Instance) : null; + + private CodeInfo? _executingCode; + private long _codeBytes; + private bool _codeReadPending; + + /// Bodies hashed because their code carried no stamped hash, which only initcode should need. + internal int CodeHashComputations { get; private set; } + + private ValueHash256 HashCode(ReadOnlySpan code) + { + CodeHashComputations++; + return ValueKeccak.Compute(code); + } + + /// EIP-7805: counts a code body the prefix loads against MAX_REPLAY_CODE_BODIES and MAX_REPLAY_CODE_BYTES. + private void LoadCode(in ValueHash256 codeHash, int length) + { + if (!_codeBodies!.Add(codeHash)) return; + _codeBytes += length; + if (maxCodeBodies > 0 && _codeBodies.Count > maxCodeBodies) Violate("validation code body count exceeded"); + else if (maxCodeBytes > 0 && _codeBytes > maxCodeBytes) Violate("validation code byte limit exceeded"); + } + public override void LoadOperationStorage(Address address, UInt256 storageIndex, ReadOnlySpan value) { - // SLOAD may read only tx.sender storage, including transitively via CALL*/DELEGATECALL. - if (!Violated && address != sender && !IsRecentRootKeyRead(address, storageIndex)) Violate("SLOAD outside tx.sender storage"); + // SLOAD may read only in-surface storage, including transitively via CALL*/DELEGATECALL. + if (!Violated && !InSurface(address, in storageIndex) && !IsRecentRootKeyRead(address, storageIndex)) ViolateSurface("SLOAD", address, in storageIndex); } public override void SetOperationStorage(Address address, UInt256 storageIndex, ReadOnlySpan newValue, ReadOnlySpan currentValue) { - // The carve-out is the deploy frame's alone, and covers tx.sender's storage only. Every other prefix - // frame is static, so this is belt-and-braces -- but that is an invariant held in another file. - if (!Violated && (!_inDeployFrame || address != sender)) Violate("SSTORE outside tx.sender storage"); + // The carve-out is the deploy frame's alone, and covers tx.sender's storage only -- never the payer's, + // whose slots are readable but not writable. Every other prefix frame is static. + if (Violated) return; + if (!_inDeployFrame) Violate("SSTORE outside tx.sender storage"); + else if (address != sender || !InSlotBound(in storageIndex)) ViolateSurface("SSTORE", address, in storageIndex); } + /// Whether a storage cell the prefix touched is inside the configured surface. + private bool InSurface(Address address, in UInt256 slot) => + (address == sender || (payer is not null && address == payer)) && InSlotBound(in slot); + + private bool InSlotBound(in UInt256 slot) => storageSlotBound.IsZero || slot < storageSlotBound; + + /// Records an out-of-surface storage access as a trace-rule violation. + // The default surface keeps its original wording; a widened or slot-bounded one names the cell, + // since the address alone no longer says which half of the rule failed. + private void ViolateSurface(string op, Address address, in UInt256 slot) => + Violate(payer is null && storageSlotBound.IsZero + ? $"{op} outside tx.sender storage" + : $"{op} outside the permitted storage surface at {address}:{slot}"); + public override void ReportAction(ulong gas, UInt256 value, Address from, Address to, ReadOnlyMemory input, ExecutionType callType, bool isPrecompileCall = false) { if (!callType.IsAnyCreate()) return; diff --git a/src/Nethermind/Nethermind.Evm/TransactionProcessing/ExecutionOptions.cs b/src/Nethermind/Nethermind.Evm/TransactionProcessing/ExecutionOptions.cs index eca91dec3f6a..7da545f2f6cd 100644 --- a/src/Nethermind/Nethermind.Evm/TransactionProcessing/ExecutionOptions.cs +++ b/src/Nethermind/Nethermind.Evm/TransactionProcessing/ExecutionOptions.cs @@ -57,6 +57,10 @@ public enum ExecutionOptions /// With : charge gas and value in full, so a sender that cannot pay fails the run. StrictWarmup = 256, + /// With : bound the payer by the max_cost execution escrows at the + /// block's base fees, and reject a max_fee below required_max_fee, instead of the base-fee-free max_fee. + FramePrefixAtBlockBaseFee = 512, + /// /// Skip potential fail checks and commit state after execution /// diff --git a/src/Nethermind/Nethermind.Evm/TransactionProcessing/TransactionProcessorBase.FrameTx.cs b/src/Nethermind/Nethermind.Evm/TransactionProcessing/TransactionProcessorBase.FrameTx.cs index 6818a198ac0d..86951e511d95 100644 --- a/src/Nethermind/Nethermind.Evm/TransactionProcessing/TransactionProcessorBase.FrameTx.cs +++ b/src/Nethermind/Nethermind.Evm/TransactionProcessing/TransactionProcessorBase.FrameTx.cs @@ -438,6 +438,27 @@ private TransactionResult ExecuteFrameTx(Transaction tx, ITxTracer tra assertReverted: assertReverted); } + /// Prices a prefix simulation's payer bound at 's base fees, as execution does. + private TransactionResult PricePrefixAtBlockBaseFee(Transaction tx, ExecutionOptions opts, BlockHeader header, IReleaseSpec spec, + out UInt256 maxCost, out UInt256 effectiveGasPrice) + { + maxCost = default; + effectiveGasPrice = default; + if (!FrameTxValidation.TryCalculateGasBudget(tx, spec, out _, out _, out ulong maxGas)) + { + return TransactionResult.ErrorType.MalformedTransaction.WithDetail("frame transaction maximum cost cannot be priced"); + } + + UInt256 blobFee = UInt256.Zero; + if (tx.BlobVersionedHashes is { Length: > 0 } + && !_blobBaseFeeCalculator.TryCalculateBlobFees(header, tx, spec.BlobBaseFeeUpdateFraction, out _, out blobFee)) + { + return RequiredBalanceExceeds256Bits(tx); + } + + return PriceFeeBudget(tx, opts, header, maxGas, in blobFee, out maxCost, out effectiveGasPrice); + } + /// Prices the max_fee budget at 's base fees. /// The transaction's max_gas. /// The escrow the payer's approval collects. @@ -785,14 +806,23 @@ private TransactionResult PrepareValidationPrefixSimulation( return TransactionResult.ErrorType.MalformedTransaction.WithDetail("frame transaction validation prefix exceeds MAX_VERIFY_GAS"); } - // A bound this simulation rolls back, not an escrow: shared with the admission gate so both judge the - // same number. It is max_fee, as the base fees at inclusion are unknown here. - if (!FrameTxValidation.TryCalculateMaxCost(tx, spec, out UInt256 maxCost)) + UInt256 maxCost; + if (opts.HasFlag(ExecutionOptions.FramePrefixAtBlockBaseFee)) { - return TransactionResult.ErrorType.MalformedTransaction.WithDetail("frame transaction maximum cost cannot be priced"); + TransactionResult budgetResult = PricePrefixAtBlockBaseFee(tx, opts, header, spec, out maxCost, out effectiveGasPrice); + if (!budgetResult) return budgetResult; } + else + { + // A bound this simulation rolls back, not an escrow: shared with the admission gate so both judge the + // same number. It is max_fee, as the base fees at inclusion are unknown here. + if (!FrameTxValidation.TryCalculateMaxCost(tx, spec, out maxCost)) + { + return TransactionResult.ErrorType.MalformedTransaction.WithDetail("frame transaction maximum cost cannot be priced"); + } - effectiveGasPrice = CalculateEffectiveGasPrice(tx, spec.IsEip1559Enabled, header.BaseFeePerGas, out _); + effectiveGasPrice = CalculateEffectiveGasPrice(tx, spec.IsEip1559Enabled, header.BaseFeePerGas, out _); + } frameContext = new FrameTxContext( sender, tx.Nonce, tx.Frames!, tx.FrameSignatures ?? [], tx, sigHash, in maxCost, in tx.MaxPriorityFeePerGas, diff --git a/src/Nethermind/Nethermind.Init/Modules/BlockProcessingModule.cs b/src/Nethermind/Nethermind.Init/Modules/BlockProcessingModule.cs index f0f46039193e..6ea7e037c82b 100644 --- a/src/Nethermind/Nethermind.Init/Modules/BlockProcessingModule.cs +++ b/src/Nethermind/Nethermind.Init/Modules/BlockProcessingModule.cs @@ -67,7 +67,6 @@ protected override void Load(ContainerBuilder builder) .AddScoped() .AddScoped() .AddScoped() - .AddScoped() .AddScoped() .AddScoped() .AddSingleton() @@ -94,6 +93,11 @@ protected override void Load(ContainerBuilder builder) (lifetime, worldStateManager, specProvider, blockFinder, txPoolConfig, logManager) => new FrameTxPrefixSimulator( new AutoReadOnlyTxProcessingEnvFactory(lifetime, worldStateManager, shareCodeCache: false), blockFinder, specProvider, txPoolConfig, logManager)) + // Its own code cache for the same reason: the replay materialises code the access list deploys. + .AddSingleton( + (lifetime, worldStateManager, specProvider, ecdsa, logManager) => new Profile2EligibilityReplayer( + new AutoReadOnlyTxProcessingEnvFactory(lifetime, worldStateManager, shareCodeCache: false), + ecdsa, logManager)) .Add() .AddSingleton() diff --git a/src/Nethermind/Nethermind.Merge.Plugin.Test/Data/CanonicalQuantityConverterTests.cs b/src/Nethermind/Nethermind.Merge.Plugin.Test/Data/CanonicalQuantityConverterTests.cs new file mode 100644 index 000000000000..953fe0675548 --- /dev/null +++ b/src/Nethermind/Nethermind.Merge.Plugin.Test/Data/CanonicalQuantityConverterTests.cs @@ -0,0 +1,48 @@ +// SPDX-FileCopyrightText: 2026 Demerzel Solutions Limited +// SPDX-License-Identifier: LGPL-3.0-only + +using System.Text.Json; +using Nethermind.Core; +using Nethermind.Core.Test.Builders; +using Nethermind.Serialization.Json; +using NUnit.Framework; + +namespace Nethermind.Merge.Plugin.Test.Data; + +/// An omission claim's index is a canonical QUANTITY (execution-apis common.md) however lenient the +/// serializer's own numeric parsing is. +public class CanonicalQuantityConverterTests +{ + private static readonly EthereumJsonSerializer Serializer = new(); + + [TestCase("\"0x0\"", 0UL)] + [TestCase("\"0x1\"", 1UL)] + [TestCase("\"0x1f\"", 31UL)] + [TestCase("\"0xAbC\"", 2748UL)] + [TestCase("\"0xffffffffffffffff\"", ulong.MaxValue)] + public void Reads_a_canonical_quantity(string index, ulong expected) + { + OmissionClaim claim = Serializer.Deserialize(Claim(index)); + + using (Assert.EnterMultipleScope()) + { + Assert.That(claim.EvaluationIndex, Is.EqualTo(expected)); + Assert.That(Serializer.Serialize(claim), Does.Contain($"\"evaluationIndex\":{index.ToLowerInvariant()}")); + } + } + + [TestCase("\"0x01\"", TestName = "Leading zero")] + [TestCase("\"0x00\"", TestName = "Zero with a leading zero")] + [TestCase("\"0x\"", TestName = "No digits")] + [TestCase("\"1\"", TestName = "Decimal without 0x")] + [TestCase("\"x1\"", TestName = "Prefix without 0")] + [TestCase("\"0X1\"", TestName = "Uppercase prefix")] + [TestCase("1", TestName = "JSON number")] + [TestCase("\"0x10000000000000000\"", TestName = "Over 64 bits")] + [TestCase("\"0xg\"", TestName = "Not hex")] + [TestCase("\" 0x1\"", TestName = "Leading whitespace")] + public void Rejects_a_noncanonical_quantity(string index) => + Assert.Throws(() => Serializer.Deserialize(Claim(index))); + + private static string Claim(string index) => $"{{\"transactionHash\":\"{TestItem.KeccakA}\",\"evaluationIndex\":{index}}}"; +} diff --git a/src/Nethermind/Nethermind.Merge.Plugin.Test/EngineModuleTests.Eip8369.cs b/src/Nethermind/Nethermind.Merge.Plugin.Test/EngineModuleTests.Eip8369.cs new file mode 100644 index 000000000000..5d800af457ae --- /dev/null +++ b/src/Nethermind/Nethermind.Merge.Plugin.Test/EngineModuleTests.Eip8369.cs @@ -0,0 +1,430 @@ +// SPDX-FileCopyrightText: 2026 Demerzel Solutions Limited +// SPDX-License-Identifier: LGPL-3.0-only + +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text.Json; +using System.Threading.Tasks; +using Autofac; +using Nethermind.Blockchain; +using Nethermind.Config; +using Nethermind.Consensus.Producers; +using Nethermind.Consensus.Processing; +using Nethermind.Core; +using Nethermind.Core.Crypto; +using Nethermind.Core.Extensions; +using Nethermind.Core.Specs; +using Nethermind.Core.Test.Builders; +using Nethermind.Core.Test.Container; +using Nethermind.Evm; +using Nethermind.Evm.State; +using Nethermind.Int256; +using Nethermind.JsonRpc; +using Nethermind.JsonRpc.Test; +using Nethermind.Merge.Plugin.Data; +using Nethermind.Serialization.Rlp; +using Nethermind.Specs.Forks; +using NUnit.Framework; + +namespace Nethermind.Merge.Plugin.Test; + +/// EIP-7805 omission claims and separate inclusion lists over the engine API. +/// The frame sender approves only once its slot 0 is set, which the list's second entry does, so the +/// builder's attempt at index 0 fails while the candidate is eligible at the end of the payload. +public partial class EngineModuleTests +{ + private static readonly Address Profile2Sender = TestItem.AddressD; + + [TestCase(true, TestName = "Claim from getPayloadV7 excuses the omission through newPayloadV6")] + [TestCase(false, TestName = "Without the claim the omission is judged at the end of the payload")] + public async Task Claimed_index_travels_from_getPayload_through_newPayloadV6_to_the_verdict(bool sendClaims) + { + using MergeTestBlockchain chain = await CreateProfile2Blockchain(); + IEngineRpcModule rpc = chain.EngineRpcModule; + (GetPayloadV7Result built, byte[] frameTx, byte[] enabler, _) = await BuildProfile2Payload(chain); + ExecutionPayloadV4 payload = built.ExecutionPayload; + + using (Assert.EnterMultipleScope()) + { + Assert.That(payload.Transactions, Is.EqualTo(new[] { enabler }), "only the enabling entry was appended"); + Assert.That(built.OmissionClaims, Is.EqualTo(new[] { new OmissionClaim(Keccak.Compute(frameTx), 0) })); + } + + ResultWrapper newPayload = await rpc.engine_newPayloadV6( + payload, [], Keccak.Zero, built.ExecutionRequests, AtPositions([frameTx, enabler]), sendClaims ? built.OmissionClaims : []); + + using (Assert.EnterMultipleScope()) + { + Assert.That(newPayload.Result.ResultType, Is.EqualTo(ResultType.Success), newPayload.Result.Error); + Assert.That(newPayload.Data.Status, Is.EqualTo(PayloadStatus.Valid)); + Assert.That(newPayload.Data.InclusionListSatisfied, Is.EqualTo(sendClaims)); + } + } + + /// newPayloadWithWitnessV6 carries the lists and claims as newPayloadV6 does, and its response keeps the + /// witness shape, so a completed check answers VALID whatever its verdict. + [TestCase(true, TestName = "Claims sent through newPayloadWithWitnessV6 answer VALID")] + [TestCase(false, TestName = "Without claims newPayloadWithWitnessV6 answers VALID")] + public async Task NewPayloadWithWitnessV6_carries_inclusion_lists_and_claims(bool sendClaims) + { + using MergeTestBlockchain chain = await CreateProfile2Blockchain(); + IEngineRpcModule rpc = chain.EngineRpcModule; + (GetPayloadV7Result built, byte[] frameTx, byte[] enabler, _) = await BuildProfile2Payload(chain); + ExecutionPayloadV4 payload = built.ExecutionPayload; + byte[][][] inclusionLists = AtPositions([frameTx, enabler]); + OmissionClaim[] claims = sendClaims ? built.OmissionClaims : []; + + ResultWrapper newPayload = await rpc.engine_newPayloadWithWitnessV6( + payload, [], Keccak.Zero, built.ExecutionRequests, inclusionLists, claims); + + Assert.That(newPayload.Data.Status, Is.EqualTo(PayloadStatus.Valid), newPayload.Result.Error); + } + + /// Claims change the verdict, so the same block and lists under other claims are another check. + [Test] + public async Task NewPayloadV6_classifies_candidates_by_the_forks_verify_gas_cap_whatever_the_local_cap() + { + using MergeTestBlockchain chain = await CreateProfile2Blockchain( + configure: builder => builder.AddSingleton(new BlocksConfig { FocilProfile2MaxVerifyGas = 1 })); + (GetPayloadV7Result built, byte[] frameTx, byte[] enabler, _) = await BuildProfile2Payload(chain); + + ResultWrapper newPayload = await chain.EngineRpcModule.engine_newPayloadV6( + built.ExecutionPayload, [], Keccak.Zero, built.ExecutionRequests, AtPositions([frameTx, enabler]), []); + + Assert.That(newPayload.Data.InclusionListSatisfied, Is.False, newPayload.Result.Error); + } + + [Test] + public async Task NewPayloadV6_does_not_reuse_a_verdict_checked_under_other_claims() + { + using MergeTestBlockchain chain = await CreateProfile2Blockchain(); + IEngineRpcModule rpc = chain.EngineRpcModule; + (GetPayloadV7Result built, byte[] frameTx, byte[] enabler, _) = await BuildProfile2Payload(chain); + byte[][][] inclusionLists = AtPositions([frameTx, enabler]); + + ResultWrapper claimed = await rpc.engine_newPayloadV6(built.ExecutionPayload, [], Keccak.Zero, built.ExecutionRequests, inclusionLists, built.OmissionClaims); + bool? claimedVerdict = claimed.Data.InclusionListSatisfied; + // Canonical, so the resend is answered from the result cache or the committed state, not re-executed. + Hash256 hash = built.ExecutionPayload.BlockHash; + await rpc.engine_forkchoiceUpdatedV5(new ForkchoiceStateV1(hash, hash, hash), payloadAttributes: null); + ResultWrapper unclaimed = await rpc.engine_newPayloadV6(built.ExecutionPayload, [], Keccak.Zero, built.ExecutionRequests, inclusionLists, []); + + using (Assert.EnterMultipleScope()) + { + Assert.That(claimedVerdict, Is.True); + Assert.That(unclaimed.Data.InclusionListSatisfied, Is.False); + } + } + + /// EIP-7805 § VERIFY budget over the wire: the stuffing and the candidate overrun one committee position's + /// budget and excuse the candidate, while at two positions each has its own budget and the candidate is judged. + [TestCase(true, true, TestName = "Inclusion lists fill the VERIFY budget per committee position")] + [TestCase(false, false, TestName = "Entries at separate committee positions draw on separate budgets")] + public async Task NewPayloadV6_fills_the_verify_budget_per_position(bool samePosition, bool satisfied) + { + using MergeTestBlockchain chain = await CreateProfile2Blockchain(); + // Each declares 250,000 of VERIFY gas, under MAX_VERIFY_GAS_PER_TX, so four fill a position's 1,048,576 and + // a fifth overruns it; the stuffing's senders are picked so that their hashes, and so their turns, come first. + byte[] candidate = Encode(Profile2FrameTx(chain, Profile2Sender, 250_000)); + byte[][] stuffing = [.. TestItem.Addresses.Where(a => a != Profile2Sender).Select(a => Encode(Profile2FrameTx(chain, a, 250_000))) + .Where(tx => Keccak.Compute(tx).CompareTo(Keccak.Compute(candidate)) < 0).Take(4)]; + byte[] enabler = Encode(Profile2Enabler()); + // One payload, built with all of them at one position so the candidate is tried first and omitted. + (GetPayloadV7Result built, _) = await BuildWithFcu(chain, BuildBogotaPayloadAttributes(AtPositions([.. stuffing, candidate, enabler]))); + byte[][][] inclusionLists = samePosition ? AtPositions([.. stuffing, candidate, enabler]) : AtPositions([.. stuffing, enabler], [candidate]); + Assume.That(built.ExecutionPayload.Transactions, Is.EqualTo(new[] { enabler })); + + ResultWrapper newPayload = await chain.EngineRpcModule.engine_newPayloadV6( + built.ExecutionPayload, [], Keccak.Zero, built.ExecutionRequests, inclusionLists, []); + + Assert.That(newPayload.Data.InclusionListSatisfied, Is.EqualTo(satisfied), newPayload.Result.Error); + } + + /// The claims and lists round-trip the JSON wire: getPayloadV7 writes the claims, newPayloadV6 parses + /// them back beside the separate lists and answers with the check's identifier. + [Test] + public async Task Claims_and_inclusion_lists_round_trip_the_json_wire() + { + using MergeTestBlockchain chain = await CreateProfile2Blockchain(); + IEngineRpcModule rpc = chain.EngineRpcModule; + (GetPayloadV7Result built, byte[] frameTx, byte[] enabler, string payloadId) = await BuildProfile2Payload(chain); + + using JsonDocument getPayload = JsonDocument.Parse(await RpcTest.TestSerializedRequest(rpc, "engine_getPayloadV7", payloadId)); + JsonElement result = getPayload.RootElement.GetProperty("result"); + JsonElement claims = result.GetProperty("omissionClaims"); + using (Assert.EnterMultipleScope()) + { + Assert.That(claims.GetArrayLength(), Is.EqualTo(1)); + Assert.That(claims[0].GetProperty("transactionHash").GetString(), Is.EqualTo(Keccak.Compute(frameTx).ToString())); + Assert.That(claims[0].GetProperty("evaluationIndex").GetString(), Is.EqualTo("0x0")); + } + + using JsonDocument newPayload = JsonDocument.Parse(await RpcTest.TestSerializedRequest(rpc, "engine_newPayloadV6", + result.GetProperty("executionPayload"), System.Array.Empty(), Keccak.Zero, result.GetProperty("executionRequests"), AtPositions([frameTx, enabler]), claims)); + JsonElement status = newPayload.RootElement.GetProperty("result"); + + using (Assert.EnterMultipleScope()) + { + Assert.That(status.GetProperty("status").GetString(), Is.EqualTo(PayloadStatus.Valid)); + Assert.That(status.GetProperty("inclusionListSatisfied").GetBoolean(), Is.True); + Assert.That(status.TryGetProperty("inclusionCheckId", out _), Is.False); + } + } + + /// Claims are Bogota's alone: getPayloadV6 no longer serves a Bogota payload, and getPayloadV7 serves + /// no earlier one, each answering -38005 as a getPayload version outside its fork does. + [TestCase(true, 6, false, TestName = "GetPayloadV6 rejects a Bogota payload as an unsupported fork")] + [TestCase(true, 7, true, TestName = "GetPayloadV7 serves a Bogota payload")] + [TestCase(false, 7, false, TestName = "GetPayloadV7 rejects an Amsterdam payload as an unsupported fork")] + [TestCase(false, 6, true, TestName = "GetPayloadV6 serves an Amsterdam payload")] + public async Task GetPayload_version_is_gated_by_fork(bool bogota, int version, bool served) + { + using MergeTestBlockchain chain = await CreateBlockchain(bogota ? Bogota.Instance : Amsterdam.Instance, new MergeConfig { TerminalTotalDifficulty = "0" }); + Hash256 head = chain.BlockTree.HeadHash; + PayloadAttributes attributes = BuildBogotaPayloadAttributes(inclusionList: bogota ? [] : null!); + ForkchoiceStateV1 state = new(head, Keccak.Zero, head); + string? id = bogota + ? (await chain.EngineRpcModule.engine_forkchoiceUpdatedV5(state, attributes)).Data.PayloadId + : (await chain.EngineRpcModule.engine_forkchoiceUpdatedV4(state, attributes)).Data.PayloadId; + byte[] payloadId = Bytes.FromHexString(id!); + + int errorCode = version == 7 + ? (await chain.EngineRpcModule.engine_getPayloadV7(payloadId)).ErrorCode + : (await chain.EngineRpcModule.engine_getPayloadV6(payloadId)).ErrorCode; + + Assert.That(errorCode, Is.EqualTo(served ? ErrorCodes.None : MergeErrorCodes.UnsupportedFork)); + } + + /// bogota.md makes the separate lists and claims positional in Bogota, with or without EIP-8141. + [TestCase(true, TestName = "Inclusion lists are required when EIP-8141 frames are active")] + [TestCase(false, TestName = "Inclusion lists are required under EIP-7805 alone")] + public async Task Inclusion_lists_are_required_with_or_without_frame_transactions(bool frames) + { + using MergeTestBlockchain chain = frames ? await CreateProfile2Blockchain() : await CreateBlockchain(Bogota.Instance, new MergeConfig { TerminalTotalDifficulty = "0" }); + Hash256 head = chain.BlockTree.HeadHash; + (GetPayloadV7Result built, _) = await BuildWithFcu(chain, BuildBogotaPayloadAttributes(inclusionList: [])); + + ResultWrapper withoutLists = await chain.EngineRpcModule.engine_newPayloadV6( + built.ExecutionPayload, [], Keccak.Zero, built.ExecutionRequests, null, []); + ResultWrapper withoutClaims = await chain.EngineRpcModule.engine_newPayloadV6( + built.ExecutionPayload, [], Keccak.Zero, built.ExecutionRequests, AtPositions(), null); + ResultWrapper fcu = await chain.EngineRpcModule.engine_forkchoiceUpdatedV5( + new ForkchoiceStateV1(head, Keccak.Zero, head), BuildBogotaPayloadAttributes(inclusionList: null!)); + + using (Assert.EnterMultipleScope()) + { + Assert.That(withoutLists.ErrorCode, Is.EqualTo(ErrorCodes.InvalidParams), withoutLists.Result.Error); + Assert.That(withoutClaims.ErrorCode, Is.EqualTo(ErrorCodes.InvalidParams), withoutClaims.Result.Error); + Assert.That(fcu.ErrorCode, Is.EqualTo(MergeErrorCodes.InvalidPayloadAttributes), fcu.Result.Error); + } + } + + /// The builder fills each committee position's VERIFY budget apart, in ascending hash order: the + /// stuffed position admits four of its five entries and the fifth gets no claim, while the other position's + /// candidate keeps its claim however the first spends. + [Test] + public async Task ForkchoiceUpdatedV5_builder_claims_per_committee_position() + { + using MergeTestBlockchain chain = await CreateProfile2Blockchain(); + // 250,000 each, under MAX_VERIFY_GAS_PER_TX: four fit one position's 1,048,576, a fifth does not; pooled, the + // four would exhaust the budget. + byte[][] stuffing = [.. TestItem.Addresses.Where(a => a != Profile2Sender).Take(5).Select(a => Encode(Profile2FrameTx(chain, a, 250_000)))]; + byte[] frameBytes = Encode(Profile2FrameTx(chain, Profile2Sender, 100_000)); + byte[] enablerBytes = Encode(Profile2Enabler()); + byte[][][] inclusionLists = AtPositions(stuffing, [frameBytes, enablerBytes]); + Hash256[] admittedStuffing = [.. stuffing.Select(Keccak.Compute).Order().Take(4)]; + + (GetPayloadV7Result built, _) = await BuildWithFcu(chain, BuildBogotaPayloadAttributes(inclusionLists)); + ResultWrapper newPayload = await chain.EngineRpcModule.engine_newPayloadV6( + built.ExecutionPayload, [], Keccak.Zero, built.ExecutionRequests, inclusionLists, built.OmissionClaims); + + using (Assert.EnterMultipleScope()) + { + Assert.That(built.ExecutionPayload.Transactions, Is.EqualTo(new[] { enablerBytes })); + Assert.That(built.OmissionClaims, Is.EquivalentTo( + admittedStuffing.Select(h => new OmissionClaim(h, 0)).Append(new OmissionClaim(Keccak.Compute(frameBytes), 0)))); + Assert.That(newPayload.Data.InclusionListSatisfied, Is.True, newPayload.Result.Error); + } + } + + /// PayloadAttributesV5 parses the separate lists from the wire, and they are part of the build's identity: + /// the same entries at other committee positions are a different build, since positions change the claims. + [Test] + public async Task ForkchoiceUpdatedV5_parses_inclusion_lists_into_a_distinct_build() + { + using MergeTestBlockchain chain = await CreateProfile2Blockchain(); + byte[] frameBytes = Encode(Profile2FrameTx(chain, Profile2Sender, 100_000)); + byte[] enablerBytes = Encode(Profile2Enabler()); + Hash256 head = chain.BlockTree.HeadHash; + PayloadAttributes flat = BuildBogotaPayloadAttributes(inclusionList: []); + + string[][] inclusionLists = [[frameBytes.ToHexString(true)], [enablerBytes.ToHexString(true)], .. Enumerable.Repeat(System.Array.Empty(), Eip7805Constants.InclusionListCommitteeSize - 2)]; + using JsonDocument parsed = JsonDocument.Parse(await RpcTest.TestSerializedRequest(chain.EngineRpcModule, "engine_forkchoiceUpdatedV5", + new ForkchoiceStateV1(head, Keccak.Zero, head), + new + { + timestamp = flat.Timestamp.ToHexString(true), + prevRandao = flat.PrevRandao, + suggestedFeeRecipient = flat.SuggestedFeeRecipient, + withdrawals = System.Array.Empty(), + parentBeaconBlockRoot = flat.ParentBeaconBlockRoot, + slotNumber = flat.SlotNumber!.Value.ToHexString(true), + targetGasLimit = flat.TargetGasLimit!.Value.ToHexString(true), + inclusionLists, + })); + ResultWrapper samePositions = await chain.EngineRpcModule.engine_forkchoiceUpdatedV5( + new ForkchoiceStateV1(head, Keccak.Zero, head), BuildBogotaPayloadAttributes(AtPositions([frameBytes], [enablerBytes]))); + ResultWrapper otherPositions = await chain.EngineRpcModule.engine_forkchoiceUpdatedV5( + new ForkchoiceStateV1(head, Keccak.Zero, head), BuildBogotaPayloadAttributes(AtPositions([frameBytes, enablerBytes]))); + + string? parsedId = parsed.RootElement.GetProperty("result").GetProperty("payloadId").GetString(); + using (Assert.EnterMultipleScope()) + { + Assert.That(parsedId, Is.EqualTo(samePositions.Data.PayloadId), parsed.RootElement.ToString()); + Assert.That(parsedId, Is.Not.EqualTo(otherPositions.Data.PayloadId)); + } + } + + [Test] + public async Task Unknown_gas_dimensions_share_profile_2_replay_verdicts() + { + IneligibleReplayer replayer = new(); + using MergeTestBlockchain chain = await CreateProfile2Blockchain( + new MergeConfig { TerminalTotalDifficulty = "0", NewPayloadCacheSize = 0 }, + builder => builder.AddSingleton(replayer)); + (GetPayloadV7Result built, byte[] frameTx, byte[] enabler, _) = await BuildProfile2Payload(chain); + ExecutionPayloadV4 payload = built.ExecutionPayload; + byte[][][] inclusionLists = AtPositions([frameTx, enabler]); + IEngineRpcModule rpc = chain.EngineRpcModule; + ResultWrapper first = await rpc.engine_newPayloadV6(payload, [], Keccak.Zero, built.ExecutionRequests, inclusionLists, []); + Assert.That(first.Data.InclusionListSatisfied, Is.Not.Null); + await rpc.engine_forkchoiceUpdatedV5(new ForkchoiceStateV1(payload.BlockHash, payload.BlockHash, payload.BlockHash), null); + chain.BlockTree.FindHeader(payload.BlockHash, BlockTreeLookupOptions.TotalDifficultyNotNeeded)!.GasUsedPerDimension = null; + replayer.Batches = 0; + + // A claim at the end of the payload names another check of the same block, run without the gas dimensions. + ResultWrapper resent = await rpc.engine_newPayloadV6(payload, [], Keccak.Zero, built.ExecutionRequests, inclusionLists, + [new OmissionClaim(Keccak.Compute(frameTx), (ulong)payload.Transactions.Length)]); + + using (Assert.EnterMultipleScope()) + { + Assert.That(resent.Data.InclusionListSatisfied, Is.True); + Assert.That(replayer.Batches, Is.EqualTo(1)); + } + } + + private sealed class IneligibleReplayer : IProfile2EligibilityReplayer + { + public int Batches { get; set; } + public bool AreSignaturesValid(Transaction transaction, IReleaseSpec spec) => true; + public bool?[] AreEligible(Block block, IReadOnlyList<(Transaction Transaction, int Index)> requests, IReleaseSpec spec) + { + Batches++; + return [.. requests.Select(_ => (bool?)false)]; + } + } + + private sealed class UndecidedOnceReplayer : IProfile2EligibilityReplayer + { + public int Batches { get; private set; } + public bool AreSignaturesValid(Transaction transaction, IReleaseSpec spec) => true; + public bool?[] AreEligible(Block block, IReadOnlyList<(Transaction Transaction, int Index)> requests, IReleaseSpec spec) + { + Batches++; + return Batches == 1 ? new bool?[requests.Count] : [.. requests.Select(_ => (bool?)false)]; + } + } + + [Test] + public async Task An_undecided_replay_is_not_kept_as_a_verdict_and_the_check_is_asked_again() + { + UndecidedOnceReplayer replayer = new(); + using MergeTestBlockchain chain = await CreateProfile2Blockchain( + new MergeConfig { TerminalTotalDifficulty = "0", NewPayloadCacheSize = 0 }, + builder => builder.AddSingleton(replayer)); + (GetPayloadV7Result built, byte[] frameTx, byte[] enabler, _) = await BuildProfile2Payload(chain); + ExecutionPayloadV4 payload = built.ExecutionPayload; + byte[][][] inclusionLists = AtPositions([frameTx, enabler]); + IEngineRpcModule rpc = chain.EngineRpcModule; + + ResultWrapper first = await rpc.engine_newPayloadV6(payload, [], Keccak.Zero, built.ExecutionRequests, inclusionLists, []); + bool? undecided = first.Data.InclusionListSatisfied; + await rpc.engine_forkchoiceUpdatedV5(new ForkchoiceStateV1(payload.BlockHash, payload.BlockHash, payload.BlockHash), null); + ResultWrapper asked = await rpc.engine_newPayloadV6(payload, [], Keccak.Zero, built.ExecutionRequests, inclusionLists, []); + + using (Assert.EnterMultipleScope()) + { + Assert.That(undecided, Is.Null); + Assert.That(first.Data.Status, Is.EqualTo(PayloadStatus.Syncing)); + Assert.That(asked.Data.InclusionListSatisfied, Is.True); + Assert.That(replayer.Batches, Is.EqualTo(2)); + } + } + + private async Task CreateProfile2Blockchain(MergeConfig? config = null, Action? configure = null) => + await CreateBlockchain( + Eip8369Prototype.Instance, + config ?? new MergeConfig { TerminalTotalDifficulty = "0" }, + configurer: builder => + { + configure?.Invoke(builder); + builder.AddScoped((worldState, specProvider) => + new FunctionalGenesisPostProcessor(_ => + { + worldState.CreateAccount(Profile2Sender, 10.Ether); + worldState.InsertCode(Profile2Sender, ApproveOnceSlotIsSet, specProvider.GenesisSpec); + worldState.RecalculateStateRoot(); + })); + }); + + /// Builds on the head with [frame transaction, enabler], in that order, at committee position 0. + private async Task<(GetPayloadV7Result Built, byte[] FrameTx, byte[] Enabler, string PayloadId)> BuildProfile2Payload(MergeTestBlockchain chain) + { + byte[] frameBytes = Encode(Profile2FrameTx(chain, Profile2Sender, 100_000)); + byte[] enablerBytes = Encode(Profile2Enabler()); + (GetPayloadV7Result built, string payloadId) = await BuildWithFcu(chain, BuildBogotaPayloadAttributes(AtPositions([frameBytes, enablerBytes]))); + return (built, frameBytes, enablerBytes, payloadId); + } + + private static async Task<(GetPayloadV7Result Built, string PayloadId)> BuildWithFcu(MergeTestBlockchain chain, PayloadAttributes attributes) + { + Hash256 head = chain.BlockTree.HeadHash; + ResultWrapper fcu = await chain.EngineRpcModule.engine_forkchoiceUpdatedV5(new ForkchoiceStateV1(head, Keccak.Zero, head), attributes); + Assert.That(fcu.Data?.PayloadId, Is.Not.Null, fcu.Result.Error); + ResultWrapper built = await chain.EngineRpcModule.engine_getPayloadV7(Bytes.FromHexString(fcu.Data!.PayloadId!)); + return (built.Data!, fcu.Data.PayloadId!); + } + + private static Transaction Profile2FrameTx(MergeTestBlockchain chain, Address sender, ulong verifyGas) => new() + { + Type = TxType.FrameTx, + ChainId = chain.SpecProvider.ChainId, + Nonce = 0, + SenderAddress = sender, + NonceKeys = [], + Frames = [new TxFrame(FrameMode.Verify, FrameFlags.ApproveExecutionAndPayment, target: null, verifyGas, UInt256.Zero, default)], + FrameSignatures = [], + GasPrice = 2.GWei, + DecodedMaxFeePerGas = 10.GWei, + MaxFee = 1.Ether, + }; + + private static Transaction Profile2Enabler() => Build.A.Transaction + .WithNonce(0).WithMaxFeePerGas(10.GWei).WithMaxPriorityFeePerGas(2.GWei).WithGasLimit(1_000_000) + .WithType(TxType.EIP1559).WithTo(Profile2Sender).WithData([1]).SignedAndResolved(TestItem.PrivateKeyB).TestObject; + + private static byte[] Encode(Transaction tx) => TxDecoder.Instance.Encode(tx, RlpBehaviors.SkipTypedWrapping); + + // Called with calldata it sets slot 0; as a VERIFY frame it approves only once slot 0 is nonzero. + private static readonly byte[] ApproveOnceSlotIsSet = + [ + (byte)Instruction.CALLDATASIZE, (byte)Instruction.PUSH1, 0x13, (byte)Instruction.JUMPI, + (byte)Instruction.PUSH1, 0, (byte)Instruction.SLOAD, (byte)Instruction.ISZERO, + (byte)Instruction.PUSH1, 0x1a, (byte)Instruction.JUMPI, + (byte)Instruction.PUSH1, (byte)FrameFlags.ApproveExecutionAndPayment, + (byte)Instruction.PUSH1, 0, (byte)Instruction.PUSH1, 0, (byte)Instruction.APPROVE, (byte)Instruction.STOP, + (byte)Instruction.JUMPDEST, (byte)Instruction.PUSH1, 1, (byte)Instruction.PUSH1, 0, (byte)Instruction.SSTORE, (byte)Instruction.STOP, + (byte)Instruction.JUMPDEST, (byte)Instruction.PUSH1, 0, (byte)Instruction.PUSH1, 0, (byte)Instruction.REVERT, + ]; +} diff --git a/src/Nethermind/Nethermind.Merge.Plugin.Test/EngineModuleTests.V1.cs b/src/Nethermind/Nethermind.Merge.Plugin.Test/EngineModuleTests.V1.cs index cbc11673a9fa..b1617e2914e4 100644 --- a/src/Nethermind/Nethermind.Merge.Plugin.Test/EngineModuleTests.V1.cs +++ b/src/Nethermind/Nethermind.Merge.Plugin.Test/EngineModuleTests.V1.cs @@ -2280,14 +2280,6 @@ public void OnWait(Hash256 blockHash) { if (blockHash == Volatile.Read(ref _watched)) WaitEntered.TrySetResult(); } - - /// Completes once the handler waits for a watched block to leave the queue while a copy of it is still there. - public TaskCompletionSource RemovalWaitPending { get; } = new(TaskCreationOptions.RunContinuationsAsynchronously); - - public void OnRemovalWait(Hash256 blockHash, bool pending) - { - if (pending && blockHash == Volatile.Read(ref _watched)) RemovalWaitPending.TrySetResult(); - } } /// Passes every call through, reporting the handler's commit waits to a . @@ -2327,12 +2319,7 @@ private bool IsCalledFromHandler() return false; } - public ValueTask WaitUntilRemovedAsync(Hash256 blockHash, bool executedOnly = false) - { - ValueTask wait = inner.WaitUntilRemovedAsync(blockHash, executedOnly); - if (IsCalledFromHandler()) probe.OnRemovalWait(blockHash, !wait.IsCompleted); - return wait; - } + public ValueTask WaitUntilRemovedAsync(Hash256 blockHash, bool executedOnly = false) => inner.WaitUntilRemovedAsync(blockHash, executedOnly); public void Start() => inner.Start(); diff --git a/src/Nethermind/Nethermind.Merge.Plugin.Test/EngineModuleTests.V3.cs b/src/Nethermind/Nethermind.Merge.Plugin.Test/EngineModuleTests.V3.cs index 02f4654c7d34..d4ab5ea4e234 100644 --- a/src/Nethermind/Nethermind.Merge.Plugin.Test/EngineModuleTests.V3.cs +++ b/src/Nethermind/Nethermind.Merge.Plugin.Test/EngineModuleTests.V3.cs @@ -640,6 +640,7 @@ public async Task NewPayloadV3_should_verify_blob_versioned_hashes_again Substitute.For>(), Substitute.For>(), Substitute.For>(), + Substitute.For>(), newPayloadHandlerMock, Substitute.For(), Substitute.For, IReadOnlyList>>(), @@ -653,7 +654,7 @@ public async Task NewPayloadV3_should_verify_blob_versioned_hashes_again Substitute.For(), Substitute.For>(), Substitute.For(), - Substitute.For(), + Substitute.For(), Substitute.For, NewPayloadWithWitnessV1Result>>(), Substitute.For, NewPayloadWithWitnessV1Result>>(), Substitute.For>(), @@ -662,8 +663,7 @@ public async Task NewPayloadV3_should_verify_blob_versioned_hashes_again chain.SpecProvider, chain.Container.Resolve(), chain.BlockProcessingQueue, - Substitute.For(), - chain.BlockTree)); + 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 f76885d822e5..08b4f07e4c76 100644 --- a/src/Nethermind/Nethermind.Merge.Plugin.Test/EngineModuleTests.V4.cs +++ b/src/Nethermind/Nethermind.Merge.Plugin.Test/EngineModuleTests.V4.cs @@ -418,7 +418,7 @@ public async Task NewPayload_returns_unsupported_fork_outside_its_fork_wind EngineApiVersions.NewPayload.V3 => (await rpc.engine_newPayloadV3(ExecutionPayloadV3.Create(block), [], Keccak.Zero)).ErrorCode, EngineApiVersions.NewPayload.V4 => (await rpc.engine_newPayloadV4(ExecutionPayloadV3.Create(block), [], Keccak.Zero, [])).ErrorCode, EngineApiVersions.NewPayload.V5 => (await rpc.engine_newPayloadV5(ExecutionPayloadV4.Create(block), [], Keccak.Zero, [])).ErrorCode, - EngineApiVersions.NewPayload.V6 => (await rpc.engine_newPayloadV6(ExecutionPayloadV4.Create(block), [], Keccak.Zero, [], [])).ErrorCode, + EngineApiVersions.NewPayload.V6 => (await rpc.engine_newPayloadV6(ExecutionPayloadV4.Create(block), [], Keccak.Zero, [], AtPositions(), [])).ErrorCode, _ => throw new ArgumentOutOfRangeException(nameof(version)) }; } diff --git a/src/Nethermind/Nethermind.Merge.Plugin.Test/EngineModuleTests.V7.cs b/src/Nethermind/Nethermind.Merge.Plugin.Test/EngineModuleTests.V7.cs index 22fa2930d160..521cd3e9a270 100644 --- a/src/Nethermind/Nethermind.Merge.Plugin.Test/EngineModuleTests.V7.cs +++ b/src/Nethermind/Nethermind.Merge.Plugin.Test/EngineModuleTests.V7.cs @@ -4,8 +4,10 @@ using System; using System.Collections.Concurrent; using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; using System.Linq; using System.Runtime.CompilerServices; +using System.Text.Json; using System.Text.Json.Nodes; using System.Threading; using System.Threading.Tasks; @@ -14,6 +16,7 @@ using Nethermind.Blockchain.BlockAccessLists; using Nethermind.Blockchain.Tracing; using Nethermind.Consensus; +using Nethermind.Consensus.Decoders; using Nethermind.Consensus.ExecutionRequests; using Nethermind.Consensus.Processing; using Nethermind.Consensus.Producers; @@ -28,7 +31,6 @@ using Nethermind.Core.Test.Builders; using Nethermind.Core.Threading; using Nethermind.Core.Test.Container; -using Nethermind.Core.Test.Threading; using Nethermind.Core.Utils; using Nethermind.Crypto; using Nethermind.Evm; @@ -60,13 +62,13 @@ public void Inclusion_list_bal_view_skips_state_for_full_or_included_blocks([Val { Transaction entry = BuildInclusionListTransfer(); Block block = Build.A.Block.WithGasLimit(30_000_000).WithGasUsed(fullBlock ? 30_000_000UL : 0) - .WithTransactions(fullBlock ? [] : [entry]).WithInclusionListTransactions([entry]).TestObject; + .WithTransactions(fullBlock ? [] : [entry]).TestObject; IReadOnlyStateProvider committed = Substitute.For(); IReadOnlyStateProvider parent = Substitute.For(); InclusionListCommittedState state = new(committed, (uint)block.Transactions.Length + 1, () => throw new AssertionException("The validator must not decode an unused BAL."), () => parent); - bool satisfied = InclusionListValidator.IsSatisfied(block, state, Bogota.Instance, Substitute.For()); + bool satisfied = InclusionListValidator.IsSatisfied(block, [[entry]], state, Bogota.Instance, Substitute.For(), 0, null); Assert.That(satisfied, Is.True); committed.DidNotReceive().TryGetAccount(Arg.Any
(), out Arg.Any()); @@ -244,11 +246,10 @@ public async Task Inclusion_list_recheck_needs_a_valid_bal_only_for_account_chec configurer: builder => builder.UpdateSingleton(inner => inner.AddSingleton(unavailable))); IEngineRpcModule rpc = chain.EngineRpcModule; ExecutionPayloadV4 payload = await BuildAndInsertEmptyBlock(chain, chain.BlockTree.HeadHash, 2); - chain.BlockTree.FindBlock(payload.BlockHash, BlockTreeLookupOptions.None)!.BlockAccessList = reason == UnavailableBal.CarriedMismatch - ? new ReadOnlyBlockAccessList([], 0, Keccak.Zero) : null; byte[][] list = omittedEntry ? [Rlp.Encode(BuildInclusionListTransfer())] : []; - bool? result = chain.Container.Resolve().TryEvaluate(payload.BlockHash, list); + bool? result = await Recheck(chain, payload, list, reason == UnavailableBal.CarriedMismatch + ? new ReadOnlyBlockAccessList([], 0, Keccak.Zero) : null); Assert.That(result, Is.EqualTo(omittedEntry ? (bool?)null : true)); } @@ -261,9 +262,7 @@ public async Task NewPayloadV6_ignores_blob_entries_without_hiding_ordinary_omis using MergeTestBlockchain chain = await CreateBlockchain(Bogota.Instance, new MergeConfig { TerminalTotalDifficulty = "0" }); IEngineRpcModule rpc = chain.EngineRpcModule; Hash256 parent = chain.BlockTree.HeadHash; - ResultWrapper build = await rpc.engine_forkchoiceUpdatedV5( - new ForkchoiceStateV1(parent, Keccak.Zero, parent), BuildBogotaPayloadAttributes(inclusionList: [])); - ResultWrapper built = await rpc.engine_getPayloadV6(Bytes.FromHexString(build.Data.PayloadId!)); + ResultWrapper built = await BuildBogotaPayload(rpc, parent, BuildBogotaPayloadAttributes(inclusionList: [])); ExecutionPayloadV4 payload = built.Data!.ExecutionPayload; Assert.That(payload.Transactions, Is.Empty); Transaction blob = Build.A.Transaction.WithType(TxType.Blob).WithNonce(0).WithGasLimit(100_000) @@ -272,11 +271,11 @@ public async Task NewPayloadV6_ignores_blob_entries_without_hiding_ordinary_omis byte[][] list = ordinaryOmitted ? [Rlp.Encode(blob), Rlp.Encode(BuildInclusionListTransfer())] : [Rlp.Encode(blob)]; - ResultWrapper result = await rpc.engine_newPayloadV6(payload, [], Keccak.Zero, built.Data.ExecutionRequests, list); + ResultWrapper result = await NewPayloadV6(rpc, payload, built.Data.ExecutionRequests, list); Assert.That(result.Data.Status, Is.EqualTo(PayloadStatus.Valid)); await rpc.engine_forkchoiceUpdatedV5( new ForkchoiceStateV1(payload.BlockHash, payload.BlockHash, payload.BlockHash), payloadAttributes: null); - bool? rechecked = chain.Container.Resolve().TryEvaluate(payload.BlockHash, list); + bool? rechecked = await Recheck(chain, payload, list); using (Assert.EnterMultipleScope()) { @@ -285,19 +284,6 @@ await rpc.engine_forkchoiceUpdatedV5( } } - [Test] - public async Task Inclusion_list_recheck_requires_executed_block([Values] bool executed) - { - using MergeTestBlockchain chain = await CreateBlockchain(Bogota.Instance, new MergeConfig { TerminalTotalDifficulty = "0" }); - ExecutionPayloadV4 payload = await BuildAndInsertEmptyBlock(chain, chain.BlockTree.HeadHash, 2); - chain.BlockTree.GetInfo(payload.BlockNumber, payload.BlockHash).Info!.WasProcessed = executed; - - bool? answer = chain.Container.Resolve().TryEvaluate(payload.BlockHash, - [Rlp.Encode(BuildInclusionListTransfer())]); - - Assert.That(answer, Is.EqualTo(executed ? false : (bool?)null)); - } - [Test] public async Task NewPayloadV6_rechecks_changed_list_before_finalization([Values] FinalizationChange change) { @@ -336,29 +322,25 @@ public async Task NewPayloadV6_rechecks_changed_list_before_finalization([Values }))); IEngineRpcModule rpc = chain.EngineRpcModule; Hash256 parent = chain.BlockTree.HeadHash; - PayloadAttributes attributes = BuildBogotaPayloadAttributes([]); + PayloadAttributes attributes = BuildBogotaPayloadAttributes(inclusionList: []); if (change == FinalizationChange.Withdrawal) attributes.Withdrawals = [Build.A.Withdrawal.WithRecipient(sender).WithAmount(1_000_000_000).TestObject]; - ResultWrapper build = await rpc.engine_forkchoiceUpdatedV5(new(parent, Keccak.Zero, parent), attributes); - ResultWrapper built = await rpc.engine_getPayloadV6(Bytes.FromHexString(build.Data.PayloadId!)); + ResultWrapper built = await BuildBogotaPayload(rpc, parent, attributes); ExecutionPayloadV4 payload = built.Data!.ExecutionPayload; - ResultWrapper initial = await rpc.engine_newPayloadV6(payload, [], Keccak.Zero, built.Data.ExecutionRequests, []); + ResultWrapper initial = await NewPayloadV6(rpc, payload, built.Data.ExecutionRequests, []); Assert.That(initial.Data.Status, Is.EqualTo(PayloadStatus.Valid)); await rpc.engine_forkchoiceUpdatedV5(new(payload.BlockHash, payload.BlockHash, payload.BlockHash), null); Transaction omitted = Build.A.Transaction.WithNonce(0).WithMaxFeePerGas(10.GWei).WithMaxPriorityFeePerGas(2.GWei) .WithGasLimit(100_000).WithValue(0).WithTo(TestItem.AddressA).SignedAndResolved(TestItem.PrivateKeyD).TestObject; byte[][] inclusionList = [Rlp.Encode(omitted)]; - ResultWrapper resend = await rpc.engine_newPayloadV6(payload, [], Keccak.Zero, built.Data.ExecutionRequests, inclusionList); - ResultWrapper forkchoice = await rpc.engine_forkchoiceUpdatedV5(new(payload.BlockHash, payload.BlockHash, payload.BlockHash), null); - chain.BlockTree.FindBlock(payload.BlockHash, BlockTreeLookupOptions.None)!.BlockAccessList = null; - bool? storedAnswer = chain.Container.Resolve().TryEvaluate(payload.BlockHash, inclusionList); + ResultWrapper resend = await NewPayloadV6(rpc, payload, built.Data.ExecutionRequests, inclusionList); + bool? storedAnswer = await Recheck(chain, payload, inclusionList); bool expected = change is FinalizationChange.Funding or FinalizationChange.Withdrawal or FinalizationChange.Code; using (Assert.EnterMultipleScope()) { Assert.That(resend.Data.Status, Is.EqualTo(PayloadStatus.Valid)); Assert.That(resend.Data.InclusionListSatisfied, Is.EqualTo(expected)); - Assert.That(forkchoice.Data.PayloadStatus.InclusionListSatisfied, Is.EqualTo(expected)); Assert.That(storedAnswer, Is.EqualTo(expected)); } } @@ -384,7 +366,7 @@ public async Task Should_process_block_as_expected_V7() PayloadAttributes payloadAttrs = BuildBogotaPayloadAttributes(inclusionList: []); ForkchoiceStateV1 fcuState = new(startingHead, Keccak.Zero, startingHead); - ResultWrapper fcuResult = await rpc.engine_forkchoiceUpdatedV5(fcuState, payloadAttrs); + ResultWrapper fcuResult = await rpc.engine_forkchoiceUpdatedV5(fcuState, payloadAttrs); using (Assert.EnterMultipleScope()) { Assert.That(fcuResult.Result.ResultType, Is.EqualTo(ResultType.Success), fcuResult.Result.Error); @@ -392,28 +374,23 @@ public async Task Should_process_block_as_expected_V7() Assert.That(fcuResult.Data.PayloadId, Is.Not.Null); } - ResultWrapper payloadResult = await rpc.engine_getPayloadV6(Bytes.FromHexString(fcuResult.Data.PayloadId!)); + ResultWrapper payloadResult = await rpc.engine_getPayloadV7(Bytes.FromHexString(fcuResult.Data.PayloadId!)); Assert.That(payloadResult.Data, Is.Not.Null); ExecutionPayloadV4 executionPayload = payloadResult.Data!.ExecutionPayload; Assert.That(executionPayload.Transactions, Is.Empty); - ResultWrapper newPayload = await rpc.engine_newPayloadV6( - executionPayload, - blobVersionedHashes: [], - parentBeaconBlockRoot: Keccak.Zero, - executionRequests: payloadResult.Data!.ExecutionRequests, - inclusionListTransactions: []); + ResultWrapper newPayload = await NewPayloadV6(rpc, executionPayload, payloadResult.Data!.ExecutionRequests, []); using (Assert.EnterMultipleScope()) { Assert.That(newPayload.Result.ResultType, Is.EqualTo(ResultType.Success), newPayload.Result.Error); Assert.That(newPayload.Data.Status, Is.EqualTo(PayloadStatus.Valid)); - Assert.That(newPayload.Data.InclusionListSatisfied, Is.True); Assert.That(newPayload.Data.LatestValidHash, Is.EqualTo(executionPayload.BlockHash)); + Assert.That(newPayload.Data.InclusionListSatisfied, Is.True); } // VALID comes before the commit, which the forkchoice waits for only a bounded time before answering SYNCING. await chain.WaitForCommitted(executionPayload.BlockHash); - ResultWrapper finalFcu = await rpc.engine_forkchoiceUpdatedV5( + ResultWrapper finalFcu = await rpc.engine_forkchoiceUpdatedV5( new ForkchoiceStateV1(executionPayload.BlockHash, executionPayload.BlockHash, executionPayload.BlockHash), payloadAttributes: null); using (Assert.EnterMultipleScope()) @@ -422,8 +399,6 @@ public async Task Should_process_block_as_expected_V7() Assert.That(finalFcu.Data.PayloadStatus.Status, Is.EqualTo(PayloadStatus.Valid)); Assert.That(finalFcu.Data.PayloadStatus.LatestValidHash, Is.EqualTo(executionPayload.BlockHash)); Assert.That(finalFcu.Data.PayloadId, Is.Null); - // execution-apis#609: FCU V5 reports the head's inclusion-list compliance retained from newPayloadV6. - Assert.That(finalFcu.Data.PayloadStatus.InclusionListSatisfied, Is.True); } } @@ -434,224 +409,163 @@ public async Task NewPayloadV6_accepts_empty_hex_logs_bloom_of_log_less_block([V using MergeTestBlockchain chain = await CreateBlockchain(spec, new MergeConfig { TerminalTotalDifficulty = "0" }); IEngineRpcModule rpc = chain.EngineRpcModule; Hash256 startingHead = chain.BlockTree.HeadHash; - ResultWrapper fcuResult = await rpc.engine_forkchoiceUpdatedV5( + ResultWrapper fcuResult = await rpc.engine_forkchoiceUpdatedV5( new ForkchoiceStateV1(startingHead, Keccak.Zero, startingHead), BuildBogotaPayloadAttributes(inclusionList: [])); - ResultWrapper payloadResult = await rpc.engine_getPayloadV6(Bytes.FromHexString(fcuResult.Data.PayloadId!)); + ResultWrapper payloadResult = await rpc.engine_getPayloadV7(Bytes.FromHexString(fcuResult.Data.PayloadId!)); // Before EIP-7668 "0x" reads as the zero bloom, so the hash computed over 256 zero bytes still matches. JsonNode payloadJson = JsonNode.Parse(chain.JsonSerializer.Serialize(payloadResult.Data!.ExecutionPayload))!; payloadJson["logsBloom"] = "0x"; ExecutionPayloadV4 executionPayload = chain.JsonSerializer.Deserialize(payloadJson.ToJsonString())!; - ResultWrapper newPayload = await rpc.engine_newPayloadV6( - executionPayload, [], Keccak.Zero, payloadResult.Data!.ExecutionRequests, []); + ResultWrapper newPayload = await NewPayloadV6(rpc, executionPayload, payloadResult.Data!.ExecutionRequests, []); Assert.That(newPayload.Data.Status, Is.EqualTo(PayloadStatus.Valid), newPayload.Data.ValidationError); } - [Test] - public async Task ForkchoiceUpdatedV5_reports_head_inclusion_list_unsatisfied() - { - using MergeTestBlockchain chain = await CreateBlockchain(Bogota.Instance, new MergeConfig { TerminalTotalDifficulty = "0" }); - IEngineRpcModule rpc = chain.EngineRpcModule; - Hash256 startingHead = chain.BlockTree.HeadHash; - - ResultWrapper build = await rpc.engine_forkchoiceUpdatedV5( - new ForkchoiceStateV1(startingHead, Keccak.Zero, startingHead), - BuildBogotaPayloadAttributes(inclusionList: [])); - ResultWrapper payloadResult = await rpc.engine_getPayloadV6(Bytes.FromHexString(build.Data.PayloadId!)); - ExecutionPayloadV4 emptyPayload = payloadResult.Data!.ExecutionPayload; - - // Deliver the empty block with a censoring IL → newPayloadV6 retains inclusionListSatisfied=false. - Transaction censoredTx = Build.A.Transaction - .WithNonce(0).WithMaxFeePerGas(10.GWei).WithMaxPriorityFeePerGas(2.GWei).WithGasLimit(100_000) - .WithTo(TestItem.AddressA).SignedAndResolved(TestItem.PrivateKeyB).TestObject; - ResultWrapper np = await rpc.engine_newPayloadV6( - emptyPayload, [], Keccak.Zero, payloadResult.Data!.ExecutionRequests, [Rlp.Encode(censoredTx)]); - Assert.That(np.Data.InclusionListSatisfied, Is.False); - - // FCU V5 to that VALID head reports the retained compliance. - ResultWrapper fcu = await rpc.engine_forkchoiceUpdatedV5( - new ForkchoiceStateV1(emptyPayload.BlockHash, startingHead, startingHead), - payloadAttributes: null); - using (Assert.EnterMultipleScope()) - { - Assert.That(fcu.Data.PayloadStatus.Status, Is.EqualTo(PayloadStatus.Valid)); - Assert.That(fcu.Data.PayloadStatus.InclusionListSatisfied, Is.False); - } - } - [Test] public async Task NewPayloadV6_should_report_unsatisfied_inclusion_list() { using MergeTestBlockchain chain = await CreateBlockchain(Bogota.Instance, new MergeConfig { TerminalTotalDifficulty = "0" }); IEngineRpcModule rpc = chain.EngineRpcModule; - Hash256 startingHead = chain.BlockTree.HeadHash; - - // Let the engine compute the hashes so the test stays stable across unrelated changes. - ResultWrapper baselineFcu = await rpc.engine_forkchoiceUpdatedV5( - new ForkchoiceStateV1(startingHead, Keccak.Zero, startingHead), - BuildBogotaPayloadAttributes(inclusionList: [])); - ResultWrapper baselinePayload = await rpc.engine_getPayloadV6(Bytes.FromHexString(baselineFcu.Data.PayloadId!)); - ExecutionPayloadV4 emptyPayload = baselinePayload.Data!.ExecutionPayload; + ExecutionPayloadV4 emptyPayload = await BuildEmptyPayload(rpc, chain.BlockTree.HeadHash); - // Censored tx: a normal transfer that fits in the empty payload → IL unsatisfied. - Transaction censoredTx = Build.A.Transaction - .WithNonce(0) - .WithMaxFeePerGas(10.GWei) - .WithMaxPriorityFeePerGas(2.GWei) - .WithGasLimit(100_000) - .WithTo(TestItem.AddressA) - .SignedAndResolved(TestItem.PrivateKeyB) - .TestObject; - byte[][] inclusionList = [Rlp.Encode(censoredTx)]; - - ResultWrapper result = await rpc.engine_newPayloadV6( - emptyPayload, - blobVersionedHashes: [], - parentBeaconBlockRoot: Keccak.Zero, - executionRequests: baselinePayload.Data!.ExecutionRequests, - inclusionListTransactions: inclusionList); + // A transfer that fits the empty payload, so its omission is censorship. + ResultWrapper result = await NewPayloadV6(rpc, emptyPayload, [], [Rlp.Encode(BuildInclusionListTransfer())]); - // execution-apis#609: a censoring payload stays VALID and reports inclusionListSatisfied=false. + // EIP-7805: a censoring payload stays VALID, and its inclusion check completes unsatisfied. using (Assert.EnterMultipleScope()) { Assert.That(result.Result.ResultType, Is.EqualTo(ResultType.Success), result.Result.Error); Assert.That(result.Data.Status, Is.EqualTo(PayloadStatus.Valid)); - Assert.That(result.Data.InclusionListSatisfied, Is.False); Assert.That(result.Data.LatestValidHash, Is.EqualTo(emptyPayload.BlockHash)); + Assert.That(result.Data.InclusionListSatisfied, Is.False); } } - // Also pins that forkchoiceUpdatedV5 reports the answer for the latest list, whichever order they arrive in. + /// bogota.md § Inclusion checking: one payload under other inputs is checked again, each answer for its + /// own inputs. [Test] - public async Task NewPayloadV6_should_revalidate_same_block_against_new_inclusion_list([Values] bool censoringListLast) + public async Task NewPayloadV6_checks_the_same_block_against_each_call_s_inclusion_lists([Values] bool censoringListLast) { using MergeTestBlockchain chain = await CreateBlockchain(Bogota.Instance, new MergeConfig { TerminalTotalDifficulty = "0" }); IEngineRpcModule rpc = chain.EngineRpcModule; - Hash256 startingHead = chain.BlockTree.HeadHash; - - ResultWrapper fcu = await rpc.engine_forkchoiceUpdatedV5( - new ForkchoiceStateV1(startingHead, Keccak.Zero, startingHead), - BuildBogotaPayloadAttributes(inclusionList: [])); - ResultWrapper payloadResult = await rpc.engine_getPayloadV6(Bytes.FromHexString(fcu.Data.PayloadId!)); - ExecutionPayloadV4 emptyPayload = payloadResult.Data!.ExecutionPayload; + ExecutionPayloadV4 emptyPayload = await BuildEmptyPayload(rpc, chain.BlockTree.HeadHash); byte[][] censoringList = [Rlp.Encode(BuildInclusionListTransfer())]; - ResultWrapper first = await rpc.engine_newPayloadV6( - emptyPayload, - blobVersionedHashes: [], - parentBeaconBlockRoot: Keccak.Zero, - executionRequests: payloadResult.Data!.ExecutionRequests, - inclusionListTransactions: censoringListLast ? [] : censoringList); + ResultWrapper first = await NewPayloadV6(rpc, emptyPayload, [], censoringListLast ? [] : censoringList); + bool? firstVerdict = first.Data.InclusionListSatisfied; + ResultWrapper second = await NewPayloadV6(rpc, emptyPayload, [], censoringListLast ? censoringList : []); + using (Assert.EnterMultipleScope()) { Assert.That(first.Data.Status, Is.EqualTo(PayloadStatus.Valid)); - Assert.That(first.Data.InclusionListSatisfied, Is.EqualTo(censoringListLast)); - } - - // Same block hash, different IL: the cached VALID must not short-circuit the IL check. - ResultWrapper second = await rpc.engine_newPayloadV6( - emptyPayload, - blobVersionedHashes: [], - parentBeaconBlockRoot: Keccak.Zero, - executionRequests: payloadResult.Data!.ExecutionRequests, - inclusionListTransactions: censoringListLast ? censoringList : []); - ResultWrapper toBlock = await rpc.engine_forkchoiceUpdatedV5( - new ForkchoiceStateV1(emptyPayload.BlockHash, startingHead, startingHead), payloadAttributes: null); - using (Assert.EnterMultipleScope()) - { Assert.That(second.Data.Status, Is.EqualTo(PayloadStatus.Valid)); + Assert.That(firstVerdict, Is.EqualTo(censoringListLast)); Assert.That(second.Data.InclusionListSatisfied, Is.EqualTo(!censoringListLast)); - Assert.That(toBlock.Data.PayloadStatus.Status, Is.EqualTo(PayloadStatus.Valid)); - Assert.That(toBlock.Data.PayloadStatus.InclusionListSatisfied, Is.EqualTo(!censoringListLast)); } } + /// A check whose block state is unavailable answers SYNCING with no verdict, so it is never taken as + /// satisfied; resubmitting the original inputs once the state is back runs it again. [Test] - public async Task NewPayloadV6_accepts_aggregate_inclusion_list_exceeding_single_member_cap() + public async Task Undecidable_inclusion_check_answers_syncing_until_the_inputs_are_resubmitted() { - using MergeTestBlockchain chain = await CreateBlockchain(Bogota.Instance, new MergeConfig { TerminalTotalDifficulty = "0" }); + HeadStateInterceptor headState = new(); + using MergeTestBlockchain chain = await CreateBlockchainWithHeadState(headState); IEngineRpcModule rpc = chain.EngineRpcModule; - Hash256 startingHead = chain.BlockTree.HeadHash; - - ResultWrapper fcu = await rpc.engine_forkchoiceUpdatedV5( - new ForkchoiceStateV1(startingHead, Keccak.Zero, startingHead), - BuildBogotaPayloadAttributes(inclusionList: [])); - ResultWrapper payloadResult = await rpc.engine_getPayloadV6(Bytes.FromHexString(fcu.Data.PayloadId!)); + ExecutionPayloadV4 payload = await BuildEmptyPayload(rpc, chain.BlockTree.HeadHash); + byte[][] censoringList = [Rlp.Encode(BuildInclusionListTransfer())]; - // The flattened aggregate can exceed the per-member cap; newPayloadV6 must not reject it. - byte[] member = new byte[Eip7805Constants.MaxBytesPerInclusionList * 3 / 4]; - ResultWrapper result = await rpc.engine_newPayloadV6( - payloadResult.Data!.ExecutionPayload, - blobVersionedHashes: [], - parentBeaconBlockRoot: Keccak.Zero, - executionRequests: payloadResult.Data!.ExecutionRequests, - inclusionListTransactions: [member, member]); + headState.PrunedBlock = payload.BlockHash; + ResultWrapper unavailable = await NewPayloadV6(rpc, payload, [], censoringList); + headState.PrunedBlock = null; + ResultWrapper resubmitted = await NewPayloadV6(rpc, payload, [], censoringList); - Assert.That(result.Result.ResultType, Is.EqualTo(ResultType.Success)); + using (Assert.EnterMultipleScope()) + { + Assert.That(unavailable.Data.Status, Is.EqualTo(PayloadStatus.Syncing), "VALID must carry a completed verdict"); + Assert.That(unavailable.Data.InclusionListSatisfied, Is.Null); + Assert.That(resubmitted.Data.Status, Is.EqualTo(PayloadStatus.Valid)); + Assert.That(resubmitted.Data.InclusionListSatisfied, Is.False); + } } - [Test] - public async Task NewPayloadV6_accepts_an_aggregate_of_entry_dense_conforming_members() + /// bogota.md engine_newPayloadV6 point 2.1: one list per committee position, each within its byte cap + /// before deduplication, and no empty entry; point 2.2: at most MAX_OMISSION_CLAIMS claims. Each is paired with an + /// arm at the bound, so a method rejecting everything cannot pass. + public static IEnumerable InclusionListBounds { - using MergeTestBlockchain chain = await CreateBlockchain(Bogota.Instance, new MergeConfig { TerminalTotalDifficulty = "0" }); - IEngineRpcModule rpc = chain.EngineRpcModule; - Hash256 startingHead = chain.BlockTree.HeadHash; + get + { + static TestCaseData Case(string name, byte[][][] inclusionLists, int claims, bool invalid) => + new(inclusionLists, claims, invalid) { TestName = name }; + byte[] full = new byte[Eip7805Constants.MaxBytesPerInclusionList]; + byte[] half = new byte[Eip7805Constants.MaxBytesPerInclusionList / 2]; - ResultWrapper fcu = await rpc.engine_forkchoiceUpdatedV5( - new ForkchoiceStateV1(startingHead, Keccak.Zero, startingHead), - BuildBogotaPayloadAttributes(inclusionList: [])); - ResultWrapper payloadResult = await rpc.engine_getPayloadV6(Bytes.FromHexString(fcu.Data.PayloadId!)); + yield return Case("Every position's list at its byte cap is valid", [.. Enumerable.Repeat([full], Eip7805Constants.InclusionListCommitteeSize)], 0, false); + yield return Case("A list one byte over its cap is invalid", AtPositions([full], [[.. full, 0]]), 0, true); + yield return Case("A duplicate counts toward the cap before deduplication", AtPositions([half, half, [0]]), 0, true); + yield return Case("A duplicate within the cap is valid", AtPositions([half, half]), 0, false); + yield return Case("Two-byte entries filling every position are valid", + [.. Enumerable.Repeat([.. Enumerable.Range(0, Eip7805Constants.MaxBytesPerInclusionList / 2).Select(i => new[] { (byte)(i >> 8), (byte)i })], Eip7805Constants.InclusionListCommitteeSize)], 0, false); + yield return Case("Fifteen lists are invalid", [.. Enumerable.Repeat([], Eip7805Constants.InclusionListCommitteeSize - 1)], 0, true); + yield return Case("Seventeen lists are invalid", [.. Enumerable.Repeat([], Eip7805Constants.InclusionListCommitteeSize + 1)], 0, true); + yield return Case("An empty entry is invalid", AtPositions([Array.Empty()]), 0, true); + yield return Case("Claims at MAX_OMISSION_CLAIMS are valid", AtPositions(), Eip8369Constants.MaxOmissionClaims, false); + yield return Case("Claims over MAX_OMISSION_CLAIMS are invalid", AtPositions(), Eip8369Constants.MaxOmissionClaims + 1, true); + } + } - byte[][] aggregate = new byte[Eip7805Constants.MaxAggregateInclusionListBytes / 2][]; - for (int i = 0; i < aggregate.Length; i++) aggregate[i] = [(byte)(i >> 8), (byte)i]; + [TestCaseSource(nameof(InclusionListBounds))] + public async Task NewPayloadV6_bounds_inclusion_lists_and_claims(byte[][][] inclusionLists, int claims, bool invalid) + { + using MergeTestBlockchain chain = await CreateBlockchain(Bogota.Instance, new MergeConfig { TerminalTotalDifficulty = "0" }); + ExecutionPayloadV4 payload = await BuildEmptyPayload(chain.EngineRpcModule, chain.BlockTree.HeadHash); - ResultWrapper result = await rpc.engine_newPayloadV6( - payloadResult.Data!.ExecutionPayload, [], Keccak.Zero, payloadResult.Data!.ExecutionRequests, aggregate); + ResultWrapper result = await chain.EngineRpcModule.engine_newPayloadV6( + payload, [], Keccak.Zero, [], inclusionLists, [.. Enumerable.Repeat(new OmissionClaim(Keccak.Zero, 0), claims)]); - Assert.That(result.Result.ResultType, Is.EqualTo(ResultType.Success), result.Result.Error); + Assert.That(result.ErrorCode, Is.EqualTo(invalid ? ErrorCodes.InvalidParams : ErrorCodes.None), result.Result.Error); } - [Test] - public async Task NewPayloadV6_bounds_aggregate_inclusion_list_bytes() + [TestCaseSource(nameof(InclusionListBounds))] + public async Task ForkchoiceUpdatedV5_bounds_inclusion_lists(byte[][][] inclusionLists, int claims, bool invalid) { using MergeTestBlockchain chain = await CreateBlockchain(Bogota.Instance, new MergeConfig { TerminalTotalDifficulty = "0" }); - IEngineRpcModule rpc = chain.EngineRpcModule; - Hash256 startingHead = chain.BlockTree.HeadHash; + Hash256 head = chain.BlockTree.HeadHash; + + ResultWrapper result = await chain.EngineRpcModule.engine_forkchoiceUpdatedV5( + new ForkchoiceStateV1(head, Keccak.Zero, head), BuildBogotaPayloadAttributes(inclusionLists)); + + // Payload attributes carry no claims, so only the list arms apply. + Assert.That(result.ErrorCode, Is.EqualTo(invalid && claims == 0 ? MergeErrorCodes.InvalidPayloadAttributes : ErrorCodes.None), result.Result.Error); + } + + /// bogota.md engine_newPayloadV6 point 2.2: a claim must match OmissionClaimV1 on the wire, its index a + /// canonical QUANTITY (common.md), while an index above the payload's transaction count is well formed and + /// only clamped by EIP-7805. + [TestCase("""{"transactionHash":"0x0000000000000000000000000000000000000000000000000000000000000000","evaluationIndex":"0xffffffffffffffff"}""", false, TestName = "Claim at the largest uint64 index is well formed")] + [TestCase("""{"transactionHash":"0x0000000000000000000000000000000000000000000000000000000000000000","evaluationIndex":"0x10000000000000000"}""", true, TestName = "Claim index overflowing uint64 is invalid params")] + [TestCase("""{"transactionHash":"0x0000000000000000000000000000000000000000000000000000000000000000"}""", true, TestName = "Claim without an index is invalid params")] + [TestCase("""{"evaluationIndex":"0x0"}""", true, TestName = "Claim without a hash is invalid params")] + [TestCase("""{"transactionHash":"0x00","evaluationIndex":"0x0"}""", true, TestName = "Claim with a short hash is invalid params")] + [TestCase("""{"transactionHash":"0x0000000000000000000000000000000000000000000000000000000000000000","evaluationIndex":"0x0"}""", false, TestName = "Claim at index zero is well formed")] + [TestCase("""{"transactionHash":"0x0000000000000000000000000000000000000000000000000000000000000000","evaluationIndex":"0xAbC"}""", false, TestName = "Claim index in either hex case is well formed")] + [TestCase("""{"transactionHash":"0x0000000000000000000000000000000000000000000000000000000000000000","evaluationIndex":"0x01"}""", true, TestName = "Claim index with a leading zero is invalid params")] + [TestCase("""{"transactionHash":"0x0000000000000000000000000000000000000000000000000000000000000000","evaluationIndex":"0x00"}""", true, TestName = "Claim index zero with a leading zero is invalid params")] + [TestCase("""{"transactionHash":"0x0000000000000000000000000000000000000000000000000000000000000000","evaluationIndex":"0x"}""", true, TestName = "Claim index without digits is invalid params")] + [TestCase("""{"transactionHash":"0x0000000000000000000000000000000000000000000000000000000000000000","evaluationIndex":"1"}""", true, TestName = "Claim index without 0x is invalid params")] + [TestCase("""{"transactionHash":"0x0000000000000000000000000000000000000000000000000000000000000000","evaluationIndex":1}""", true, TestName = "Claim index as a JSON number is invalid params")] + public async Task NewPayloadV6_rejects_a_malformed_claim(string claim, bool invalid) + { + using MergeTestBlockchain chain = await CreateBlockchain(Bogota.Instance, new MergeConfig { TerminalTotalDifficulty = "0" }); + ExecutionPayloadV4 payload = await BuildEmptyPayload(chain.EngineRpcModule, chain.BlockTree.HeadHash); - ResultWrapper fcu = await rpc.engine_forkchoiceUpdatedV5( - new ForkchoiceStateV1(startingHead, Keccak.Zero, startingHead), - BuildBogotaPayloadAttributes(inclusionList: [])); - ResultWrapper payloadResult = await rpc.engine_getPayloadV6(Bytes.FromHexString(fcu.Data.PayloadId!)); - ExecutionPayloadV4 emptyPayload = payloadResult.Data!.ExecutionPayload; - - // At the aggregate limit (IL_COMMITTEE_SIZE * MAX_BYTES_PER_INCLUSION_LIST): accepted. - ResultWrapper atLimit = await rpc.engine_newPayloadV6( - emptyPayload, [], Keccak.Zero, payloadResult.Data!.ExecutionRequests, - [new byte[Eip7805Constants.MaxAggregateInclusionListBytes]]); - Assert.That(atLimit.Result.ResultType, Is.EqualTo(ResultType.Success), atLimit.Result.Error); - - // One byte over the limit: rejected before decode. - ResultWrapper overLimit = await rpc.engine_newPayloadV6( - emptyPayload, [], Keccak.Zero, payloadResult.Data!.ExecutionRequests, - [new byte[Eip7805Constants.MaxAggregateInclusionListBytes + 1]]); - using (Assert.EnterMultipleScope()) - { - Assert.That(overLimit.Result.ResultType, Is.EqualTo(ResultType.Failure)); - Assert.That(overLimit.Result.Error, Does.Contain("exceeds the maximum aggregate size")); - } + string response = await RpcTest.TestSerializedRequest(chain.EngineRpcModule, nameof(IEngineRpcModule.engine_newPayloadV6), + payload, Array.Empty(), Keccak.Zero, Array.Empty(), AtPositions(), JsonDocument.Parse($"[{claim}]").RootElement); - // Entry count is bounded independently of bytes — empty entries cost no bytes but still allocate. - byte[][] tooManyEmpty = new byte[Eip7805Constants.MaxAggregateInclusionListTransactions + 1][]; - for (int i = 0; i < tooManyEmpty.Length; i++) tooManyEmpty[i] = []; - ResultWrapper tooManyEntries = await rpc.engine_newPayloadV6( - emptyPayload, [], Keccak.Zero, payloadResult.Data!.ExecutionRequests, tooManyEmpty); - using (Assert.EnterMultipleScope()) - { - Assert.That(tooManyEntries.Result.ResultType, Is.EqualTo(ResultType.Failure)); - Assert.That(tooManyEntries.Result.Error, Does.Contain("maximum number of transactions")); - } + Assert.That(response, invalid ? Does.Contain($"\"code\":{ErrorCodes.InvalidParams}") : Does.Contain("\"status\":\"VALID\"")); } [Test] @@ -659,14 +573,9 @@ public async Task NewPayloadV5_is_unsupported_at_Bogota() { using MergeTestBlockchain chain = await CreateBlockchain(Bogota.Instance, new MergeConfig { TerminalTotalDifficulty = "0" }); IEngineRpcModule rpc = chain.EngineRpcModule; - Hash256 startingHead = chain.BlockTree.HeadHash; - - ResultWrapper fcu = await rpc.engine_forkchoiceUpdatedV5( - new ForkchoiceStateV1(startingHead, Keccak.Zero, startingHead), - BuildBogotaPayloadAttributes(inclusionList: [])); - ResultWrapper payloadResult = await rpc.engine_getPayloadV6(Bytes.FromHexString(fcu.Data.PayloadId!)); + ResultWrapper payloadResult = await BuildBogotaPayload(rpc, chain.BlockTree.HeadHash, BuildBogotaPayloadAttributes(inclusionList: [])); - // execution-apis#609: at/after Bogota, engine_newPayloadV5 must be rejected with -38005. + // At and after Bogota, engine_newPayloadV5 must be rejected with -38005. ResultWrapper result = await rpc.engine_newPayloadV5( payloadResult.Data!.ExecutionPayload, [], Keccak.Zero, payloadResult.Data!.ExecutionRequests); using (Assert.EnterMultipleScope()) @@ -683,19 +592,14 @@ public async Task NewPayloadWithWitnessV6_supersedes_V5_at_Bogota() { using MergeTestBlockchain chain = await CreateBlockchain(Bogota.Instance, new MergeConfig { TerminalTotalDifficulty = "0" }); IEngineRpcModule rpc = chain.EngineRpcModule; - Hash256 startingHead = chain.BlockTree.HeadHash; - - ResultWrapper fcu = await rpc.engine_forkchoiceUpdatedV5( - new ForkchoiceStateV1(startingHead, Keccak.Zero, startingHead), - BuildBogotaPayloadAttributes(inclusionList: [])); - ResultWrapper payloadResult = await rpc.engine_getPayloadV6(Bytes.FromHexString(fcu.Data.PayloadId!)); + ResultWrapper payloadResult = await BuildBogotaPayload(rpc, chain.BlockTree.HeadHash, BuildBogotaPayloadAttributes(inclusionList: [])); ExecutionPayloadV4 executionPayload = payloadResult.Data!.ExecutionPayload; byte[][]? executionRequests = payloadResult.Data!.ExecutionRequests; using ResultWrapper v5 = await rpc.engine_newPayloadWithWitnessV5( executionPayload, [], Keccak.Zero, executionRequests); using ResultWrapper v6 = await rpc.engine_newPayloadWithWitnessV6( - executionPayload, [], Keccak.Zero, executionRequests, []); + executionPayload, [], Keccak.Zero, executionRequests, AtPositions(), []); using (Assert.EnterMultipleScope()) { @@ -719,9 +623,9 @@ public async Task NewPayloadV6_is_unsupported_before_Bogota() ResultWrapper fcu = await rpc.engine_forkchoiceUpdatedV4(fcuState, attrs); ResultWrapper payloadResult = await rpc.engine_getPayloadV6(Bytes.FromHexString(fcu.Data.PayloadId!)); - // execution-apis#609: before Bogota, engine_newPayloadV6 must be rejected with -38005. + // Before Bogota, engine_newPayloadV6 must be rejected with -38005, ahead of any parameter check. ResultWrapper result = await rpc.engine_newPayloadV6( - payloadResult.Data!.ExecutionPayload, [], Keccak.Zero, payloadResult.Data!.ExecutionRequests, []); + payloadResult.Data!.ExecutionPayload, [], Keccak.Zero, payloadResult.Data!.ExecutionRequests, [], []); using (Assert.EnterMultipleScope()) { Assert.That(result.Result.ResultType, Is.EqualTo(ResultType.Failure)); @@ -729,19 +633,19 @@ public async Task NewPayloadV6_is_unsupported_before_Bogota() } } - // bogota.md: PayloadAttributesV5 appends inclusionListTransactions unconditionally, so an empty list is - // how a proposer says it has none — omitting the field leaves the attributes V4-shaped. + // bogota.md: PayloadAttributesV5 appends inclusionLists unconditionally, so sixteen empty lists are how a + // proposer says it has none — omitting the field leaves the attributes V4-shaped. [Test] - public async Task ForkchoiceUpdatedV5_rejects_attributes_without_an_inclusion_list() + public async Task ForkchoiceUpdatedV5_rejects_attributes_without_inclusion_lists() { using MergeTestBlockchain chain = await CreateBlockchain(Bogota.Instance, new MergeConfig { TerminalTotalDifficulty = "0" }); IEngineRpcModule rpc = chain.EngineRpcModule; Hash256 startingHead = chain.BlockTree.HeadHash; - ResultWrapper missing = await rpc.engine_forkchoiceUpdatedV5( + ResultWrapper missing = await rpc.engine_forkchoiceUpdatedV5( new ForkchoiceStateV1(startingHead, Keccak.Zero, startingHead), BuildBogotaPayloadAttributes(inclusionList: null!)); - ResultWrapper empty = await rpc.engine_forkchoiceUpdatedV5( + ResultWrapper empty = await rpc.engine_forkchoiceUpdatedV5( new ForkchoiceStateV1(startingHead, Keccak.Zero, startingHead), BuildBogotaPayloadAttributes(inclusionList: [])); @@ -770,7 +674,7 @@ public async Task Should_build_block_with_inclusion_list_transactions() .TestObject; byte[] txBytes = Rlp.Encode(tx); - ResultWrapper fcu = await rpc.engine_forkchoiceUpdatedV5( + ResultWrapper fcu = await rpc.engine_forkchoiceUpdatedV5( new ForkchoiceStateV1(startingHead, Keccak.Zero, startingHead), BuildBogotaPayloadAttributes(inclusionList: [txBytes])); @@ -781,22 +685,18 @@ public async Task Should_build_block_with_inclusion_list_transactions() } // Even the producer's EmptyBlock fast path carries the IL, so the first getPayload is populated. - ResultWrapper payloadResult = await rpc.engine_getPayloadV6(Bytes.FromHexString(fcu.Data.PayloadId!)); + ResultWrapper payloadResult = await rpc.engine_getPayloadV7(Bytes.FromHexString(fcu.Data.PayloadId!)); Assert.That(payloadResult.Data, Is.Not.Null); ExecutionPayloadV4 payload = payloadResult.Data!.ExecutionPayload; using (Assert.EnterMultipleScope()) { Assert.That(payload.Transactions, Has.Length.EqualTo(1)); Assert.That(payload.Transactions[0], Is.EqualTo(txBytes)); + Assert.That(payloadResult.Data.OmissionClaims, Is.Empty); } - // The block-as-built must round-trip through newPayloadV6 with the same IL. - ResultWrapper verify = await rpc.engine_newPayloadV6( - payload, - blobVersionedHashes: [], - parentBeaconBlockRoot: Keccak.Zero, - executionRequests: [], - inclusionListTransactions: [txBytes]); + // The block-as-built must round-trip through newPayloadV6 with the same lists. + ResultWrapper verify = await NewPayloadV6(rpc, payload, [], [txBytes]); using (Assert.EnterMultipleScope()) { Assert.That(verify.Result.ResultType, Is.EqualTo(ResultType.Success), verify.Result.Error); @@ -806,7 +706,7 @@ public async Task Should_build_block_with_inclusion_list_transactions() } [Test] - public async Task NewPayloadV6_resubmitting_canonical_block_with_same_inclusion_list_requires_state([Values] bool statePruned) + public async Task NewPayloadV6_resubmitting_canonical_block_requires_state([Values] bool statePruned) { ConcurrentDictionary pruned = new(); using MergeTestBlockchain chain = await CreateBlockchainWithPrunableState(pruned, releaseSpec: Bogota.Instance); @@ -818,32 +718,27 @@ public async Task NewPayloadV6_resubmitting_canonical_block_with_same_inclusion_ .WithTo(TestItem.AddressA).SignedAndResolved(TestItem.PrivateKeyB).TestObject; byte[][] inclusionList = [Rlp.Encode(tx)]; - ResultWrapper fcu = await rpc.engine_forkchoiceUpdatedV5( - new ForkchoiceStateV1(startingHead, Keccak.Zero, startingHead), - BuildBogotaPayloadAttributes(inclusionList: inclusionList)); - ResultWrapper payloadResult = await rpc.engine_getPayloadV6(Bytes.FromHexString(fcu.Data.PayloadId!)); + ResultWrapper payloadResult = await BuildBogotaPayload(rpc, startingHead, BuildBogotaPayloadAttributes(inclusionList: inclusionList)); ExecutionPayloadV4 payload = payloadResult.Data!.ExecutionPayload; - ResultWrapper first = await rpc.engine_newPayloadV6( - payload, [], Keccak.Zero, payloadResult.Data!.ExecutionRequests, inclusionList); + ResultWrapper first = await NewPayloadV6(rpc, payload, payloadResult.Data!.ExecutionRequests, inclusionList); using (Assert.EnterMultipleScope()) { Assert.That(first.Data.Status, Is.EqualTo(PayloadStatus.Valid)); Assert.That(first.Data.InclusionListSatisfied, Is.True); } - // Promote to canonical head, then re-submit the same (block, IL). + // Promote to canonical head, then re-submit the same payload and lists. await rpc.engine_forkchoiceUpdatedV5( new ForkchoiceStateV1(payload.BlockHash, payload.BlockHash, payload.BlockHash), payloadAttributes: null); if (statePruned) pruned[payload.BlockHash] = 0; - // A cached result can only be reused while the state that established compliance is available. - ResultWrapper resend = await rpc.engine_newPayloadV6( - payload, [], Keccak.Zero, payloadResult.Data!.ExecutionRequests, inclusionList); + // Execution validity is only reused while the state that established it is available. + ResultWrapper resend = await NewPayloadV6(rpc, payload, payloadResult.Data!.ExecutionRequests, inclusionList); using (Assert.EnterMultipleScope()) { Assert.That(resend.Data.Status, Is.EqualTo(statePruned ? PayloadStatus.Syncing : PayloadStatus.Valid)); - if (!statePruned) Assert.That(resend.Data.InclusionListSatisfied, Is.True); + Assert.That(resend.Data.InclusionListSatisfied, statePruned ? Is.Null : Is.True, "a verdict is present exactly when execution is VALID"); } } @@ -852,7 +747,6 @@ public async Task Should_build_block_including_reversed_nonce_inclusion_list() { using MergeTestBlockchain chain = await CreateBlockchain(Bogota.Instance, new MergeConfig { TerminalTotalDifficulty = "0" }); IEngineRpcModule rpc = chain.EngineRpcModule; - Hash256 startingHead = chain.BlockTree.HeadHash; Transaction tx0 = Build.A.Transaction .WithNonce(0).WithMaxFeePerGas(10.GWei).WithMaxPriorityFeePerGas(2.GWei) @@ -861,13 +755,10 @@ public async Task Should_build_block_including_reversed_nonce_inclusion_list() .WithNonce(1).WithMaxFeePerGas(10.GWei).WithMaxPriorityFeePerGas(2.GWei) .WithTo(TestItem.AddressA).SignedAndResolved(TestItem.PrivateKeyB).TestObject; - // Reversed order (nonce 1 before nonce 0): a one-pass producer would skip nonce 1 forever. - byte[][] inclusionList = [Rlp.Encode(tx1), Rlp.Encode(tx0)]; - - ResultWrapper fcu = await rpc.engine_forkchoiceUpdatedV5( - new ForkchoiceStateV1(startingHead, Keccak.Zero, startingHead), - BuildBogotaPayloadAttributes(inclusionList: inclusionList)); - ResultWrapper payloadResult = await rpc.engine_getPayloadV6(Bytes.FromHexString(fcu.Data.PayloadId!)); + // Reversed order (nonce 1 before nonce 0), split across two positions: a one-pass producer would skip + // nonce 1 forever. + ResultWrapper payloadResult = await BuildBogotaPayload(rpc, chain.BlockTree.HeadHash, + BuildBogotaPayloadAttributes(AtPositions([Rlp.Encode(tx1)], [Rlp.Encode(tx0)]))); ExecutionPayloadV4 payload = payloadResult.Data!.ExecutionPayload; // Both IL txs must be produced, in ascending-nonce order. @@ -884,23 +775,19 @@ public async Task Should_build_block_including_inclusion_list_transaction_funded { using MergeTestBlockchain chain = await CreateBlockchain(Bogota.Instance, new MergeConfig { TerminalTotalDifficulty = "0" }); IEngineRpcModule rpc = chain.EngineRpcModule; - Hash256 startingHead = chain.BlockTree.HeadHash; (Transaction spend, Transaction fund) = BuildSpendFundedByLaterTransaction(); byte[] spendBytes = Rlp.Encode(spend); byte[] fundBytes = Rlp.Encode(fund); byte[][] inclusionList = [spendBytes, fundBytes]; - ResultWrapper fcu = await rpc.engine_forkchoiceUpdatedV5( - new ForkchoiceStateV1(startingHead, Keccak.Zero, startingHead), + ResultWrapper payloadResult = await BuildBogotaPayload(rpc, chain.BlockTree.HeadHash, BuildBogotaPayloadAttributes(inclusionList: inclusionList)); - ResultWrapper payloadResult = await rpc.engine_getPayloadV6(Bytes.FromHexString(fcu.Data.PayloadId!)); ExecutionPayloadV4 payload = payloadResult.Data!.ExecutionPayload; Assert.That(payload.Transactions, Is.EqualTo(new[] { fundBytes, spendBytes })); - ResultWrapper verify = await rpc.engine_newPayloadV6( - payload, [], Keccak.Zero, payloadResult.Data!.ExecutionRequests, inclusionList); + ResultWrapper verify = await NewPayloadV6(rpc, payload, payloadResult.Data!.ExecutionRequests, inclusionList); using (Assert.EnterMultipleScope()) { Assert.That(verify.Data.Status, Is.EqualTo(PayloadStatus.Valid)); @@ -947,7 +834,7 @@ public async Task Should_not_offer_inclusion_list_transaction_again_while_its_se .WithTo(TestItem.AddressA).SignedAndResolved(Build.A.PrivateKey.TestObject).TestObject; (Transaction spend, Transaction fund) = BuildSpendFundedByLaterTransaction(); PayloadAttributes payloadAttributes = BuildBogotaPayloadAttributes(inclusionList: [Rlp.Encode(unfunded), Rlp.Encode(spend), Rlp.Encode(fund)]); - chain.InclusionListTxSource!.Set(payloadAttributes.InclusionListTransactions!, Bogota.Instance); + chain.InclusionListTxSource!.Set(payloadAttributes.InclusionLists!, Bogota.Instance); Block? block = await chain.BlockProducer!.BuildBlock(chain.BlockTree.Head!.Header, payloadAttributes: payloadAttributes); @@ -974,7 +861,7 @@ public async Task Should_offer_inclusion_list_transaction_again_after_its_sender .WithNonce(0).WithMaxFeePerGas(10.GWei).WithMaxPriorityFeePerGas(2.GWei).WithValue(2.Ether).WithGasLimit(1_000_000) .WithTo(TestItem.AddressE).SignedAndResolved(TestItem.PrivateKeyB).TestObject; PayloadAttributes payloadAttributes = BuildBogotaPayloadAttributes(inclusionList: [Rlp.Encode(spend), Rlp.Encode(relay), Rlp.Encode(fund)]); - chain.InclusionListTxSource!.Set(payloadAttributes.InclusionListTransactions!, Bogota.Instance); + chain.InclusionListTxSource!.Set(payloadAttributes.InclusionLists!, Bogota.Instance); Block? block = await chain.BlockProducer!.BuildBlock(chain.BlockTree.Head!.Header, payloadAttributes: payloadAttributes); @@ -1047,7 +934,7 @@ public async Task Should_not_offer_inclusion_list_transactions_again_when_a_buil .WithNonce(0).WithMaxFeePerGas(10.GWei).WithMaxPriorityFeePerGas(2.GWei) .WithTo(TestItem.AddressA).SignedAndResolved(TestItem.PrivateKeyC).TestObject; PayloadAttributes payloadAttributes = BuildBogotaPayloadAttributes(inclusionList: [Rlp.Encode(first), Rlp.Encode(second)]); - chain.InclusionListTxSource!.Set(payloadAttributes.InclusionListTransactions!, Bogota.Instance); + chain.InclusionListTxSource!.Set(payloadAttributes.InclusionLists!, Bogota.Instance); return (first, second, payloadAttributes); } @@ -1095,7 +982,6 @@ public BlockProcessor.AddingTxEventArgs CanAddTransaction(Block block, Transacti } } - [Test] public async Task Can_get_inclusion_list() { using MergeTestBlockchain chain = await CreateBlockchain(Bogota.Instance); @@ -1239,10 +1125,10 @@ public async Task ForkchoiceUpdatedV5_returns_the_payload_id_before_the_inclusio try { - ResultWrapper forkchoiceUpdated = await Task.Run(() => rpc.engine_forkchoiceUpdatedV5( + ResultWrapper forkchoiceUpdated = await Task.Run(() => rpc.engine_forkchoiceUpdatedV5( new ForkchoiceStateV1(startingHead, Keccak.Zero, startingHead), payloadAttributes)).WaitAsync(TimeSpan.FromSeconds(5)); - Task> getPayload = rpc.engine_getPayloadV6(Bytes.FromHexString(forkchoiceUpdated.Data.PayloadId!)); + Task> getPayload = rpc.engine_getPayloadV7(Bytes.FromHexString(forkchoiceUpdated.Data.PayloadId!)); bool waitedForBuild = !getPayload.IsCompleted; inclusionListRelease.Set(); ExecutionPayloadV4 payload = (await getPayload).Data!.ExecutionPayload; @@ -1269,15 +1155,19 @@ public IEnumerable GetTransactions(BlockHeader parent, BlockHeader public bool SupportsBlobs => inner.SupportsBlobs; - public void Set(byte[][] inclusionListTransactions, IReleaseSpec spec) => inner.Set(inclusionListTransactions, spec); + public void Set(byte[][][] inclusionLists, IReleaseSpec spec) => inner.Set(inclusionLists, spec); + + public IReadOnlySet? GetProfile2Candidates(PayloadAttributes? payloadAttributes, ulong maxVerifyGasPerTx) => + inner.GetProfile2Candidates(payloadAttributes, maxVerifyGasPerTx); } - // bogota.md newPayloadV6 (2.1): a VALID response must carry a compliance answer. A canonical block this node ran - // is answered from its own state; otherwise it is answered SYNCING rather than re-executed. + // A canonical block this node ran is VALID, and its inclusion check is judged against its own state; once that + // state is pruned below finality the check cannot be decided, so it is answered SYNCING. A block this node never + // ran is answered SYNCING rather than re-executed, and no check is run. [TestCase(true, false, PayloadStatus.Valid)] [TestCase(true, true, PayloadStatus.Syncing)] [TestCase(false, false, PayloadStatus.Syncing)] - public async Task NewPayloadV6_answers_an_inclusion_list_behind_head_from_its_state_only_when_run_here( + public async Task NewPayloadV6_checks_inclusion_behind_head_against_its_own_state( bool runHere, bool statePruned, string expected) { ConcurrentDictionary pruned = new(); @@ -1291,21 +1181,15 @@ public async Task NewPayloadV6_answers_an_inclusion_list_behind_head_from_its_st if (!runHere) chain.BlockTree.GetInfo(first.BlockNumber, first.BlockHash).Info!.WasProcessed = false; if (statePruned) pruned[first.BlockHash] = 0; - // A different IL misses the (block, IL) cache, and the first block is now behind head. - Transaction censoredTx = Build.A.Transaction - .WithNonce(0).WithMaxFeePerGas(10.GWei).WithMaxPriorityFeePerGas(2.GWei) - .WithTo(TestItem.AddressA).SignedAndResolved(TestItem.PrivateKeyB).TestObject; - int processed = 0; chain.BranchProcessor.BlockProcessing += (_, _) => Interlocked.Increment(ref processed); - ResultWrapper resend = await rpc.engine_newPayloadV6( - first, [], Keccak.Zero, [], [Rlp.Encode(censoredTx)]); + ResultWrapper resend = await NewPayloadV6(rpc, first, [], [Rlp.Encode(BuildInclusionListTransfer())]); using (Assert.EnterMultipleScope()) { Assert.That(resend.Data.Status, Is.EqualTo(expected), - runHere && !statePruned ? "a block this node ran is answered from its state" : "a block without its own state is not answered from a state root"); - if (expected == PayloadStatus.Valid) Assert.That(resend.Data.InclusionListSatisfied, Is.False); + runHere ? "a block this node ran is answered from the tree" : "a block this node never ran is not answered from a state root"); + Assert.That(resend.Data.InclusionListSatisfied, expected == PayloadStatus.Valid ? Is.False : Is.Null); Assert.That(processed, Is.Zero, "a block on the node's own chain is not re-executed"); Assert.That(chain.BlockTree.BestKnownNumber, Is.EqualTo(bestKnown)); foreach (ExecutionPayloadV4 block in new[] { first, second }) @@ -1316,11 +1200,11 @@ public async Task NewPayloadV6_answers_an_inclusion_list_behind_head_from_its_st } /// - /// The inclusion-list counterpart of newPayloadV1_answers_valid_for_a_head_resent_while_its_re_execution_commits: - /// the resent head waits for its commit and has the new list judged against the restored state. + /// The inclusion counterpart of newPayloadV1_answers_valid_for_a_head_resent_while_its_re_execution_commits: + /// the resent head waits for its commit, and its inclusion check is judged against the restored state. /// [Test] - public async Task NewPayloadV6_judges_an_inclusion_list_for_a_head_resent_while_its_re_execution_commits() + public async Task NewPayloadV6_checks_inclusion_for_a_head_resent_while_its_re_execution_commits() { ConcurrentDictionary pruned = new(); CommitWaitProbe probe = new(); @@ -1331,13 +1215,11 @@ public async Task NewPayloadV6_judges_an_inclusion_list_for_a_head_resent_while_ Hash256 genesisHash = chain.BlockTree.HeadHash!; // Built and made head without finalizing it, so the head can move back below it. - ResultWrapper fcu = await rpc.engine_forkchoiceUpdatedV5( - new ForkchoiceStateV1(genesisHash, Keccak.Zero, Keccak.Zero), - BuildBogotaPayloadAttributes(inclusionList: [], timestamp: Timestamper.UnixTime.Seconds + 2, slotNumber: 2)); - ResultWrapper built = await rpc.engine_getPayloadV6(Bytes.FromHexString(fcu.Data.PayloadId!)); + ResultWrapper built = await BuildBogotaPayload(rpc, genesisHash, + BuildBogotaPayloadAttributes(inclusionList: [], timestamp: Timestamper.UnixTime.Seconds + 2, slotNumber: 2), finalizedHash: Keccak.Zero); ExecutionPayloadV4 block = built.Data!.ExecutionPayload; byte[][] requests = built.Data!.ExecutionRequests!; - Assert.That((await rpc.engine_newPayloadV6(block, [], Keccak.Zero, requests, [])).Data.Status, Is.EqualTo(PayloadStatus.Valid)); + Assert.That((await NewPayloadV6(rpc, block, requests, [])).Data.Status, Is.EqualTo(PayloadStatus.Valid)); await rpc.engine_forkchoiceUpdatedV5(new ForkchoiceStateV1(block.BlockHash, Keccak.Zero, Keccak.Zero), payloadAttributes: null); // The Hive shape: the head moves back, the block's state is pruned, and the block is sent again and re-executed. @@ -1346,15 +1228,12 @@ public async Task NewPayloadV6_judges_an_inclusion_list_for_a_head_resent_while_ TaskCompletionSource commit = HoldCommit(chain, block.BlockHash); - Assert.That((await rpc.engine_newPayloadV6(block, [], Keccak.Zero, requests, [])).Data.Status, Is.EqualTo(PayloadStatus.Valid)); + Assert.That((await NewPayloadV6(rpc, block, requests, [])).Data.Status, Is.EqualTo(PayloadStatus.Valid)); MoveHeadBeforeCommit(chain, block.BlockHash); - // A different list misses the (block, IL) cache; release the commit once the re-send waits on it or answers. - Transaction censoredTx = Build.A.Transaction - .WithNonce(0).WithMaxFeePerGas(10.GWei).WithMaxPriorityFeePerGas(2.GWei) - .WithTo(TestItem.AddressA).SignedAndResolved(TestItem.PrivateKeyB).TestObject; + // Release the commit once the re-send waits on it or answers. probe.Watch(block.BlockHash); - Task> resent = rpc.engine_newPayloadV6(block, [], Keccak.Zero, requests, [Rlp.Encode(censoredTx)]); + Task> resent = NewPayloadV6(rpc, block, requests, [Rlp.Encode(BuildInclusionListTransfer())]); await Task.WhenAny(probe.WaitEntered.Task, resent, Task.Delay(TimeSpan.FromSeconds(20))); bool waitedForCommit = probe.WaitEntered.Task.IsCompleted; commit.SetResult(); @@ -1364,536 +1243,146 @@ public async Task NewPayloadV6_judges_an_inclusion_list_for_a_head_resent_while_ { Assert.That(waitedForCommit, Is.True, "the re-send must wait for the head's committing re-execution"); Assert.That(result.Data.Status, Is.EqualTo(PayloadStatus.Valid), - "the head's own re-execution is committing, so its list can be judged against the state it restores"); + "the head's own re-execution is committing, so its execution validity is known"); Assert.That(result.Data.InclusionListSatisfied, Is.False); } } - // bogota.md engine_forkchoiceUpdatedV5 (2.2): a VALID head is answered from the list retained when newPayloadV6 - // could not answer. stateReadThrows: a missing trie node while evaluating must not fail the update. - [TestCase(PayloadStatus.Syncing, true, false, TestName = "ForkchoiceUpdatedV5_answers_a_satisfied_head_left_syncing_by_newPayloadV6")] - [TestCase(PayloadStatus.Syncing, false, false, TestName = "ForkchoiceUpdatedV5_answers_an_unsatisfied_head_left_syncing_by_newPayloadV6")] - [TestCase(PayloadStatus.Syncing, false, true, TestName = "ForkchoiceUpdatedV5_reports_null_when_the_retained_list_evaluation_throws")] - [TestCase(PayloadStatus.Accepted, true, false, TestName = "ForkchoiceUpdatedV5_answers_a_satisfied_head_left_accepted_by_newPayloadV6")] - [TestCase(PayloadStatus.Accepted, false, false, TestName = "ForkchoiceUpdatedV5_answers_an_unsatisfied_head_left_accepted_by_newPayloadV6")] - [NonParallelizable] - public async Task ForkchoiceUpdatedV5_answers_compliance_for_a_head_left_unanswered( - string newPayloadStatus, bool satisfied, bool stateReadThrows) + // The check must judge the list on the dimensions execution recorded, not on the max(execution, state) the + // header reduces them to. The two differ only above the EIP-7825 execution cap: past it a transaction reserves + // the cap on the execution dimension but its whole gas on the state one, so an entry that fits both dimensions + // reads as unappendable against the max, and real censorship goes unreported. After cache loss, bounds still + // prove some verdicts; an ambiguous check is forgotten rather than guessed, as recovering its exact answer needs + // safe re-execution. + [TestCase(50, false, InclusionListEntry.Boundary, false, TestName = "NewPayloadV6_checks_a_resent_block_on_the_recorded_gas_dimensions")] + [TestCase(1, false, InclusionListEntry.Boundary, false, TestName = "NewPayloadV6_checks_a_resent_block_on_the_recorded_gas_dimensions_after_the_payload_cache_evicts_it")] + [TestCase(1, true, InclusionListEntry.Boundary, false, TestName = "NewPayloadV6_forgets_a_check_once_both_caches_lose_the_gas_dimensions")] + [TestCase(1, true, InclusionListEntry.Included, false, TestName = "NewPayloadV6_checks_an_included_list_after_both_dimension_caches_are_lost")] + [TestCase(1, true, InclusionListEntry.Boundary, true, TestName = "NewPayloadV6_forgets_a_check_of_an_omitted_list_for_the_head_after_both_dimension_caches_are_lost")] + [TestCase(1, true, InclusionListEntry.Included, true, TestName = "NewPayloadV6_checks_an_included_list_for_the_head_after_both_dimension_caches_are_lost")] + [TestCase(1, true, InclusionListEntry.Small, false, TestName = "NewPayloadV6_reports_censorship_proven_without_gas_dimensions")] + [TestCase(1, true, InclusionListEntry.Small, true, TestName = "NewPayloadV6_reports_censorship_for_the_head_without_gas_dimensions")] + [TestCase(1, true, InclusionListEntry.WrongNonce, false, TestName = "NewPayloadV6_checks_an_unappendable_list_without_gas_dimensions")] + [TestCase(1, true, InclusionListEntry.WrongNonce, true, TestName = "NewPayloadV6_checks_an_unappendable_list_for_the_head_without_gas_dimensions")] + public async Task NewPayloadV6_checks_a_resent_block_on_the_recorded_gas_dimensions( + int newPayloadCacheSize, bool dimensionsLost, InclusionListEntry entry, bool resendHead) { - HeadStateInterceptor headState = new(); - StatusOverridingNewPayloadHandler newPayloadHandler = new(); - using MergeTestBlockchain chain = await CreateBlockchainWithHeadState(headState, - new MergeConfig { TerminalTotalDifficulty = "0", NewPayloadBlockProcessingTimeout = 100 }, - builder => builder.AddDecorator>((_, inner) => - { - newPayloadHandler.Inner = inner; - return newPayloadHandler; - })); + // Genesis is raised to the production target so the block's remaining gas exceeds the execution cap; + // the 4M default leaves no room for a transaction big enough to tell the two rules apart. + const ulong gasLimit = 30_000_000UL; + AccountReadCountingStateReader accountReader = null!; + using MergeTestBlockchain chain = await CreateBlockchain(Bogota.Instance, + new MergeConfig { TerminalTotalDifficulty = "0", NewPayloadCacheSize = newPayloadCacheSize }, + configurer: builder => builder + .WithGenesisPostProcessor((genesis, _) => genesis.Header.GasLimit = gasLimit) + // Every handler resolves its own decorated reader, so all share the first one's count. + .AddDecorator((_, reader) => + accountReader ??= new AccountReadCountingStateReader(reader, TestItem.AddressC))); IEngineRpcModule rpc = chain.EngineRpcModule; - Block parent = chain.BlockTree.Head!; - byte[][] inclusionList = [Rlp.Encode(BuildInclusionListTransfer())]; - - // Build with the list only in the satisfied case; the other build censors it. - ResultWrapper build = await rpc.engine_forkchoiceUpdatedV5( - new ForkchoiceStateV1(parent.Hash!, Keccak.Zero, parent.Hash!), - BuildBogotaPayloadAttributes(inclusionList: satisfied ? inclusionList : [])); - ResultWrapper payloadResult = await rpc.engine_getPayloadV6(Bytes.FromHexString(build.Data.PayloadId!)); - ExecutionPayloadV4 payload = payloadResult.Data!.ExecutionPayload; - Assert.That(payload.Transactions, Has.Length.EqualTo(satisfied ? 1 : 0)); - // This node never answers ACCEPTED itself, so that status is forced on an otherwise processed payload. - TaskCompletionSource releaseProcessing = new(TaskCreationOptions.RunContinuationsAsynchronously); - TestBranchProcessorInterceptor branchProcessor = (TestBranchProcessorInterceptor)chain.BranchProcessor; - try - { - if (newPayloadStatus == PayloadStatus.Syncing) - { - OccupyBlockProcessor(chain, parent, releaseProcessing.Task); - } - else newPayloadHandler.Status = newPayloadStatus; + // A transaction of its own, so the block's execution dimension outgrows its state dimension. + Transaction included = Build.A.Transaction + .WithNonce(0).WithMaxFeePerGas(10.GWei).WithMaxPriorityFeePerGas(2.GWei) + .WithTo(TestItem.AddressA).SignedAndResolved(TestItem.PrivateKeyB).TestObject; + byte[][] firstList = [Rlp.Encode(included)]; - ResultWrapper newPayload = await rpc.engine_newPayloadV6( - payload, [], Keccak.Zero, payloadResult.Data!.ExecutionRequests, inclusionList); - using (Assert.EnterMultipleScope()) - { - Assert.That(newPayload.Data.Status, Is.EqualTo(newPayloadStatus)); - Assert.That(newPayload.Data.InclusionListSatisfied, Is.Null); - } - } - finally - { - releaseProcessing.TrySetResult(); - branchProcessor.ProcessingRelease = null; - newPayloadHandler.Status = null; - } - using CancellationTokenSource cts = new(TimeSpan.FromSeconds(20)); - while (!chain.BlockTree.WasProcessed(payload.BlockNumber, payload.BlockHash)) - { - await Task.Delay(20, cts.Token); - } + ResultWrapper payloadResult = await BuildBogotaPayload(rpc, chain.BlockTree.HeadHash, + BuildBogotaPayloadAttributes(firstList, targetGasLimit: gasLimit, timestamp: Timestamper.UnixTime.Seconds + 2, slotNumber: 2)); + ExecutionPayloadV4 first = payloadResult.Data!.ExecutionPayload; - if (stateReadThrows) headState.MissingNodeBlock = payload.BlockHash; + await NewPayloadV6(rpc, first, payloadResult.Data!.ExecutionRequests, firstList); + await BuildAndInsertEmptyBlock(chain, first.BlockHash, slot: 3, finalize: !resendHead); - // Attributes are attached so a failed evaluation is seen to cost no block proposal. - ResultWrapper fcu = await rpc.engine_forkchoiceUpdatedV5( - new ForkchoiceStateV1(payload.BlockHash, parent.Hash!, parent.Hash!), - BuildBogotaPayloadAttributes(inclusionList: [], timestamp: payload.Timestamp + 12, slotNumber: 2)); + Block executed = chain.BlockTree.FindBlock(first.BlockHash, BlockTreeLookupOptions.TotalDifficultyNotNeeded)!; + Assert.That(executed.Header.GasUsedPerDimension, Is.Not.Null, "the dimensions must reach the block a check is handed"); + (ulong execution, ulong state) = executed.Header.GasUsedPerDimension!.Value; using (Assert.EnterMultipleScope()) { - Assert.That(fcu.Result.ResultType, Is.EqualTo(ResultType.Success), fcu.Result.Error); - Assert.That(fcu.Data.PayloadStatus.Status, Is.EqualTo(PayloadStatus.Valid)); - Assert.That(fcu.Data.PayloadStatus.InclusionListSatisfied, Is.EqualTo(stateReadThrows ? null : satisfied)); - Assert.That(fcu.Data.PayloadId, Is.Not.Null); + Assert.That(executed.Transactions, Has.Length.EqualTo(1)); + Assert.That(Math.Max(execution, state), Is.EqualTo(executed.GasUsed), "EIP-8037 reduces the dimensions to their maximum"); + Assert.That(execution, Is.GreaterThan(state), "the max must exceed the state dimension for the two rules to differ"); } - } - // The inclusion list is a per-call parameter, not a property of the block, so the answer newPayloadV6 - // cached for one call must never stand in for a later call that supplied a different list. - [TestCase(true, false, false, TestName = "ForkchoiceUpdatedV5_recomputes_a_resent_inclusion_list_once_the_head_state_is_readable")] - [TestCase(false, false, null, TestName = "ForkchoiceUpdatedV5_reports_null_for_a_resent_inclusion_list_it_cannot_evaluate")] - [TestCase(true, true, false, TestName = "ForkchoiceUpdatedV5_reports_censorship_proven_without_gas_dimensions")] - public async Task ForkchoiceUpdatedV5_does_not_answer_a_resent_inclusion_list_from_the_previous_answer( - bool stateHealed, bool dimensionsLost, bool? expected) - { - HeadStateInterceptor headState = new(); - using MergeTestBlockchain chain = await CreateBlockchainWithHeadState(headState, - new MergeConfig { TerminalTotalDifficulty = "0", NewPayloadCacheSize = 0 }); - IEngineRpcModule rpc = chain.EngineRpcModule; + // Reserves the whole remaining state dimension, and only the execution cap on the execution dimension: + // appendable on the recorded dimensions, over budget against max(execution, state). + Transaction censored = Build.A.Transaction + .WithNonce(entry == InclusionListEntry.WrongNonce ? 99UL : 0UL) + .WithGasLimit(entry is InclusionListEntry.Small or InclusionListEntry.WrongNonce ? 100_000UL : gasLimit - state).WithMaxFeePerGas(10.GWei).WithMaxPriorityFeePerGas(2.GWei) + .WithTo(TestItem.AddressA).SignedAndResolved(TestItem.PrivateKeyC).TestObject; + if (entry == InclusionListEntry.Boundary) + Assert.That(censored.GasLimit, Is.GreaterThan(gasLimit - execution), "the entry must not fit the max"); - // An empty list is trivially satisfied, so this leaves inclusionListSatisfied=true cached for the head. - ExecutionPayloadV4 payload = await BuildAndInsertEmptyBlock(chain, chain.BlockTree.HeadHash, slot: 2); + // What a restart leaves behind: the payload cache is already past this block at size 1, and a header + // read back from disk carries no dimensions. + if (resendHead) + { + await rpc.engine_forkchoiceUpdatedV5( + new ForkchoiceStateV1(first.BlockHash, first.BlockHash, first.BlockHash), payloadAttributes: null); + Assert.That(chain.BlockTree.HeadHash, Is.EqualTo(first.BlockHash), "the resend must target the current head"); + } - await RetainInclusionListByPrunedResend(rpc, headState, payload, [Rlp.Encode(BuildInclusionListTransfer())]); - if (!stateHealed) headState.PrunedBlock = payload.BlockHash; if (dimensionsLost) { - Block executed = chain.BlockTree.FindBlock(payload.BlockHash, BlockTreeLookupOptions.TotalDifficultyNotNeeded)!; - Assert.That(executed.Header.GasUsedPerDimension, Is.Not.Null); executed.Header.GasUsedPerDimension = null; - chain.BlockTree.FindHeader(payload.BlockHash, BlockTreeLookupOptions.TotalDifficultyNotNeeded)!.GasUsedPerDimension = null; - Assert.That(chain.StateReader.HasStateForBlock(executed.Header), Is.True, - "readable state alone cannot recover EIP-8037 gas dimensions"); + chain.BlockTree.FindHeader(first.BlockHash, BlockTreeLookupOptions.TotalDifficultyNotNeeded)!.GasUsedPerDimension = null; } - ResultWrapper fcu = await rpc.engine_forkchoiceUpdatedV5( - new ForkchoiceStateV1(payload.BlockHash, payload.BlockHash, payload.BlockHash), payloadAttributes: null); + accountReader.TrackedBlockHash = first.BlockHash; + + ResultWrapper resend = await NewPayloadV6(rpc, first, [], entry == InclusionListEntry.Included ? firstList : [Rlp.Encode(censored)]); + bool? verdict = resend.Data.InclusionListSatisfied; + + bool answerUnavailable = dimensionsLost && entry == InclusionListEntry.Boundary; + bool expectedSatisfied = entry is InclusionListEntry.Included or InclusionListEntry.WrongNonce; using (Assert.EnterMultipleScope()) { - Assert.That(fcu.Data.PayloadStatus.Status, Is.EqualTo(PayloadStatus.Valid)); - Assert.That(fcu.Data.PayloadStatus.InclusionListSatisfied, Is.EqualTo(expected)); + if (dimensionsLost && entry is InclusionListEntry.WrongNonce) + Assert.That(accountReader.AccountReads, Is.EqualTo(1), "all gas-bound passes must share the sender account read"); + Assert.That(resend.Data.Status, Is.EqualTo(answerUnavailable ? PayloadStatus.Syncing : PayloadStatus.Valid)); + Assert.That(verdict, answerUnavailable ? Is.Null : Is.EqualTo(expectedSatisfied), + answerUnavailable ? "without the dimensions the check must not be guessed" + : expectedSatisfied ? "the entry is included or cannot be appended" + : "the omitted entry fits the remaining gas dimensions"); + Assert.That(executed.Header.GasUsedPerDimension, dimensionsLost ? Is.Null : Is.Not.Null, "bounds must not alter the tree's header"); } } - [Test] - public async Task ForkchoiceUpdatedV5_retains_an_unresolved_branch_tip_across_unrelated_payloads() + /// Wraps the chain's so one block's state can be made unreadable. + /// + /// is assigned once the chain is built, because the reader being wrapped is itself one + /// of the chain's components; nothing reads state during the build. + /// + private sealed class HeadStateInterceptor : IStateReader { - HeadStateInterceptor headState = new(); - using MergeTestBlockchain chain = await CreateBlockchainWithHeadState(headState); - IEngineRpcModule rpc = chain.EngineRpcModule; - Hash256 parentHash = chain.BlockTree.HeadHash; + public IStateReader Inner { get; set; } = null!; - ExecutionPayloadV4 first = await BuildAndInsertEmptyBlock(chain, parentHash, slot: 2, finalize: false); - await RetainInclusionListByPrunedResend(rpc, headState, first, [Rlp.Encode(BuildInclusionListTransfer())]); + /// Block whose state must appear pruned, as it is once the block leaves the pruning window. + public Hash256? PrunedBlock { get; set; } - for (ulong slot = 3; slot < 21; slot++) - { - await BuildAndInsertEmptyBlock(chain, parentHash, slot, finalize: false); - } + /// Block whose account reads must throw, as they do when a subtrie node is absent under a present root. + public Hash256? MissingNodeBlock { get; set; } - ResultWrapper fcu = await rpc.engine_forkchoiceUpdatedV5( - new ForkchoiceStateV1(first.BlockHash, parentHash, parentHash), payloadAttributes: null); - using (Assert.EnterMultipleScope()) - { - Assert.That(fcu.Data.PayloadStatus.Status, Is.EqualTo(PayloadStatus.Valid)); - Assert.That(fcu.Data.PayloadStatus.InclusionListSatisfied, Is.False); - } - } + public bool HasStateForBlock(BlockHeader? baseBlock) => !Matches(baseBlock, PrunedBlock) && Inner.HasStateForBlock(baseBlock); - [Test] - public async Task ForkchoiceUpdatedV5_answers_a_parent_head_whose_child_was_validated( - [Values] bool parentAnswered, [Values(PayloadStatus.Valid, PayloadStatus.Accepted, PayloadStatus.Syncing)] string childStatus) - { - HeadStateInterceptor headState = new(); - StatusOverridingNewPayloadHandler newPayloadHandler = new(); - using MergeTestBlockchain chain = await CreateBlockchainWithHeadState(headState, configure: builder => builder - .AddDecorator>((_, inner) => - { - newPayloadHandler.Inner = inner; - return newPayloadHandler; - })); - IEngineRpcModule rpc = chain.EngineRpcModule; - Hash256 genesis = chain.BlockTree.HeadHash; + public bool TryGetAccount(BlockHeader? baseBlock, Address address, out AccountStruct account) => + Matches(baseBlock, MissingNodeBlock) + ? throw new MissingTrieNodeException("Node missing", null, TreePath.Empty, Keccak.Zero) + : Inner.TryGetAccount(baseBlock, address, out account); - ExecutionPayloadV4 parent = await BuildAndInsertEmptyBlock(chain, genesis, slot: 2, finalize: false, finalizedHash: genesis); - ExecutionPayloadV4 child = await BuildAndInsertEmptyBlock(chain, parent.BlockHash, slot: 3, finalize: false, finalizedHash: genesis); - byte[][] inclusionList = [Rlp.Encode(BuildInclusionListTransfer())]; + public void GetStorage(BlockHeader? baseBlock, Address address, in UInt256 index, out UInt256 value) => + Inner.GetStorage(baseBlock, address, in index, out value); - if (parentAnswered) - { - ResultWrapper censored = await rpc.engine_newPayloadV6(parent, [], Keccak.Zero, [], inclusionList); - Assert.That(censored.Data.InclusionListSatisfied, Is.False); - } - else - { - await RetainInclusionListByPrunedResend(rpc, headState, parent, inclusionList); - } + public byte[]? GetCode(Hash256 codeHash) => Inner.GetCode(codeHash); - if (childStatus == PayloadStatus.Syncing) - { - await RetainInclusionListByPrunedResend(rpc, headState, child, inclusionList); - ResultWrapper childFcu = await rpc.engine_forkchoiceUpdatedV5( - new ForkchoiceStateV1(child.BlockHash, genesis, genesis), payloadAttributes: null); - Assert.That(childFcu.Data.PayloadStatus.InclusionListSatisfied, Is.False); - } - else - { - newPayloadHandler.Status = childStatus == PayloadStatus.Accepted ? childStatus : null; - ResultWrapper childResend = await rpc.engine_newPayloadV6(child, [], Keccak.Zero, [], inclusionList); - newPayloadHandler.Status = null; - using (Assert.EnterMultipleScope()) - { - Assert.That(childResend.Data.Status, Is.EqualTo(childStatus)); - Assert.That(childResend.Data.InclusionListSatisfied, Is.EqualTo(childStatus == PayloadStatus.Valid ? false : null)); - } - } + public byte[]? GetCode(in ValueHash256 codeHash) => Inner.GetCode(in codeHash); - ResultWrapper fcu = await rpc.engine_forkchoiceUpdatedV5( - new ForkchoiceStateV1(parent.BlockHash, genesis, genesis), payloadAttributes: null); - using (Assert.EnterMultipleScope()) - { - Assert.That(fcu.Data.PayloadStatus.Status, Is.EqualTo(PayloadStatus.Valid)); - Assert.That(fcu.Data.PayloadStatus.InclusionListSatisfied, Is.False); - } - } + public void RunTreeVisitor(ITreeVisitor treeVisitor, BlockHeader? baseBlock, VisitingOptions? visitingOptions = null, VisitingStats? diagnostics = null) + where TCtx : struct, INodeContext => Inner.RunTreeVisitor(treeVisitor, baseBlock, visitingOptions, diagnostics); - [Test] - public async Task ForkchoiceUpdatedV5_prunes_earlier_syncing_lists_when_a_descendant_is_finalized() - { - HeadStateInterceptor headState = new(); - using MergeTestBlockchain chain = await CreateBlockchainWithHeadState(headState); - EngineRpcModule rpc = (EngineRpcModule)chain.EngineRpcModule; - Hash256 genesis = chain.BlockTree.HeadHash; - - ExecutionPayloadV4 first = await BuildAndInsertEmptyBlock(chain, genesis, slot: 2, finalize: false, finalizedHash: genesis); - ExecutionPayloadV4 second = await BuildAndInsertEmptyBlock(chain, first.BlockHash, slot: 3, finalize: false, finalizedHash: genesis); - ExecutionPayloadV4 third = await BuildAndInsertEmptyBlock(chain, second.BlockHash, slot: 4, finalize: false, finalizedHash: genesis); - ExecutionPayloadV4 sibling = await BuildAndInsertEmptyBlock(chain, second.BlockHash, slot: 5, finalize: false, finalizedHash: genesis); - - byte[][] inclusionList = [Rlp.Encode(BuildInclusionListTransfer())]; - await RetainInclusionListByPrunedResend(rpc, headState, first, inclusionList); - await RetainInclusionListByPrunedResend(rpc, headState, second, inclusionList); - ResultWrapper thirdResend = await rpc.engine_newPayloadV6(third, [], Keccak.Zero, [], []); - - using (Assert.EnterMultipleScope()) - { - Assert.That(thirdResend.Data.Status, Is.EqualTo(PayloadStatus.Valid)); - Assert.That(rpc.HasRetainedInclusionList(first.BlockHash), Is.True, - "a VALID grandchild alone does not make the earlier SYNCING list disappear"); - } - - ResultWrapper syncingFcu = await rpc.engine_forkchoiceUpdatedV5( - new ForkchoiceStateV1(Keccak.Compute("unknown-head"), third.BlockHash, third.BlockHash), payloadAttributes: null); - using (Assert.EnterMultipleScope()) - { - Assert.That(syncingFcu.Data.PayloadStatus.Status, Is.EqualTo(PayloadStatus.Syncing)); - Assert.That(rpc.HasRetainedInclusionList(first.BlockHash), Is.False, - "a SYNCING forkchoice update must still prune blocks behind its finalized marker"); - } - - ResultWrapper finalizing = await rpc.engine_forkchoiceUpdatedV5( - new ForkchoiceStateV1(third.BlockHash, third.BlockHash, third.BlockHash), payloadAttributes: null); - using (Assert.EnterMultipleScope()) - { - Assert.That(finalizing.Data.PayloadStatus.Status, Is.EqualTo(PayloadStatus.Valid)); - Assert.That(rpc.HasRetainedInclusionList(first.BlockHash), Is.False); - Assert.That(rpc.HasRetainedInclusionList(second.BlockHash), Is.False); - Assert.That(rpc.HasInclusionListAnswer(third.BlockHash), Is.True); - Assert.That(rpc.HasInclusionListAnswer(sibling.BlockHash), Is.False); - } - } - - [Test] - public async Task Inclusion_list_cache_keeps_accepted_tips_without_finality() - { - using MergeTestBlockchain chain = await CreateBlockchain(Bogota.Instance, - new MergeConfig { TerminalTotalDifficulty = "0" }); - EngineRpcModule rpc = (EngineRpcModule)chain.EngineRpcModule; - Hash256 first = Keccak.Compute(BitConverter.GetBytes(0)); - Hash256 newest = first; - - for (int i = 0; i < 300; i++) - { - newest = Keccak.Compute(BitConverter.GetBytes(i)); - rpc.SetRetainedInclusionList(newest, (ulong)i + 1, [new byte[1]], accepted: true); - } - - using (Assert.EnterMultipleScope()) - { - Assert.That(rpc.RetainedInclusionListCount, Is.EqualTo(300)); - Assert.That(rpc.HasRetainedInclusionList(first), Is.True); - Assert.That(rpc.HasRetainedInclusionList(newest), Is.True); - } - } - - [Test] - public async Task Inclusion_list_cache_limits_syncing_entries_without_evicting_accepted_tips() - { - using MergeTestBlockchain chain = await CreateBlockchain(Bogota.Instance, - new MergeConfig { TerminalTotalDifficulty = "0" }); - EngineRpcModule rpc = (EngineRpcModule)chain.EngineRpcModule; - Hash256 accepted = Keccak.Compute("accepted-tip"); - Hash256 oldestSyncing = Keccak.Compute(BitConverter.GetBytes(0)); - Hash256 newestSyncing = oldestSyncing; - - rpc.SetRetainedInclusionList(accepted, 1, [new byte[1]], accepted: true); - for (int i = 0; i < 65; i++) - { - newestSyncing = Keccak.Compute(BitConverter.GetBytes(i)); - rpc.SetRetainedInclusionList(newestSyncing, 1, [new byte[1]], accepted: false); - } - - using (Assert.EnterMultipleScope()) - { - Assert.That(rpc.RetainedInclusionListCount, Is.EqualTo(65)); - Assert.That(rpc.HasRetainedInclusionList(accepted), Is.True); - Assert.That(rpc.HasRetainedInclusionList(oldestSyncing), Is.False); - Assert.That(rpc.HasRetainedInclusionList(newestSyncing), Is.True); - } - } - - [Test] - public async Task Inclusion_list_cache_limits_answers_without_finality() - { - using MergeTestBlockchain chain = await CreateBlockchain(Bogota.Instance, - new MergeConfig { TerminalTotalDifficulty = "0" }); - EngineRpcModule rpc = (EngineRpcModule)chain.EngineRpcModule; - Hash256 oldest = Keccak.Compute(BitConverter.GetBytes(0)); - Hash256 newest = oldest; - - for (int i = 0; i < 257; i++) - { - newest = Keccak.Compute(BitConverter.GetBytes(i)); - rpc.SetInclusionListAnswer(newest, (ulong)i + 1, answer: true); - } - - using (Assert.EnterMultipleScope()) - { - Assert.That(rpc.HasInclusionListAnswer(oldest), Is.False); - Assert.That(rpc.HasInclusionListAnswer(newest), Is.True); - } - } - - // A newPayloadV6 landing while forkchoiceUpdatedV5 evaluates the retained list wins: the answer being - // computed is already stale, so publishing it would shadow the newer list on every later update. - [Test] - public async Task ForkchoiceUpdatedV5_does_not_publish_an_answer_for_a_list_superseded_while_it_was_evaluated() - { - HeadStateInterceptor headState = new(); - InterleavingEvaluator evaluator = new(); - using MergeTestBlockchain chain = await CreateBlockchainWithInterleavingEvaluator(headState, evaluator); - IEngineRpcModule rpc = chain.EngineRpcModule; - - ExecutionPayloadV4 payload = await BuildAndInsertEmptyBlock(chain, chain.BlockTree.HeadHash, slot: 2); - await RetainInclusionListByPrunedResend(rpc, headState, payload, [Rlp.Encode(BuildInclusionListTransfer())]); - - // A nonce the sender is past cannot be appended, so this list is satisfied where the censoring one is not. - Transaction unappendableTx = Build.A.Transaction - .WithNonce(99).WithMaxFeePerGas(10.GWei).WithMaxPriorityFeePerGas(2.GWei).WithGasLimit(100_000) - .WithTo(TestItem.AddressA).SignedAndResolved(TestItem.PrivateKeyB).TestObject; - - // Stand in for the concurrent call: retain the satisfied list after the forkchoice update has read the - // censoring one but before it can publish an answer for it. - evaluator.BeforeEvaluate = () => - { - evaluator.BeforeEvaluate = null; - RetainInclusionListByPrunedResend(rpc, headState, payload, [Rlp.Encode(unappendableTx)]).GetAwaiter().GetResult(); - }; - - ForkchoiceStateV1 forkchoiceState = new(payload.BlockHash, payload.BlockHash, payload.BlockHash); - ResultWrapper superseded = await rpc.engine_forkchoiceUpdatedV5(forkchoiceState, payloadAttributes: null); - ResultWrapper next = await rpc.engine_forkchoiceUpdatedV5(forkchoiceState, payloadAttributes: null); - using (Assert.EnterMultipleScope()) - { - Assert.That(superseded.Data.PayloadStatus.InclusionListSatisfied, Is.False, "answer for the list that update read"); - Assert.That(next.Data.PayloadStatus.InclusionListSatisfied, Is.True, "answer for the list that superseded it"); - } - } - - // bogota.md lets a retained list go only once its payload is no longer a tip, so an evaluation that - // threw answers null for that call alone and a later update still gets to answer. - [Test] - public async Task ForkchoiceUpdatedV5_re_evaluates_a_retained_list_after_an_evaluation_threw() - { - HeadStateInterceptor headState = new(); - InterleavingEvaluator evaluator = new(); - using MergeTestBlockchain chain = await CreateBlockchainWithInterleavingEvaluator(headState, evaluator); - IEngineRpcModule rpc = chain.EngineRpcModule; - - ExecutionPayloadV4 payload = await BuildAndInsertEmptyBlock(chain, chain.BlockTree.HeadHash, slot: 2); - await RetainInclusionListByPrunedResend(rpc, headState, payload, [Rlp.Encode(BuildInclusionListTransfer())]); - - int evaluations = 0; - evaluator.BeforeEvaluate = () => - { - if (++evaluations == 1) throw new InvalidOperationException("evaluation failed"); - }; - - ForkchoiceStateV1 forkchoiceState = new(payload.BlockHash, payload.BlockHash, payload.BlockHash); - ResultWrapper first = await rpc.engine_forkchoiceUpdatedV5(forkchoiceState, payloadAttributes: null); - ResultWrapper second = await rpc.engine_forkchoiceUpdatedV5(forkchoiceState, payloadAttributes: null); - using (Assert.EnterMultipleScope()) - { - Assert.That(first.Data.PayloadStatus.Status, Is.EqualTo(PayloadStatus.Valid)); - Assert.That(first.Data.PayloadStatus.InclusionListSatisfied, Is.Null, "the failed evaluation cannot answer"); - Assert.That(second.Data.PayloadStatus.InclusionListSatisfied, Is.False); - Assert.That(evaluations, Is.EqualTo(2), "the retained list must survive an evaluation that threw"); - } - } - - /// - /// A payload resent with another inclusion list while the copy a timed-out request left behind is still queued. - /// That copy's verdict judged the list it carried, so it must not answer the resend. - /// - [Test, NonParallelizable] - public async Task NewPayloadV6_validates_resent_inclusion_list_independently_of_queued_copy() - { - CommitWaitProbe probe = new(); - using MergeTestBlockchain chain = await CreateBlockchain(Bogota.Instance, - new MergeConfig { TerminalTotalDifficulty = "0", NewPayloadBlockProcessingTimeout = 30_000 }, - configurer: builder => builder.AddDecorator((_, inner) => new CommitWaitObservingQueue(inner, probe, typeof(NewPayloadHandler)))); - IEngineRpcModule rpc = chain.EngineRpcModule; - Block parent = chain.BlockTree.Head!; - - ResultWrapper build = await rpc.engine_forkchoiceUpdatedV5( - new ForkchoiceStateV1(parent.Hash!, Keccak.Zero, parent.Hash!), BuildBogotaPayloadAttributes(inclusionList: [])); - ResultWrapper built = await rpc.engine_getPayloadV6(Bytes.FromHexString(build.Data.PayloadId!)); - ExecutionPayloadV4 payload = built.Data!.ExecutionPayload; - byte[][] requests = built.Data!.ExecutionRequests!; - Assert.That(payload.Transactions, Is.Empty); - - payload.ParentBeaconBlockRoot = Keccak.Zero; - payload.ExecutionRequests = requests; - Block queuedCopy = payload.TryGetBlock(parent.TotalDifficulty).Data!; - queuedCopy.Header.IsPostMerge = true; - Assert.That(queuedCopy.CalculateHash(), Is.EqualTo(payload.BlockHash)); - - TaskCompletionSource releaseProcessing = new(TaskCreationOptions.RunContinuationsAsynchronously); - TestBranchProcessorInterceptor branchProcessor = (TestBranchProcessorInterceptor)chain.BranchProcessor; - TaskCompletionSource firstCopyQueued = new(TaskCreationOptions.RunContinuationsAsynchronously); - TaskCompletionSource secondCopyQueued = new(TaskCreationOptions.RunContinuationsAsynchronously); - chain.BlockProcessingQueue.BlockAdded += (_, e) => - { - if (e.Block.Hash != payload.BlockHash) return; - if (ReferenceEquals(e.Block, queuedCopy)) firstCopyQueued.TrySetResult(); - else secondCopyQueued.TrySetResult(); - }; - - Task> resend; - try - { - OccupyBlockProcessor(chain, parent, releaseProcessing.Task); - Assert.That(await chain.BlockTree.SuggestBlockAsync(queuedCopy, BlockTreeSuggestOptions.ForceDontSetAsMain), Is.EqualTo(AddBlockResult.Added)); - _ = Task.Run(async () => await chain.BlockProcessingQueue.Enqueue(queuedCopy, ProcessingOptions.EthereumMerge)); - await firstCopyQueued.Task.WaitAsync(TimeSpan.FromSeconds(10)); - - probe.Watch(payload.BlockHash); - resend = rpc.engine_newPayloadV6(payload, [], Keccak.Zero, requests, [Rlp.Encode(BuildInclusionListTransfer())]); - await Task.WhenAny(secondCopyQueued.Task, probe.RemovalWaitPending.Task).WaitAsync(TimeSpan.FromSeconds(10)); - } - finally - { - releaseProcessing.TrySetResult(); - branchProcessor.ProcessingRelease = null; - } - - ResultWrapper result = await resend; - using (Assert.EnterMultipleScope()) - { - Assert.That(result.Data.Status, Is.EqualTo(PayloadStatus.Valid)); - Assert.That(result.Data.InclusionListSatisfied, Is.False); - } - } - - /// - /// A payload resent after its newPayload timed out, while the copy that request queued is still waiting. - /// A resend without that copy's list must not take its verdict; one with the same list takes it on that copy's - /// verdict, before the copy commits. - /// - [TestCase(false, true, TestName = "NewPayloadV6_does_not_answer_an_empty_list_resend_from_a_queued_copy_with_a_list")] - [TestCase(true, false, TestName = "NewPayloadV6_answers_a_same_list_resend_from_the_queued_copy")] - [NonParallelizable] - public async Task NewPayloadV6_answers_a_resend_after_a_timeout_against_its_own_list(bool resendSameList, bool satisfied) - { - const int budgetMs = 3_000; - CommitWaitProbe probe = new(); - // The handler's budget runs on this clock, so only the first request times out, and only when the test says so. - ManualTimeProvider clock = new(); - using MergeTestBlockchain chain = await CreateBlockchain(Bogota.Instance, - new MergeConfig { TerminalTotalDifficulty = "0", NewPayloadBlockProcessingTimeout = budgetMs }, - configurer: builder => builder - .AddDecorator((_, inner) => new CommitWaitObservingQueue(inner, probe, typeof(NewPayloadHandler))) - .UpdateSingleton(inner => inner.AddSingleton(clock))); - IEngineRpcModule rpc = chain.EngineRpcModule; - Block parent = chain.BlockTree.Head!; - byte[][] inclusionList = [Rlp.Encode(BuildInclusionListTransfer())]; - - ResultWrapper build = await rpc.engine_forkchoiceUpdatedV5( - new ForkchoiceStateV1(parent.Hash!, Keccak.Zero, parent.Hash!), BuildBogotaPayloadAttributes(inclusionList: [])); - ResultWrapper built = await rpc.engine_getPayloadV6(Bytes.FromHexString(build.Data.PayloadId!)); - ExecutionPayloadV4 payload = built.Data!.ExecutionPayload; - byte[][] requests = built.Data!.ExecutionRequests!; - Assert.That(payload.Transactions, Is.Empty); - - int copiesQueued = 0; - int executed = 0; - TaskCompletionSource resendAnswered = new(TaskCreationOptions.RunContinuationsAsynchronously); - TaskCompletionSource firstCopyQueued = new(TaskCreationOptions.RunContinuationsAsynchronously); - TaskCompletionSource secondCopyQueued = new(TaskCreationOptions.RunContinuationsAsynchronously); - chain.BlockProcessingQueue.BlockAdded += (_, e) => - { - if (e.Block.Hash != payload.BlockHash) return; - int copy = Interlocked.Increment(ref copiesQueued); - if (copy == 1) firstCopyQueued.TrySetResult(); - else if (copy == 2) secondCopyQueued.TrySetResult(); - }; - chain.BlockProcessingQueue.BlockExecuted += (_, e) => - { - if (e.BlockHash != payload.BlockHash) return; - if (Interlocked.Increment(ref executed) == 1 && resendSameList) resendAnswered.Task.Wait(TimeSpan.FromSeconds(10)); - }; - - TaskCompletionSource releaseProcessing = new(TaskCreationOptions.RunContinuationsAsynchronously); - TestBranchProcessorInterceptor branchProcessor = (TestBranchProcessorInterceptor)chain.BranchProcessor; - Task> resend; - try - { - OccupyBlockProcessor(chain, parent, releaseProcessing.Task); - Task> timingOut = rpc.engine_newPayloadV6(payload, [], Keccak.Zero, requests, inclusionList); - // Out of budget only once its copy is queued, so the request leaves that copy behind with its list. The - // clock fires only the last timer it created, which here is this request's timeout. - await firstCopyQueued.Task.WaitAsync(TimeSpan.FromSeconds(10)); - clock.AdvanceAndFireTimer(TimeSpan.FromMilliseconds(budgetMs)); - ResultWrapper timedOut = await timingOut.WaitAsync(TimeSpan.FromSeconds(10)); - Assert.That(timedOut.Data.Status, Is.EqualTo(PayloadStatus.Syncing)); - - probe.Watch(payload.BlockHash); - resend = rpc.engine_newPayloadV6(payload, [], Keccak.Zero, requests, resendSameList ? inclusionList : []); - await Task.WhenAny(secondCopyQueued.Task, probe.RemovalWaitPending.Task).WaitAsync(TimeSpan.FromSeconds(10)); - } - finally - { - releaseProcessing.TrySetResult(); - branchProcessor.ProcessingRelease = null; - } + public void RunTreeVisitor(INodeRecordVisitor visitor, BlockHeader? baseBlock, VisitingOptions? visitingOptions, VisitingStats? diagnostics) + where TCtx : struct, INodeContext => Inner.RunTreeVisitor(visitor, baseBlock, visitingOptions, diagnostics); - ResultWrapper result = await resend.WaitAsync(TimeSpan.FromSeconds(10)); - resendAnswered.TrySetResult(); - await WaitForCommit(chain, payload.BlockHash); - using (Assert.EnterMultipleScope()) - { - Assert.That(result.Data.Status, Is.EqualTo(PayloadStatus.Valid)); - Assert.That(result.Data.InclusionListSatisfied, Is.EqualTo(satisfied)); - } + private static bool Matches(BlockHeader? header, Hash256? hash) => hash is not null && header?.Hash == hash; } /// Builds a Bogota chain whose reads state through . @@ -1910,29 +1399,6 @@ private async Task CreateBlockchainWithHeadState(HeadStateI return chain; } - private Task CreateBlockchainWithInterleavingEvaluator(HeadStateInterceptor headState, InterleavingEvaluator evaluator) => - CreateBlockchainWithHeadState(headState, configure: builder => builder - .AddDecorator((_, inner) => - { - evaluator.Inner = inner; - return evaluator; - })); - - /// Resends with its state hidden, so newPayloadV6 answers SYNCING - /// and is left retained for the forkchoice update. - private static async Task RetainInclusionListByPrunedResend(IEngineRpcModule rpc, HeadStateInterceptor headState, - ExecutionPayloadV4 payload, byte[][] inclusionList) - { - headState.PrunedBlock = payload.BlockHash; - ResultWrapper resend = await rpc.engine_newPayloadV6(payload, [], Keccak.Zero, [], inclusionList); - headState.PrunedBlock = null; - using (Assert.EnterMultipleScope()) - { - Assert.That(resend.Data.Status, Is.EqualTo(PayloadStatus.Syncing), "the resend must leave its list retained"); - Assert.That(resend.Data.InclusionListSatisfied, Is.Null); - } - } - /// Occupies the block processor so the payload sent next has to queue and its newPayload times out. /// The block that holds the processor until completes. internal static Block OccupyBlockProcessor(MergeTestBlockchain chain, Block parent, Task processingRelease) @@ -1964,193 +1430,6 @@ private static Transaction BuildInclusionListTransfer() => Build.A.Transaction .WithNonce(0).WithMaxFeePerGas(10.GWei).WithMaxPriorityFeePerGas(2.GWei).WithGasLimit(100_000) .WithTo(TestItem.AddressA).SignedAndResolved(TestItem.PrivateKeyB).TestObject; - /// Forces a chosen status onto newPayload results after the wrapped handler has run. - private sealed class StatusOverridingNewPayloadHandler : IAsyncHandler - { - public IAsyncHandler Inner { get; set; } = null!; - - /// Status to answer with, or null to pass the wrapped handler's result through. - public string? Status { get; set; } - - public async Task> HandleAsync(ExecutionPayload request) - { - ResultWrapper result = await Inner.HandleAsync(request); - return Status is { } status ? ResultWrapper.Success(new PayloadStatusV1 { Status = status }) : result; - } - } - - /// Wraps the chain's so a test can act inside the - /// window between engine_forkchoiceUpdatedV5 reading the retained list and publishing an answer. - private sealed class InterleavingEvaluator : IInclusionListComplianceEvaluator - { - public IInclusionListComplianceEvaluator Inner { get; set; } = null!; - - public Action? BeforeEvaluate { get; set; } - - public bool? TryEvaluate(Hash256 blockHash, byte[][] inclusionListTransactions) - { - BeforeEvaluate?.Invoke(); - return Inner.TryEvaluate(blockHash, inclusionListTransactions); - } - } - - /// Wraps the chain's so one block's state can be made unreadable. - /// - /// is assigned once the chain is built, because the reader being wrapped is itself one - /// of the chain's components; nothing reads state during the build. - /// - private sealed class HeadStateInterceptor : IStateReader - { - public IStateReader Inner { get; set; } = null!; - - /// Block whose state must appear pruned, as it is once the block leaves the pruning window. - public Hash256? PrunedBlock { get; set; } - - /// Block whose account reads must throw, as they do when a subtrie node is absent under a present root. - public Hash256? MissingNodeBlock { get; set; } - - public bool HasStateForBlock(BlockHeader? baseBlock) => !Matches(baseBlock, PrunedBlock) && Inner.HasStateForBlock(baseBlock); - - public bool TryGetAccount(BlockHeader? baseBlock, Address address, out AccountStruct account) => - Matches(baseBlock, MissingNodeBlock) - ? throw new MissingTrieNodeException("Node missing", null, TreePath.Empty, Keccak.Zero) - : Inner.TryGetAccount(baseBlock, address, out account); - - public void GetStorage(BlockHeader? baseBlock, Address address, in UInt256 index, out UInt256 value) => - Inner.GetStorage(baseBlock, address, in index, out value); - - public byte[]? GetCode(Hash256 codeHash) => Inner.GetCode(codeHash); - - public byte[]? GetCode(in ValueHash256 codeHash) => Inner.GetCode(in codeHash); - - public void RunTreeVisitor(ITreeVisitor treeVisitor, BlockHeader? baseBlock, VisitingOptions? visitingOptions = null, VisitingStats? diagnostics = null) - where TCtx : struct, INodeContext => Inner.RunTreeVisitor(treeVisitor, baseBlock, visitingOptions, diagnostics); - - public void RunTreeVisitor(INodeRecordVisitor visitor, BlockHeader? baseBlock, VisitingOptions? visitingOptions, VisitingStats? diagnostics) - where TCtx : struct, INodeContext => Inner.RunTreeVisitor(visitor, baseBlock, visitingOptions, diagnostics); - - private static bool Matches(BlockHeader? header, Hash256? hash) => hash is not null && header?.Hash == hash; - } - - // The re-check must judge the resent list on the dimensions execution recorded, not on the max(execution, - // state) the header reduces them to. The two differ only above the EIP-7825 execution cap: past it a - // transaction reserves the cap on the execution dimension but its whole gas on the state one, so an entry - // that fits both dimensions reads as unappendable against the max, and real censorship goes unreported. - // After cache loss, bounds still prove some verdicts. Only ambiguous cases answer SYNCING with null - // compliance (bogota.md newPayloadV6 (2.2)); recovering their exact answer needs safe re-execution. - [TestCase(50, false, InclusionListEntry.Boundary, false, TestName = "NewPayloadV6_re_judges_a_resent_block_on_the_recorded_gas_dimensions")] - [TestCase(1, false, InclusionListEntry.Boundary, false, TestName = "NewPayloadV6_re_judges_a_resent_block_on_the_recorded_gas_dimensions_after_the_payload_cache_evicts_it")] - [TestCase(1, true, InclusionListEntry.Boundary, false, TestName = "NewPayloadV6_declines_to_judge_a_resent_block_once_both_caches_lose_the_gas_dimensions")] - [TestCase(1, true, InclusionListEntry.Included, false, TestName = "NewPayloadV6_answers_an_included_list_after_both_dimension_caches_are_lost")] - [TestCase(1, true, InclusionListEntry.Boundary, true, TestName = "NewPayloadV6_declines_an_omitted_list_for_the_head_after_both_dimension_caches_are_lost")] - [TestCase(1, true, InclusionListEntry.Included, true, TestName = "NewPayloadV6_answers_an_included_list_for_the_head_after_both_dimension_caches_are_lost")] - [TestCase(1, true, InclusionListEntry.Small, false, TestName = "NewPayloadV6_reports_censorship_proven_without_gas_dimensions")] - [TestCase(1, true, InclusionListEntry.Small, true, TestName = "NewPayloadV6_reports_censorship_for_the_head_without_gas_dimensions")] - [TestCase(1, true, InclusionListEntry.WrongNonce, false, TestName = "NewPayloadV6_answers_an_unappendable_list_without_gas_dimensions")] - [TestCase(1, true, InclusionListEntry.WrongNonce, true, TestName = "NewPayloadV6_answers_an_unappendable_list_for_the_head_without_gas_dimensions")] - public async Task NewPayloadV6_re_judges_a_resent_block_on_the_recorded_gas_dimensions( - int newPayloadCacheSize, bool dimensionsLost, InclusionListEntry entry, bool resendHead) - { - // Genesis is raised to the production target so the block's remaining gas exceeds the execution cap; - // the 4M default leaves no room for a transaction big enough to tell the two rules apart. - const ulong gasLimit = 30_000_000UL; - AccountReadCountingStateReader accountReader = null!; - using MergeTestBlockchain chain = await CreateBlockchain(Bogota.Instance, - new MergeConfig { TerminalTotalDifficulty = "0", NewPayloadCacheSize = newPayloadCacheSize }, - configurer: builder => builder - .WithGenesisPostProcessor((genesis, _) => genesis.Header.GasLimit = gasLimit) - // Every handler resolves its own decorated reader, so all share the first one's count. - .AddDecorator((_, reader) => - accountReader ??= new AccountReadCountingStateReader(reader, TestItem.AddressC))); - IEngineRpcModule rpc = chain.EngineRpcModule; - - // A transaction of its own, so the block's execution dimension outgrows its state dimension. - Transaction included = Build.A.Transaction - .WithNonce(0).WithMaxFeePerGas(10.GWei).WithMaxPriorityFeePerGas(2.GWei) - .WithTo(TestItem.AddressA).SignedAndResolved(TestItem.PrivateKeyB).TestObject; - byte[][] firstList = [Rlp.Encode(included)]; - - ResultWrapper fcu = await rpc.engine_forkchoiceUpdatedV5( - new ForkchoiceStateV1(chain.BlockTree.HeadHash, Keccak.Zero, chain.BlockTree.HeadHash), - BuildBogotaPayloadAttributes(firstList, targetGasLimit: gasLimit, timestamp: Timestamper.UnixTime.Seconds + 2, slotNumber: 2)); - ResultWrapper payloadResult = await rpc.engine_getPayloadV6(Bytes.FromHexString(fcu.Data.PayloadId!)); - ExecutionPayloadV4 first = payloadResult.Data!.ExecutionPayload; - - await rpc.engine_newPayloadV6(first, [], Keccak.Zero, payloadResult.Data!.ExecutionRequests, firstList); - await chain.WaitForCommitted(first.BlockHash); - await BuildAndInsertEmptyBlock(chain, first.BlockHash, slot: 3, finalize: !resendHead); - - Block executed = chain.BlockTree.FindBlock(first.BlockHash, BlockTreeLookupOptions.TotalDifficultyNotNeeded)!; - Assert.That(executed.Header.GasUsedPerDimension, Is.Not.Null, "the dimensions must reach the block a re-check is handed"); - (ulong execution, ulong state) = executed.Header.GasUsedPerDimension!.Value; - using (Assert.EnterMultipleScope()) - { - Assert.That(executed.Transactions, Has.Length.EqualTo(1)); - Assert.That(Math.Max(execution, state), Is.EqualTo(executed.GasUsed), "EIP-8037 reduces the dimensions to their maximum"); - Assert.That(execution, Is.GreaterThan(state), "the max must exceed the state dimension for the two rules to differ"); - } - - // Reserves the whole remaining state dimension, and only the execution cap on the execution dimension: - // appendable on the recorded dimensions, over budget against max(execution, state). - Transaction censored = Build.A.Transaction - .WithNonce(entry == InclusionListEntry.WrongNonce ? 99UL : 0UL) - .WithGasLimit(entry is InclusionListEntry.Small or InclusionListEntry.WrongNonce ? 100_000UL : gasLimit - state).WithMaxFeePerGas(10.GWei).WithMaxPriorityFeePerGas(2.GWei) - .WithTo(TestItem.AddressA).SignedAndResolved(TestItem.PrivateKeyC).TestObject; - if (entry == InclusionListEntry.Boundary) - Assert.That(censored.GasLimit, Is.GreaterThan(gasLimit - execution), "the entry must not fit the max"); - - // What a restart leaves behind: the payload cache is already past this block at size 1, and a header - // read back from disk carries no dimensions. Neither an ancestor nor the head itself can be - // re-executed to recover them here. - if (resendHead) - { - await rpc.engine_forkchoiceUpdatedV5( - new ForkchoiceStateV1(first.BlockHash, first.BlockHash, first.BlockHash), payloadAttributes: null); - Assert.That(chain.BlockTree.HeadHash, Is.EqualTo(first.BlockHash), "the resend must target the current head"); - } - - if (dimensionsLost) - { - executed.Header.GasUsedPerDimension = null; - chain.BlockTree.FindHeader(first.BlockHash, BlockTreeLookupOptions.TotalDifficultyNotNeeded)!.GasUsedPerDimension = null; - } - - accountReader.TrackedBlockHash = first.BlockHash; - - ResultWrapper resend = await rpc.engine_newPayloadV6( - first, [], Keccak.Zero, [], entry == InclusionListEntry.Included ? firstList : [Rlp.Encode(censored)]); - - if (dimensionsLost && resendHead && entry == InclusionListEntry.Boundary) - { - EngineRpcModule engineRpc = (EngineRpcModule)rpc; - Assert.That(engineRpc.HasRetainedInclusionList(first.BlockHash), Is.True); - Transaction[]? sharedList = executed.InclusionListTransactions; - ResultWrapper retained = await rpc.engine_forkchoiceUpdatedV5( - new ForkchoiceStateV1(first.BlockHash, first.BlockHash, first.BlockHash), payloadAttributes: null); - using (Assert.EnterMultipleScope()) - { - Assert.That(retained.Data.PayloadStatus.Status, Is.EqualTo(PayloadStatus.Valid)); - Assert.That(retained.Data.PayloadStatus.InclusionListSatisfied, Is.Null, - "the retained list remains ambiguous across gas-dimension bounds"); - Assert.That(executed.Header.GasUsedPerDimension, Is.Null, "bounds must not alter the tree's header"); - Assert.That(executed.InclusionListTransactions, Is.SameAs(sharedList), "the retained list must not replace the tree's list"); - } - } - - bool answerUnavailable = dimensionsLost && entry == InclusionListEntry.Boundary; - bool expectedSatisfied = entry is InclusionListEntry.Included or InclusionListEntry.WrongNonce; - using (Assert.EnterMultipleScope()) - { - if (dimensionsLost && entry is InclusionListEntry.WrongNonce) - Assert.That(accountReader.AccountReads, Is.EqualTo(1), "all gas-bound passes must share the sender account read"); - Assert.That(resend.Data.Status, Is.EqualTo(answerUnavailable ? PayloadStatus.Syncing : PayloadStatus.Valid)); - Assert.That(resend.Data.InclusionListSatisfied, answerUnavailable ? Is.Null : Is.EqualTo(expectedSatisfied), - answerUnavailable ? "without the dimensions the answer must be withheld, not guessed" - : expectedSatisfied ? "the entry is included or cannot be appended" - : "the omitted entry fits the remaining gas dimensions"); - } - } - [Test] public async Task Account_read_count_tracks_only_the_resend_execution_context() { @@ -2235,16 +1514,14 @@ private async Task BuildAndInsertEmptyBlock(MergeTestBlockch { IEngineRpcModule rpc = chain.EngineRpcModule; await chain.WaitForCommitted(parent); - ResultWrapper fcu = await rpc.engine_forkchoiceUpdatedV5( - new ForkchoiceStateV1(parent, Keccak.Zero, finalizedHash ?? parent), - BuildBogotaPayloadAttributes(inclusionList: [], timestamp: Timestamper.UnixTime.Seconds + slot, slotNumber: slot)); - ResultWrapper payloadResult = await rpc.engine_getPayloadV6(Bytes.FromHexString(fcu.Data.PayloadId!)); + ResultWrapper payloadResult = await BuildBogotaPayload(rpc, parent, + BuildBogotaPayloadAttributes(inclusionList: [], timestamp: Timestamper.UnixTime.Seconds + slot, slotNumber: slot), finalizedHash ?? parent); ExecutionPayloadV4 payload = payloadResult.Data!.ExecutionPayload; - await rpc.engine_newPayloadV6(payload, [], Keccak.Zero, payloadResult.Data!.ExecutionRequests, []); + await NewPayloadV6(rpc, payload, payloadResult.Data!.ExecutionRequests, []); await chain.WaitForCommitted(payload.BlockHash); Hash256 checkpoint = finalize ? payload.BlockHash : finalizedHash ?? parent; - ResultWrapper head = await rpc.engine_forkchoiceUpdatedV5( + ResultWrapper head = await rpc.engine_forkchoiceUpdatedV5( new ForkchoiceStateV1(payload.BlockHash, checkpoint, checkpoint), payloadAttributes: null); Assert.That(head.Data?.PayloadStatus.Status, Is.EqualTo(PayloadStatus.Valid), $"block {payload.BlockHash} must become the head (error: {head.Result.Error ?? "none"})"); @@ -2462,17 +1739,17 @@ public virtual async Task Eip8360_tcreate_block_validates_on_another_node_and_fr Hash256 head = producer.BlockTree.HeadHash; Task improved = producer.WaitForImprovedBlock(head, minTransactions: txs.Length); - ResultWrapper fcu = await producer.EngineRpcModule.engine_forkchoiceUpdatedV5( + ResultWrapper fcu = await producer.EngineRpcModule.engine_forkchoiceUpdatedV5( new ForkchoiceStateV1(head, Keccak.Zero, head), BuildBogotaPayloadAttributes(inclusionList: [])); Assert.That(fcu.Result.ResultType, Is.EqualTo(ResultType.Success), fcu.Result.Error); await improved; - ResultWrapper payload = await producer.EngineRpcModule.engine_getPayloadV6(Bytes.FromHexString(fcu.Data.PayloadId!)); + ResultWrapper payload = await producer.EngineRpcModule.engine_getPayloadV7(Bytes.FromHexString(fcu.Data.PayloadId!)); ExecutionPayloadV4 executionPayload = payload.Data!.ExecutionPayload; Assert.That(executionPayload.Transactions, Has.Length.EqualTo(txs.Length)); BlockHeader parent = validator.BlockTree.Head!.Header; ResultWrapper result = await validator.EngineRpcModule.engine_newPayloadWithWitnessV6( - executionPayload, [], Keccak.Zero, payload.Data.ExecutionRequests, []); + executionPayload, [], Keccak.Zero, payload.Data.ExecutionRequests, AtPositions(), []); Assert.That(result.Data.Status, Is.EqualTo(PayloadStatus.Valid), result.Data.ValidationError); Block suggested = executionPayload.TryGetBlock().Data!; @@ -2501,7 +1778,38 @@ await validator.EngineRpcModule.engine_forkchoiceUpdatedV5( } } - private PayloadAttributes BuildBogotaPayloadAttributes(byte[][] inclusionList, ulong targetGasLimit = 30_000_000UL, ulong? timestamp = null, ulong slotNumber = 1) => new() + /// Builds an empty Bogota payload on without sending it back. + private async Task BuildEmptyPayload(IEngineRpcModule rpc, Hash256 parent) => + (await BuildBogotaPayload(rpc, parent, BuildBogotaPayloadAttributes(inclusionList: []))).Data!.ExecutionPayload; + + private static async Task> BuildBogotaPayload(IEngineRpcModule rpc, Hash256 parent, PayloadAttributes attributes, + Hash256? finalizedHash = null) + { + ResultWrapper fcu = await rpc.engine_forkchoiceUpdatedV5( + new ForkchoiceStateV1(parent, Keccak.Zero, finalizedHash ?? parent), attributes); + Assert.That(fcu.Data?.PayloadId, Is.Not.Null, fcu.Result.Error); + return await rpc.engine_getPayloadV7(Bytes.FromHexString(fcu.Data!.PayloadId!)); + } + + /// Sends with packed into committee positions. + private static Task> NewPayloadV6(IEngineRpcModule rpc, ExecutionPayloadV4 payload, byte[][]? executionRequests, + byte[][] inclusionList, OmissionClaim[]? claims = null) => + rpc.engine_newPayloadV6(payload, [], Keccak.Zero, executionRequests, Pack(inclusionList), claims ?? []); + + /// Runs the deferred inclusion check on directly, its access list read from the + /// store unless is given. + private static Task Recheck(MergeTestBlockchain chain, ExecutionPayloadV4 payload, byte[][] inclusionList, ReadOnlyBlockAccessList? carried = null) + { + Block block = payload.TryGetBlock().Data!; + block.BlockAccessList = carried; + return chain.Container.Resolve() + .EvaluateAsync(block, InclusionListDecoder.DecodeLists(Pack(inclusionList)), [], CancellationToken.None); + } + + private PayloadAttributes BuildBogotaPayloadAttributes(byte[][] inclusionList, ulong targetGasLimit = 30_000_000UL, ulong? timestamp = null, ulong slotNumber = 1) => + BuildBogotaPayloadAttributes(Pack(inclusionList), targetGasLimit, timestamp, slotNumber); + + private PayloadAttributes BuildBogotaPayloadAttributes(byte[][][]? inclusionLists, ulong targetGasLimit = 30_000_000UL, ulong? timestamp = null, ulong slotNumber = 1) => new() { Timestamp = timestamp ?? Timestamper.UnixTime.Seconds, PrevRandao = Keccak.Zero, @@ -2511,6 +1819,33 @@ await validator.EngineRpcModule.engine_forkchoiceUpdatedV5( SlotNumber = slotNumber, // V4 attributes require TargetGasLimit. TargetGasLimit = targetGasLimit, - InclusionListTransactions = inclusionList, + InclusionLists = inclusionLists, }; + + /// One list per committee position: packed in order, each position filled + /// up to MAX_TRANSACTIONS_BYTES_PER_INCLUSION_LIST before the next. + [return: NotNullIfNotNull(nameof(inclusionList))] + private static byte[][][]? Pack(byte[][]? inclusionList) + { + if (inclusionList is null) return null; + + List[] positions = [.. Enumerable.Range(0, Eip7805Constants.InclusionListCommitteeSize).Select(static _ => new List())]; + int position = 0; + long bytes = 0; + foreach (byte[] transaction in inclusionList) + { + if (bytes + transaction.Length > Eip7805Constants.MaxBytesPerInclusionList && position < positions.Length - 1) + { + position++; + bytes = 0; + } + bytes += transaction.Length; + positions[position].Add(transaction); + } + return [.. positions.Select(static list => list.ToArray())]; + } + + /// One list per committee position: from position 0, the rest empty. + private static byte[][][] AtPositions(params byte[][][] inclusionLists) => + [.. inclusionLists, .. Enumerable.Repeat([], Eip7805Constants.InclusionListCommitteeSize - inclusionLists.Length)]; } diff --git a/src/Nethermind/Nethermind.Merge.Plugin.Test/GetInclusionListTransactionsHandlerTests.cs b/src/Nethermind/Nethermind.Merge.Plugin.Test/GetInclusionListTransactionsHandlerTests.cs index 713f7ef3ba3f..e170e47ab3b8 100644 --- a/src/Nethermind/Nethermind.Merge.Plugin.Test/GetInclusionListTransactionsHandlerTests.cs +++ b/src/Nethermind/Nethermind.Merge.Plugin.Test/GetInclusionListTransactionsHandlerTests.cs @@ -3,6 +3,7 @@ using System.Collections.Generic; using Nethermind.Blockchain; +using Nethermind.Config; using Nethermind.Core; using Nethermind.Core.Specs; using Nethermind.Evm.State; @@ -36,7 +37,7 @@ private static GetInclusionListTransactionsHandler BuildHandler(bool focilSchedu IChainHeadInfoProvider chainHeadInfo = Substitute.For(); chainHeadInfo.ReadOnlyStateProvider.Returns(Substitute.For()); - return new GetInclusionListTransactionsHandler(pool, Substitute.For(), specProvider, chainHeadInfo); + return new GetInclusionListTransactionsHandler(pool, Substitute.For(), specProvider, chainHeadInfo, new BlocksConfig()); } // The list is built before its block exists and a missed slot moves the timestamp, so only whether diff --git a/src/Nethermind/Nethermind.Merge.Plugin.Test/InclusionChecksTests.cs b/src/Nethermind/Nethermind.Merge.Plugin.Test/InclusionChecksTests.cs new file mode 100644 index 000000000000..dc239db605fe --- /dev/null +++ b/src/Nethermind/Nethermind.Merge.Plugin.Test/InclusionChecksTests.cs @@ -0,0 +1,61 @@ +// SPDX-FileCopyrightText: 2026 Demerzel Solutions Limited +// SPDX-License-Identifier: LGPL-3.0-only + +using System; +using System.Linq; +using System.Threading; +using System.Threading.Tasks; +using Nethermind.Core; +using Nethermind.Core.Test.Builders; +using Nethermind.Logging; +using Nethermind.Merge.Plugin.Data; +using Nethermind.Merge.Plugin.Handlers; +using Nethermind.Serialization.Rlp; +using NSubstitute; +using NUnit.Framework; + +namespace Nethermind.Merge.Plugin.Test; + +/// bogota.md § Inclusion checking: the check completes before newPayload answers, and missing local data +/// never yields a verdict. +public class InclusionChecksTests +{ + [TestCase(true)] + [TestCase(false)] + [TestCase(null)] + public async Task Check_returns_the_evaluator_verdict(bool? expected) + { + IInclusionListComplianceEvaluator evaluator = Substitute.For(); + evaluator.EvaluateAsync(Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any()).Returns(expected); + InclusionChecks checks = new(evaluator, LimboLogs.Instance); + + Assert.That(await checks.CheckAsync(Payload(), Lists(), [], CancellationToken.None), Is.EqualTo(expected)); + } + + [Test] + public async Task Empty_lists_without_claims_are_satisfied_without_evaluation() + { + IInclusionListComplianceEvaluator evaluator = Substitute.For(); + InclusionChecks checks = new(evaluator, LimboLogs.Instance); + + Assert.That(await checks.CheckAsync(Payload(), [.. Enumerable.Repeat([], Eip7805Constants.InclusionListCommitteeSize)], [], CancellationToken.None), Is.True); + await evaluator.DidNotReceiveWithAnyArgs().EvaluateAsync(default!, default!, default!, default); + } + + [Test] + public async Task Failed_evaluation_is_undecided() + { + IInclusionListComplianceEvaluator evaluator = Substitute.For(); + evaluator.EvaluateAsync(Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any()) + .Returns(Task.FromException(new InvalidOperationException())); + InclusionChecks checks = new(evaluator, LimboLogs.Instance); + + Assert.That(await checks.CheckAsync(Payload(), Lists(), [], CancellationToken.None), Is.Null); + } + + private static ExecutionPayload Payload() => ExecutionPayload.Create(Build.A.Block.WithNumber(1).TestObject); + + private static byte[][][] Lists() => + [[TxDecoder.Instance.Encode(Build.A.Transaction.SignedAndResolved().TestObject, RlpBehaviors.SkipTypedWrapping)], + .. Enumerable.Repeat([], Eip7805Constants.InclusionListCommitteeSize - 1)]; +} diff --git a/src/Nethermind/Nethermind.Merge.Plugin.Test/InclusionListBuilderTests.cs b/src/Nethermind/Nethermind.Merge.Plugin.Test/InclusionListBuilderTests.cs index a4f38b2ea436..787e67ce5004 100644 --- a/src/Nethermind/Nethermind.Merge.Plugin.Test/InclusionListBuilderTests.cs +++ b/src/Nethermind/Nethermind.Merge.Plugin.Test/InclusionListBuilderTests.cs @@ -41,17 +41,23 @@ private static Transaction TxOfSize(int payloadBytes, int nonce = 0, PrivateKey? } // Frontier leaves the parent's base fee unchanged, so the head header fixes the fee the builder asks for. - private static InclusionListBuilder BuildBuilder(ITxPool pool, UInt256 baseFee = default, (Address Sender, ulong Nonce)[]? accountNonces = null) + private static InclusionListBuilder BuildBuilder(ITxPool pool, UInt256 baseFee = default, (Address Sender, ulong Nonce)[]? accountNonces = null, IReleaseSpec? spec = null) { IBlockTree blockTree = Substitute.For(); - blockTree.Head.Returns(Build.A.Block.WithBaseFeePerGas(baseFee).TestObject); + blockTree.Head.Returns(Build.A.Block.WithBaseFeePerGas(baseFee).WithTimestamp(HeadTimestamp).TestObject); ISpecProvider specProvider = Substitute.For(); - specProvider.GetSpec(Arg.Any()).Returns(Frontier.Instance); + specProvider.GetSpec(Arg.Any()).Returns(spec ?? Frontier.Instance); IReadOnlyStateProvider headState = Substitute.For(); foreach ((Address sender, ulong nonce) in accountNonces ?? []) headState.GetNonce(sender).Returns(nonce); return new InclusionListBuilder(pool, blockTree, specProvider, headState); } + private const ulong HeadTimestamp = 1_000; + + /// A Profile 2 spec: inclusion lists, frame transactions, keyed nonces and recent roots, with a base fee + /// the head leaves unchanged when it sits at its target. + private static readonly IReleaseSpec Profile2Spec = Eip8369Prototype.Instance; + /// A pool whose ready buckets are the given transactions, grouped by sender and nonce-ordered. private static ITxPool PoolOf(params Transaction[] readyTxs) => PoolOf(null, readyTxs); @@ -65,6 +71,7 @@ private static ITxPool PoolOf(Address[]? emptyBucketSenders, params Transaction[ foreach (Address sender in emptyBucketSenders ?? []) bySender[new AddressAsKey(sender)] = []; ITxPool pool = Substitute.For(); pool.GetPendingTransactionsBySenderWithReadyNonFrameTx(Arg.Any()).Returns(bySender); + pool.GetPendingTransactions().Returns(readyTxs); return pool; } @@ -339,20 +346,98 @@ public void Measure_worst_case_inclusion_list_cost() TestContext.Out.WriteLine($"per_request_state_reads={(double)reads / iterations:F1}"); } - private static Transaction FrameTx(Address sender, ulong nonce, UInt256[]? nonceKeys = null) => new() + private static Transaction FrameTx(Address sender, ulong nonce, UInt256[]? nonceKeys = null, TxFrame[]? frames = null, UInt256? maxFeePerGas = null) => new() { Type = TxType.FrameTx, ChainId = TestBlockchainIds.ChainId, SenderAddress = sender, Nonce = nonce, NonceKeys = nonceKeys, - Frames = [new TxFrame(FrameMode.Verify, FrameFlags.ApproveExecutionAndPayment, target: null, gasLimit: 100_000, UInt256.Zero, default)], + Frames = frames ?? [SelfVerify(100_000)], FrameSignatures = [], GasLimit = 100_000, GasPrice = 1, - DecodedMaxFeePerGas = 10, + DecodedMaxFeePerGas = maxFeePerGas ?? 10, }; + private static TxFrame SelfVerify(ulong gasLimit) => + new(FrameMode.Verify, FrameFlags.ApproveExecutionAndPayment, target: null, gasLimit, UInt256.Zero, default); + + private static TxFrame Expiry(ulong deadline) + { + byte[] data = new byte[Eip8141Constants.ExpiryDataLength]; + BinaryPrimitives.WriteUInt64BigEndian(data, deadline); + return new TxFrame(FrameMode.Verify, FrameFlags.None, Eip8141Constants.ExpiryVerifierAddress, 10_000, UInt256.Zero, data); + } + + /// EIP-7805 § IL Building: once Profile 2 is active a ready Profile 2 candidate is worth listing, since its + /// omission is no longer excused; before, it only spends the byte cap. + [Test] + public void Lists_a_ready_profile_2_candidate_once_profile_2_is_active([Values] bool profile2Active) + { + Transaction ordinary = TxOfSize(50, 0, TestItem.PrivateKeyA); + Transaction candidate = FrameTx(TestItem.AddressB, nonce: 3); + + using InclusionListBytes il = BuildBuilder(PoolOf(ordinary, candidate), accountNonces: [(TestItem.AddressB, 3)], + spec: profile2Active ? Profile2Spec : Frontier.Instance).GetInclusionList(); + + Assert.That(il.Select(b => Decode(b).Type), profile2Active + ? Is.EquivalentTo(new[] { TxType.Legacy, TxType.FrameTx }) + : Is.EqualTo(new[] { TxType.Legacy })); + } + + private static IEnumerable FrameTransactionsLeftOut() + { + yield return new TestCaseData(FrameTx(TestItem.AddressB, nonce: 2)).SetName("Leaves_out_a_candidate_not_at_the_account_nonce"); + yield return new TestCaseData(FrameTx(TestItem.AddressB, nonce: 3, frames: [new TxFrame(FrameMode.Default, FrameFlags.None, TestItem.AddressC, 50_000, UInt256.Zero, default)])) + .SetName("Leaves_out_a_frame_transaction_with_no_profile_2_prefix"); + yield return new TestCaseData(FrameTx(TestItem.AddressB, nonce: 3, frames: [SelfVerify(Eip8369Constants.MaxVerifyGasPerTx + 1)])) + .SetName("Leaves_out_a_frame_transaction_over_MAX_VERIFY_GAS_PER_TX"); + yield return new TestCaseData(FrameTx(TestItem.AddressB, nonce: 3, maxFeePerGas: 4)).SetName("Leaves_out_a_candidate_below_the_next_base_fee"); + yield return new TestCaseData(FrameTx(TestItem.AddressB, nonce: 3, frames: [Expiry(HeadTimestamp), SelfVerify(100_000)])) + .SetName("Leaves_out_a_candidate_expired_by_the_parent"); + } + + [TestCaseSource(nameof(FrameTransactionsLeftOut))] + public void Leaves_out_a_frame_transaction_that_could_not_be_enforced(Transaction frameTx) + { + using InclusionListBytes il = BuildBuilder(PoolOf(frameTx), baseFee: 5, accountNonces: [(TestItem.AddressB, 3)], spec: Profile2Spec).GetInclusionList(); + + Assert.That(il, Is.Empty); + } + + [Test] + public void Lists_a_candidate_whose_expiry_is_after_the_parent() + { + Transaction candidate = FrameTx(TestItem.AddressB, nonce: 3, frames: [Expiry(HeadTimestamp + 1), SelfVerify(100_000)]); + + using InclusionListBytes il = BuildBuilder(PoolOf(candidate), accountNonces: [(TestItem.AddressB, 3)], spec: Profile2Spec).GetInclusionList(); + + Assert.That(il.Count, Is.EqualTo(1)); + } + + /// EIP-7805 § IL Building: the listed candidates' total VERIFY cost stays within MAX_VERIFY_GAS_PER_IL, so + /// the per-IL fill admits every one of them whatever its order, while ordinary transactions still fill the bytes. + [Test] + public void Keeps_listed_candidates_within_the_per_il_verify_budget() + { + const ulong verifyGas = 200_000; + Transaction[] candidates = [.. Enumerable.Range(0, 20).Select(i => FrameTx(SenderAt(i), nonce: 0, frames: [SelfVerify(verifyGas)]))]; + Transaction[] ordinary = [.. Enumerable.Range(0, 10).Select(i => TxOfSize(50, 0, TestItem.PrivateKeys[i]))]; + + using InclusionListBytes il = BuildBuilder(PoolOf([.. candidates, .. ordinary]), spec: Profile2Spec).GetInclusionList(); + Transaction[] listed = [.. il.Select(Decode)]; + ulong verifyCost = listed.Where(tx => tx.SupportsFrames).Aggregate(0UL, (sum, tx) => sum + Eip8369Profile2.VerifyBudgetCost(tx)); + + using (Assert.EnterMultipleScope()) + { + Assert.That(listed.Count(tx => tx.SupportsFrames), Is.EqualTo((int)(Eip8369Constants.MaxVerifyGasPerIl / verifyGas))); + Assert.That(verifyCost, Is.LessThanOrEqualTo(Eip8369Constants.MaxVerifyGasPerIl)); + Assert.That(listed.Count(tx => !tx.SupportsFrames), Is.EqualTo(ordinary.Length)); + Assert.That(il.Sum(t => t.Count), Is.LessThanOrEqualTo(Eip7805Constants.MaxBytesPerInclusionList)); + } + } + // A later nonce only becomes appendable once the block includes the earlier one, so a gap ends the run. [Test] public void Stops_a_sender_run_at_a_nonce_gap() diff --git a/src/Nethermind/Nethermind.Merge.Plugin.Test/NewPayloadHandlerRaceConditionTests.cs b/src/Nethermind/Nethermind.Merge.Plugin.Test/NewPayloadHandlerRaceConditionTests.cs index 81e570af2a4b..0eb385e9c8eb 100644 --- a/src/Nethermind/Nethermind.Merge.Plugin.Test/NewPayloadHandlerRaceConditionTests.cs +++ b/src/Nethermind/Nethermind.Merge.Plugin.Test/NewPayloadHandlerRaceConditionTests.cs @@ -2,9 +2,7 @@ // SPDX-License-Identifier: LGPL-3.0-only using System; -using System.Collections; using System.Collections.Generic; -using System.Linq; using System.Reflection; using System.Threading; using System.Threading.Tasks; @@ -29,7 +27,6 @@ using Nethermind.Merge.Plugin.Handlers; using Nethermind.Merge.Plugin.InvalidChainTracker; using Nethermind.Merge.Plugin.Synchronization; -using Nethermind.Serialization.Rlp; using Nethermind.State; using Nethermind.Synchronization; using NSubstitute; @@ -60,18 +57,7 @@ public override Result TryGetBlock(UInt256? totalDifficulty = null) private static readonly FieldInfo? BlockValidationTasksField = typeof(NewPayloadHandler).GetField("_blockValidationTasks", BindingFlags.Instance | BindingFlags.NonPublic); - private static readonly FieldInfo? QueuedCopiesField = - typeof(NewPayloadHandler).GetField("_queuedCopies", BindingFlags.Instance | BindingFlags.NonPublic); - - private static readonly FieldInfo? TimeoutField = - typeof(NewPayloadHandler).GetField("_timeout", BindingFlags.Instance | BindingFlags.NonPublic); - - // The long budget outlasts the answer wait, so a runner stall cannot turn the answer into Syncing, - // and a handler that waits for the wrong event is still pending when the wait gives up. private const int LongRequestBudgetMs = 60_000; - // Only the request that is meant to give up gets this budget. The handler reads `_timeout` once per request, so - // the tests switch it around that request, and a stalled runner cannot answer the other requests SYNCING. - private const int TimedOutRequestBudgetMs = 3_000; private static readonly TimeSpan AnswerWait = TimeSpan.FromSeconds(30); [Test] @@ -895,546 +881,6 @@ public async Task ValidateBlockAndProcess_does_not_take_the_first_copy_removal_f await processingQueue.Received(1).Enqueue(Arg.Any(), Arg.Any()); } - /// - /// The first copy is marked processed part way through its removal, so a re-submission can find the flag set while - /// the copy is still in flight. Its removal must not answer the re-submission - here one with an inclusion list of - /// its own - the request waits for the copy to be gone and then judges its own list. - /// - [Test] - public async Task ValidateBlockAndProcess_waits_for_a_processed_first_copy_still_in_flight_before_judging_a_new_inclusion_list() - { - Block block = PostMergeBlock(); - - TaskCompletionSource waitRequested = new(TaskCreationOptions.RunContinuationsAsynchronously); - TaskCompletionSource firstCopyRemoved = new(TaskCreationOptions.RunContinuationsAsynchronously); - TaskCompletionSource enqueued = new(TaskCreationOptions.RunContinuationsAsynchronously); - IBlockProcessingQueue processingQueue = Substitute.For(); - processingQueue.WaitUntilRemovedAsync(block.Hash!, false).Returns(_ => - { - waitRequested.TrySetResult(); - return new ValueTask(firstCopyRemoved.Task); - }); - processingQueue - .Enqueue(Arg.Any(), Arg.Any()) - .Returns(_ => - { - enqueued.TrySetResult(); - return ValueTask.CompletedTask; - }); - - using NewPayloadHandler handler = CreateHandler( - block, - suggestBlockResult: AddBlockResult.AlreadyKnown, - wasProcessed: true, - validateSuggestedBlock: true, - processingQueue: processingQueue, - timeoutMs: LongRequestBudgetMs); - - ExecutionPayloadV3 payload = ExecutionPayloadV3.Create(block); - payload.InclusionListTransactions = [Rlp.Encode(Build.A.Transaction.SignedAndResolved(TestItem.PrivateKeyB).TestObject)]; - Task> request = handler.HandleAsync(payload); - // Awaited first, so the assertion below means the request is on the wait, not at an earlier await. - await waitRequested.Task.WaitAsync(TimeSpan.FromSeconds(10)); - - processingQueue.BlockRemoved += Raise.EventWith(new BlockRemovedEventArgs(block.Hash!, ProcessingResult.Success)); - Assert.That(request.IsCompleted, Is.False, "the first copy's removal is not this request's answer"); - firstCopyRemoved.SetResult(); - - await enqueued.Task.WaitAsync(TimeSpan.FromSeconds(10)); - processingQueue.BlockExecuted += Raise.EventWith(new BlockVerdictEventArgs(block.Hash!, ProcessingResult.InclusionListUnsatisfied)); - ResultWrapper result = await request.WaitAsync(AnswerWait); - - Assert.That(result.Data.Status, Is.EqualTo(PayloadStatus.InclusionListUnsatisfied), "the answer judges this request's own inclusion list"); - } - - /// - /// A copy is handed to the queue off the request's thread, so there is a moment when the queue does not have it - /// yet. A re-submission with another inclusion list must not queue its own copy in that gap: the earlier copy - /// would then run first and its verdict would answer the re-submission. - /// - [Test, MaxTime(30_000)] - public async Task ValidateBlockAndProcess_waits_for_a_copy_with_another_inclusion_list_that_the_queue_has_not_taken_yet() - { - Block block = PostMergeBlock(); - - TaskCompletionSource firstEnqueueEntered = new(TaskCreationOptions.RunContinuationsAsynchronously); - TaskCompletionSource firstEnqueueReleased = new(TaskCreationOptions.RunContinuationsAsynchronously); - TaskCompletionSource secondEnqueueEntered = new(TaskCreationOptions.RunContinuationsAsynchronously); - int enqueues = 0; - IBlockProcessingQueue processingQueue = Substitute.For(); - processingQueue - .Enqueue(Arg.Any(), Arg.Any()) - .Returns(_ => - { - if (Interlocked.Increment(ref enqueues) == 1) - { - firstEnqueueEntered.TrySetResult(); - firstEnqueueReleased.Task.Wait(TimeSpan.FromSeconds(10)); - } - else - { - secondEnqueueEntered.TrySetResult(); - } - - return ValueTask.CompletedTask; - }); - - using NewPayloadHandler handler = CreateHandler( - block, - suggestBlockResult: AddBlockResult.AlreadyKnown, - wasProcessed: true, - validateSuggestedBlock: true, - processingQueue: processingQueue, - timeoutMs: 20_000); - - ExecutionPayloadV3 firstPayload = ExecutionPayloadV3.Create(block); - firstPayload.InclusionListTransactions = [Rlp.Encode(Build.A.Transaction.SignedAndResolved(TestItem.PrivateKeyB).TestObject)]; - ExecutionPayloadV3 resentPayload = ExecutionPayloadV3.Create(block); - resentPayload.InclusionListTransactions = [Rlp.Encode(Build.A.Transaction.SignedAndResolved(TestItem.PrivateKeyC).TestObject)]; - - Task> first = handler.HandleAsync(firstPayload); - await firstEnqueueEntered.Task.WaitAsync(TimeSpan.FromSeconds(10)); - Task> resent = handler.HandleAsync(resentPayload); - - try - { - Task earlierCopyWait = WaitForEarlierCopies(handler, block.Hash!); - using (Assert.EnterMultipleScope()) - { - Assert.That(earlierCopyWait.IsCompleted, Is.False, "a different-list wait must remain pending until the held copy leaves"); - Assert.That(WaitForEarlierCopies(handler, TestItem.KeccakD).IsCompleted, Is.True, "a held copy of one block must not hold back a request for another"); - } - } - finally - { - firstEnqueueReleased.TrySetResult(); - } - - await secondEnqueueEntered.Task.WaitAsync(TimeSpan.FromSeconds(10)); - processingQueue.BlockExecuted += Raise.EventWith(new BlockVerdictEventArgs(block.Hash!, ProcessingResult.InclusionListUnsatisfied)); - ResultWrapper result = await resent.WaitAsync(TimeSpan.FromSeconds(10)); - await first.WaitAsync(TimeSpan.FromSeconds(10)); - - Assert.That(result.Data.Status, Is.EqualTo(PayloadStatus.InclusionListUnsatisfied), "the answer judges this request's own inclusion list"); - } - - [Test] - public async Task ValidateBlockAndProcess_does_not_take_a_copy_that_has_left_the_queue_for_one_carrying_the_same_inclusion_list() - { - Block block = PostMergeBlock(); - - TaskCompletionSource enqueued = new(TaskCreationOptions.RunContinuationsAsynchronously); - IBlockProcessingQueue processingQueue = Substitute.For(); - processingQueue - .Enqueue(Arg.Any(), Arg.Any()) - .Returns(_ => - { - enqueued.TrySetResult(); - return ValueTask.CompletedTask; - }); - - using NewPayloadHandler handler = CreateHandler( - block, - suggestBlockResult: AddBlockResult.Added, - wasProcessed: false, - validateSuggestedBlock: true, - processingQueue: processingQueue, - timeoutMs: LongRequestBudgetMs); - - ExecutionPayloadV3 payload = ExecutionPayloadV3.Create(block); - payload.InclusionListTransactions = [Rlp.Encode(Build.A.Transaction.SignedAndResolved(TestItem.PrivateKeyB).TestObject)]; - - Task> request = handler.HandleAsync(payload); - await enqueued.Task.WaitAsync(TimeSpan.FromSeconds(10)); - processingQueue.BlockExecuted += Raise.EventWith(new BlockVerdictEventArgs(block.Hash!, ProcessingResult.Success)); - await request.WaitAsync(AnswerWait); - - object copy = ((IList)QueuedCopiesField!.GetValue(handler)!)[0]!; - await ((Task)copy.GetType().GetProperty("Left")!.GetValue(copy)!).WaitAsync(TimeSpan.FromSeconds(10)); - ValueHash256 sameList = (ValueHash256)copy.GetType().GetProperty("InclusionListDigest")!.GetValue(copy)!; - processingQueue.ClearReceivedCalls(); - - await WaitForEarlierCopies(handler, block.Hash!, sameList).WaitAsync(TimeSpan.FromSeconds(10)); - - await processingQueue.Received(1).WaitUntilRemovedAsync(block.Hash!, false); - } - - /// - /// A request that timed out leaves its copy on the way to the queue, and a retry with the same list queues a - /// second copy that is answered and gone while the first is still held. A re-submission with another inclusion - /// list must go on waiting for the held copy, which would otherwise run first and answer it. - /// - /// - /// No wall-clock limit: only the first request needs a short budget, and the later ones get a long one so a - /// stalled runner cannot answer them SYNCING before their verdicts land. The budget is raised through - /// `_timeout`, which the handler reads once per request. - /// - [Test] - public async Task ValidateBlockAndProcess_waits_for_a_held_copy_with_another_inclusion_list_after_a_same_list_retry_has_finished() - { - Block block = PostMergeBlock(); - - TaskCompletionSource firstEnqueueEntered = new(TaskCreationOptions.RunContinuationsAsynchronously); - TaskCompletionSource firstEnqueueReleased = new(TaskCreationOptions.RunContinuationsAsynchronously); - TaskCompletionSource retryEnqueued = new(TaskCreationOptions.RunContinuationsAsynchronously); - TaskCompletionSource retryEnqueueReleased = new(TaskCreationOptions.RunContinuationsAsynchronously); - TaskCompletionSource resentEnqueued = new(TaskCreationOptions.RunContinuationsAsynchronously); - int enqueues = 0; - IBlockProcessingQueue processingQueue = Substitute.For(); - processingQueue - .Enqueue(Arg.Any(), Arg.Any()) - .Returns(_ => - { - switch (Interlocked.Increment(ref enqueues)) - { - case 1: - firstEnqueueEntered.TrySetResult(); - firstEnqueueReleased.Task.Wait(LongRequestBudgetMs); - break; - case 2: - retryEnqueued.TrySetResult(); - retryEnqueueReleased.Task.Wait(LongRequestBudgetMs); - break; - default: - resentEnqueued.TrySetResult(); - break; - } - - return ValueTask.CompletedTask; - }); - - using NewPayloadHandler handler = CreateHandler( - block, - suggestBlockResult: AddBlockResult.AlreadyKnown, - wasProcessed: true, - validateSuggestedBlock: true, - processingQueue: processingQueue, - timeoutMs: TimedOutRequestBudgetMs); - - ExecutionPayloadV3 heldPayload = ExecutionPayloadV3.Create(block); - heldPayload.InclusionListTransactions = [Rlp.Encode(Build.A.Transaction.SignedAndResolved(TestItem.PrivateKeyB).TestObject)]; - ExecutionPayloadV3 retryPayload = ExecutionPayloadV3.Create(block); - retryPayload.InclusionListTransactions = heldPayload.InclusionListTransactions; - ExecutionPayloadV3 resentPayload = ExecutionPayloadV3.Create(block); - resentPayload.InclusionListTransactions = [Rlp.Encode(Build.A.Transaction.SignedAndResolved(TestItem.PrivateKeyC).TestObject)]; - - Task> resent; - try - { - Task> held = handler.HandleAsync(heldPayload); - await firstEnqueueEntered.Task.WaitAsync(TimeSpan.FromSeconds(10)); - Assert.That((await held.WaitAsync(AnswerWait)).Data.Status, Is.EqualTo(PayloadStatus.Syncing), "the first request gives up while its copy is still on the way to the queue"); - TimeoutField!.SetValue(handler, TimeSpan.FromMilliseconds(LongRequestBudgetMs)); - - Task> retry = handler.HandleAsync(retryPayload); - await retryEnqueued.Task.WaitAsync(TimeSpan.FromSeconds(10)); - Task bothCopiesWait = WaitForEarlierCopies(handler, block.Hash!); - retryEnqueueReleased.SetResult(); - processingQueue.BlockExecuted += Raise.EventWith(new BlockVerdictEventArgs(block.Hash!, ProcessingResult.Success)); - Assert.That((await retry.WaitAsync(AnswerWait)).Data.Status, Is.EqualTo(PayloadStatus.Valid)); - Assert.That(() => GetQueuedCopies(handler, block.Hash!).Length, Is.EqualTo(1).After(10_000, 10), "the retry's copy has left the queue and the held copy has not"); - Assert.That(bothCopiesWait.IsCompleted, Is.False, "a wait started while both copies were outstanding must outlast the retry's copy"); - - resent = handler.HandleAsync(resentPayload); - - Task earlierCopyWait = WaitForEarlierCopies(handler, block.Hash!); - Assert.That(earlierCopyWait.IsCompleted, Is.False, "a different-list wait must remain pending until the held copy leaves"); - - processingQueue.BlockExecuted += Raise.EventWith(new BlockVerdictEventArgs(block.Hash!, ProcessingResult.Success)); - } - finally - { - retryEnqueueReleased.TrySetResult(); - firstEnqueueReleased.TrySetResult(); - } - - await resentEnqueued.Task.WaitAsync(TimeSpan.FromSeconds(10)); - processingQueue.BlockExecuted += Raise.EventWith(new BlockVerdictEventArgs(block.Hash!, ProcessingResult.InclusionListUnsatisfied)); - ResultWrapper result = await resent.WaitAsync(AnswerWait); - - Assert.That(result.Data.Status, Is.EqualTo(PayloadStatus.InclusionListUnsatisfied), "the answer judges this request's own inclusion list"); - } - - [Test] - public async Task ValidateBlockAndProcess_waits_for_a_copy_with_another_inclusion_list_whose_request_timed_out_in_suggest() - { - Block block = PostMergeBlock(); - - TaskCompletionSource timedOutSuggest = new(TaskCreationOptions.RunContinuationsAsynchronously); - TaskCompletionSource resentSuggest = new(TaskCreationOptions.RunContinuationsAsynchronously); - TaskCompletionSource firstEnqueued = new(TaskCreationOptions.RunContinuationsAsynchronously); - TaskCompletionSource secondEnqueued = new(TaskCreationOptions.RunContinuationsAsynchronously); - TaskCompletionSource resentReachedTheWait = new(TaskCreationOptions.RunContinuationsAsynchronously); - int suggests = 0; - IBlockProcessingQueue processingQueue = Substitute.For(); - processingQueue.WaitUntilRemovedAsync(block.Hash!, Arg.Any()).Returns(_ => - { - resentReachedTheWait.TrySetResult(); - return ValueTask.CompletedTask; - }); - processingQueue - .Enqueue(Arg.Any(), Arg.Any()) - .Returns(_ => - { - if (!firstEnqueued.TrySetResult()) secondEnqueued.TrySetResult(); - return ValueTask.CompletedTask; - }); - - using NewPayloadHandler handler = CreateHandler( - block, - suggestBlockResult: AddBlockResult.Added, - wasProcessed: false, - validateSuggestedBlock: true, - processingQueue: processingQueue, - timeoutMs: TimedOutRequestBudgetMs, - configure: (blockTree, _) => blockTree - .SuggestBlockAsync(Arg.Any(), Arg.Any()) - .Returns(_ => new ValueTask((Interlocked.Increment(ref suggests) == 1 ? timedOutSuggest : resentSuggest).Task))); - - ExecutionPayloadV3 timedOutPayload = ExecutionPayloadV3.Create(block); - timedOutPayload.InclusionListTransactions = [Rlp.Encode(Build.A.Transaction.SignedAndResolved(TestItem.PrivateKeyB).TestObject)]; - ExecutionPayloadV3 resentPayload = ExecutionPayloadV3.Create(block); - resentPayload.InclusionListTransactions = [Rlp.Encode(Build.A.Transaction.SignedAndResolved(TestItem.PrivateKeyC).TestObject)]; - - ResultWrapper timedOut = await handler.HandleAsync(timedOutPayload).WaitAsync(AnswerWait); - Assert.That(timedOut.Data.Status, Is.EqualTo(PayloadStatus.Syncing), "the first request gives up while its suggest is still pending"); - TimeoutField!.SetValue(handler, TimeSpan.FromMilliseconds(LongRequestBudgetMs)); - - Task> resent = handler.HandleAsync(resentPayload); - resentSuggest.SetResult(AddBlockResult.AlreadyKnown); - - try - { - await resentReachedTheWait.Task.WaitAsync(TimeSpan.FromSeconds(10)); - Assert.That(WaitForEarlierCopies(handler, block.Hash!).IsCompleted, Is.False, "the re-submission must wait for the copy the timed-out request is still to queue"); - } - finally - { - timedOutSuggest.TrySetResult(AddBlockResult.Added); - } - - await secondEnqueued.Task.WaitAsync(TimeSpan.FromSeconds(10)); - processingQueue.BlockExecuted += Raise.EventWith(new BlockVerdictEventArgs(block.Hash!, ProcessingResult.InclusionListUnsatisfied)); - ResultWrapper result = await resent.WaitAsync(AnswerWait); - - Assert.That(result.Data.Status, Is.EqualTo(PayloadStatus.InclusionListUnsatisfied), "the answer judges this request's own inclusion list"); - } - - [Test] - public async Task ValidateBlockAndProcess_keeps_waiting_for_a_queued_copy_when_a_request_with_another_inclusion_list_times_out_in_suggest() - { - Block block = PostMergeBlock(); - - TaskCompletionSource timedOutSuggest = new(TaskCreationOptions.RunContinuationsAsynchronously); - TaskCompletionSource queuedCopyRemoved = new(TaskCreationOptions.RunContinuationsAsynchronously); - TaskCompletionSource firstEnqueued = new(TaskCreationOptions.RunContinuationsAsynchronously); - TaskCompletionSource secondEnqueued = new(TaskCreationOptions.RunContinuationsAsynchronously); - TaskCompletionSource queuedCopyReachedItsRemovalWait = new(TaskCreationOptions.RunContinuationsAsynchronously); - TaskCompletionSource resentWaitedForExecutedCopiesOnly = new(TaskCreationOptions.RunContinuationsAsynchronously); - int suggests = 0; - int removalWaits = 0; - IBlockProcessingQueue processingQueue = Substitute.For(); - processingQueue.WaitUntilRemovedAsync(block.Hash!, Arg.Any()).Returns(call => - { - bool executedOnly = call.ArgAt(1); - if (Interlocked.Increment(ref removalWaits) == 1) queuedCopyReachedItsRemovalWait.TrySetResult(); - else resentWaitedForExecutedCopiesOnly.TrySetResult(executedOnly); - return executedOnly ? ValueTask.CompletedTask : new ValueTask(queuedCopyRemoved.Task); - }); - processingQueue - .Enqueue(Arg.Any(), Arg.Any()) - .Returns(_ => - { - if (!firstEnqueued.TrySetResult()) secondEnqueued.TrySetResult(); - return ValueTask.CompletedTask; - }); - - using NewPayloadHandler handler = CreateHandler( - block, - suggestBlockResult: AddBlockResult.Added, - wasProcessed: false, - validateSuggestedBlock: true, - processingQueue: processingQueue, - timeoutMs: LongRequestBudgetMs, - configure: (blockTree, _) => blockTree - .SuggestBlockAsync(Arg.Any(), Arg.Any()) - .Returns(_ => Interlocked.Increment(ref suggests) switch - { - 1 => ValueTask.FromResult(AddBlockResult.Added), - 2 => new ValueTask(timedOutSuggest.Task), - _ => ValueTask.FromResult(AddBlockResult.AlreadyKnown) - })); - - ExecutionPayloadV3 queuedPayload = ExecutionPayloadV3.Create(block); - queuedPayload.InclusionListTransactions = [Rlp.Encode(Build.A.Transaction.SignedAndResolved(TestItem.PrivateKeyB).TestObject)]; - ExecutionPayloadV3 timedOutPayload = ExecutionPayloadV3.Create(block); - timedOutPayload.InclusionListTransactions = [Rlp.Encode(Build.A.Transaction.SignedAndResolved(TestItem.PrivateKeyC).TestObject)]; - ExecutionPayloadV3 resentPayload = ExecutionPayloadV3.Create(block); - resentPayload.InclusionListTransactions = timedOutPayload.InclusionListTransactions; - - Task> queuedRequest = handler.HandleAsync(queuedPayload); - await firstEnqueued.Task.WaitAsync(TimeSpan.FromSeconds(10)); - await queuedCopyReachedItsRemovalWait.Task.WaitAsync(TimeSpan.FromSeconds(10)); - processingQueue.BlockExecuted += Raise.EventWith(new BlockVerdictEventArgs(block.Hash!, ProcessingResult.Success)); - Assert.That((await queuedRequest.WaitAsync(AnswerWait)).Data.Status, Is.EqualTo(PayloadStatus.Valid)); - - TimeoutField!.SetValue(handler, TimeSpan.FromMilliseconds(TimedOutRequestBudgetMs)); - ResultWrapper timedOut = await handler.HandleAsync(timedOutPayload).WaitAsync(AnswerWait); - Assert.That(timedOut.Data.Status, Is.EqualTo(PayloadStatus.Syncing), "the second request gives up while its suggest is still pending"); - TimeoutField!.SetValue(handler, TimeSpan.FromMilliseconds(LongRequestBudgetMs)); - - Task> resent = handler.HandleAsync(resentPayload); - - try - { -#pragma warning disable NUnit2045 // The assertions sequence an asynchronous state transition or wait prerequisite with dependent state checks; preserve fail-fast ordering. - Assert.That(await resentWaitedForExecutedCopiesOnly.Task.WaitAsync(TimeSpan.FromSeconds(10)), Is.False, "the re-submission must still wait for the queued copy carrying another list"); -#pragma warning restore NUnit2045 - Assert.That(WaitForEarlierCopies(handler, block.Hash!).IsCompleted, Is.False, "a different-list wait must remain pending until the queued copy leaves"); - } - finally - { - timedOutSuggest.TrySetResult(AddBlockResult.AlreadyKnown); - queuedCopyRemoved.TrySetResult(); - } - - await secondEnqueued.Task.WaitAsync(TimeSpan.FromSeconds(10)); - processingQueue.BlockExecuted += Raise.EventWith(new BlockVerdictEventArgs(block.Hash!, ProcessingResult.InclusionListUnsatisfied)); - ResultWrapper result = await resent.WaitAsync(AnswerWait); - - Assert.That(result.Data.Status, Is.EqualTo(PayloadStatus.InclusionListUnsatisfied), "the answer judges this request's own inclusion list"); - } - - [Test] - public async Task ValidateBlockAndProcess_does_not_share_the_verdict_of_a_sync_copy_queued_while_a_same_list_suggest_is_still_pending() - { - Block block = PostMergeBlock(); - - TaskCompletionSource timedOutSuggest = new(TaskCreationOptions.RunContinuationsAsynchronously); - TaskCompletionSource syncCopyRemoved = new(TaskCreationOptions.RunContinuationsAsynchronously); - TaskCompletionSource enqueued = new(TaskCreationOptions.RunContinuationsAsynchronously); - TaskCompletionSource resentWaitedForExecutedCopiesOnly = new(TaskCreationOptions.RunContinuationsAsynchronously); - int suggests = 0; - IBlockProcessingQueue processingQueue = Substitute.For(); - processingQueue.WaitUntilRemovedAsync(block.Hash!, Arg.Any()).Returns(call => - { - bool executedOnly = call.ArgAt(1); - resentWaitedForExecutedCopiesOnly.TrySetResult(executedOnly); - return executedOnly ? ValueTask.CompletedTask : new ValueTask(syncCopyRemoved.Task); - }); - processingQueue - .Enqueue(Arg.Any(), Arg.Any()) - .Returns(_ => - { - enqueued.TrySetResult(); - return ValueTask.CompletedTask; - }); - - using NewPayloadHandler handler = CreateHandler( - block, - suggestBlockResult: AddBlockResult.AlreadyKnown, - wasProcessed: false, - validateSuggestedBlock: true, - processingQueue: processingQueue, - timeoutMs: TimedOutRequestBudgetMs, - configure: (blockTree, _) => blockTree - .SuggestBlockAsync(Arg.Any(), Arg.Any()) - .Returns(_ => Interlocked.Increment(ref suggests) == 1 - ? new ValueTask(timedOutSuggest.Task) - : ValueTask.FromResult(AddBlockResult.AlreadyKnown))); - - ExecutionPayloadV3 timedOutPayload = ExecutionPayloadV3.Create(block); - timedOutPayload.InclusionListTransactions = [Rlp.Encode(Build.A.Transaction.SignedAndResolved(TestItem.PrivateKeyB).TestObject)]; - ExecutionPayloadV3 resentPayload = ExecutionPayloadV3.Create(block); - resentPayload.InclusionListTransactions = timedOutPayload.InclusionListTransactions; - - ResultWrapper timedOut = await handler.HandleAsync(timedOutPayload).WaitAsync(AnswerWait); - Assert.That(timedOut.Data.Status, Is.EqualTo(PayloadStatus.Syncing), "the first request gives up while its suggest is still pending"); - TimeoutField!.SetValue(handler, TimeSpan.FromMilliseconds(LongRequestBudgetMs)); - - Task> resent = handler.HandleAsync(resentPayload); - - try - { - Assert.That(await resentWaitedForExecutedCopiesOnly.Task.WaitAsync(TimeSpan.FromSeconds(10)), Is.False, "the copy in the queue is sync's and carries no list, so the re-submission must wait for it to leave"); - } - finally - { - timedOutSuggest.TrySetResult(AddBlockResult.AlreadyKnown); - syncCopyRemoved.TrySetResult(); - } - - await enqueued.Task.WaitAsync(TimeSpan.FromSeconds(10)); - processingQueue.BlockExecuted += Raise.EventWith(new BlockVerdictEventArgs(block.Hash!, ProcessingResult.InclusionListUnsatisfied)); - ResultWrapper result = await resent.WaitAsync(AnswerWait); - - Assert.That(result.Data.Status, Is.EqualTo(PayloadStatus.InclusionListUnsatisfied), "the answer judges this request's own inclusion list"); - } - - [Test] - public async Task ValidateBlockAndProcess_keeps_the_entry_of_a_queued_copy_when_a_suggest_that_timed_out_adds_the_block() - { - Block block = PostMergeBlock(); - - TaskCompletionSource timedOutSuggest = new(TaskCreationOptions.RunContinuationsAsynchronously); - TaskCompletionSource queuedCopyRemoved = new(TaskCreationOptions.RunContinuationsAsynchronously); - TaskCompletionSource firstEnqueued = new(TaskCreationOptions.RunContinuationsAsynchronously); - TaskCompletionSource secondEnqueued = new(TaskCreationOptions.RunContinuationsAsynchronously); - int suggests = 0; - IBlockProcessingQueue processingQueue = Substitute.For(); - processingQueue.WaitUntilRemovedAsync(block.Hash!, false).Returns(_ => new ValueTask(queuedCopyRemoved.Task)); - processingQueue - .Enqueue(Arg.Any(), Arg.Any()) - .Returns(_ => - { - if (!firstEnqueued.TrySetResult()) secondEnqueued.TrySetResult(); - return ValueTask.CompletedTask; - }); - - using NewPayloadHandler handler = CreateHandler( - block, - suggestBlockResult: AddBlockResult.Added, - wasProcessed: false, - validateSuggestedBlock: true, - processingQueue: processingQueue, - timeoutMs: LongRequestBudgetMs, - configure: (blockTree, _) => blockTree - .SuggestBlockAsync(Arg.Any(), Arg.Any()) - .Returns(_ => Interlocked.Increment(ref suggests) == 1 - ? ValueTask.FromResult(AddBlockResult.Added) - : new ValueTask(timedOutSuggest.Task))); - - ExecutionPayloadV3 queuedPayload = ExecutionPayloadV3.Create(block); - queuedPayload.InclusionListTransactions = [Rlp.Encode(Build.A.Transaction.SignedAndResolved(TestItem.PrivateKeyB).TestObject)]; - ExecutionPayloadV3 timedOutPayload = ExecutionPayloadV3.Create(block); - timedOutPayload.InclusionListTransactions = [Rlp.Encode(Build.A.Transaction.SignedAndResolved(TestItem.PrivateKeyC).TestObject)]; - - try - { - Task> queuedRequest = handler.HandleAsync(queuedPayload); - await firstEnqueued.Task.WaitAsync(TimeSpan.FromSeconds(10)); - processingQueue.BlockExecuted += Raise.EventWith(new BlockVerdictEventArgs(block.Hash!, ProcessingResult.Success)); - Assert.That((await queuedRequest.WaitAsync(AnswerWait)).Data.Status, Is.EqualTo(PayloadStatus.Valid)); - object[] queuedCopies = GetQueuedCopies(handler, block.Hash!); - Assert.That(queuedCopies, Has.Length.EqualTo(1), "the copy still in the queue keeps its entry"); - object queuedCopy = queuedCopies[0]; - - TimeoutField!.SetValue(handler, TimeSpan.FromMilliseconds(TimedOutRequestBudgetMs)); - ResultWrapper timedOut = await handler.HandleAsync(timedOutPayload).WaitAsync(AnswerWait); - Assert.That(timedOut.Data.Status, Is.EqualTo(PayloadStatus.Syncing), "the second request gives up while its suggest is still pending"); - - timedOutSuggest.SetResult(AddBlockResult.Added); - await secondEnqueued.Task.WaitAsync(TimeSpan.FromSeconds(10)); - - Assert.That(GetQueuedCopies(handler, block.Hash!), Has.Member(queuedCopy), "the copy queued first must keep its entry while it is still queued"); - } - finally - { - timedOutSuggest.TrySetResult(AddBlockResult.AlreadyKnown); - queuedCopyRemoved.TrySetResult(); - } - } - /// /// The verdict is published before the block is committed, so a commit that then fails races the request's own /// cache write. Whichever of the two lands first, the answer must not stay cached: a block that never committed @@ -1605,43 +1051,6 @@ public async Task ValidateBlockAndProcess_gives_up_on_a_known_copy_that_never_fi await processingQueue.DidNotReceive().Enqueue(Arg.Any(), Arg.Any()); } - /// - /// Tracking a copy drops the copies that have left the queue and keeps the others in the order they were queued, - /// with the new copy last. - /// - [Test] - public void TrackQueuedCopy_drops_copies_that_left_and_keeps_order() - { - MethodInfo? trackMethod = typeof(NewPayloadHandler).GetMethod("TrackQueuedCopy", BindingFlags.Instance | BindingFlags.NonPublic); - using (Assert.EnterMultipleScope()) - { - Assert.That(trackMethod, Is.Not.Null, "TrackQueuedCopy method not found - was it renamed?"); - Assert.That(QueuedCopiesField, Is.Not.Null, "_queuedCopies field not found - was it renamed?"); - } - - using NewPayloadHandler handler = CreateHandler(PostMergeBlock(), AddBlockResult.Added, wasProcessed: false, validateSuggestedBlock: true); - Action track = trackMethod!.CreateDelegate>(handler); - IList queuedCopies = (IList)QueuedCopiesField!.GetValue(handler)!; - PropertyInfo blockHashProperty = QueuedCopiesField.FieldType.GetGenericArguments()[0].GetProperty("BlockHash")!; - - TaskCompletionSource first = new(TaskCreationOptions.RunContinuationsAsynchronously); - track(TestItem.KeccakA, null, first.Task); - track(TestItem.KeccakB, null, Task.CompletedTask); - track(TestItem.KeccakC, null, new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously).Task); - track(TestItem.KeccakD, null, new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously).Task); - Hash256[] afterD = [.. queuedCopies.Cast().Select(copy => (Hash256)blockHashProperty.GetValue(copy)!)]; - - first.SetResult(); - track(TestItem.KeccakE, null, new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously).Task); - Hash256[] afterE = [.. queuedCopies.Cast().Select(copy => (Hash256)blockHashProperty.GetValue(copy)!)]; - - using (Assert.EnterMultipleScope()) - { - Assert.That(afterD, Is.EqualTo(new[] { TestItem.KeccakA, TestItem.KeccakC, TestItem.KeccakD }), "the completed copy is dropped, the rest keep their order"); - Assert.That(afterE, Is.EqualTo(new[] { TestItem.KeccakC, TestItem.KeccakD, TestItem.KeccakE }), "a copy that left since the last call is dropped"); - } - } - private static int GetPendingValidationTaskCount(NewPayloadHandler handler) { Assert.That(BlockValidationTasksField, Is.Not.Null, "_blockValidationTasks field not found - was it renamed?"); @@ -1651,23 +1060,6 @@ private static int GetPendingValidationTaskCount(NewPayloadHandler handler) .GetValue(BlockValidationTasksField.GetValue(handler)!)!; } - private static object[] GetQueuedCopies(NewPayloadHandler handler, Hash256 blockHash) - { - Assert.That(QueuedCopiesField, Is.Not.Null, "_queuedCopies field not found - was it renamed?"); - - return [.. ((IList)QueuedCopiesField!.GetValue(handler)!).Cast().Where(copy => - (Hash256)copy.GetType().GetProperty("BlockHash")!.GetValue(copy)! == blockHash - && !((Task)copy.GetType().GetProperty("Left")!.GetValue(copy)!).IsCompleted)]; - } - - private static Task WaitForEarlierCopies(NewPayloadHandler handler, Hash256 blockHash, ValueHash256 inclusionListDigest = default) - { - MethodInfo? waitMethod = typeof(NewPayloadHandler).GetMethod("WaitForEarlierCopiesAsync", BindingFlags.Instance | BindingFlags.NonPublic); - Assert.That(waitMethod, Is.Not.Null, "WaitForEarlierCopiesAsync method not found - was it renamed?"); - - return (Task)waitMethod!.Invoke(handler, [blockHash, inclusionListDigest])!; - } - /// The block every case here drives: post-merge, one past a parent none of them have. private static Block PostMergeBlock() { diff --git a/src/Nethermind/Nethermind.Merge.Plugin.Test/SszRest/SszCodecTests.cs b/src/Nethermind/Nethermind.Merge.Plugin.Test/SszRest/SszCodecTests.cs index 2e4334a45776..b10dedf41197 100644 --- a/src/Nethermind/Nethermind.Merge.Plugin.Test/SszRest/SszCodecTests.cs +++ b/src/Nethermind/Nethermind.Merge.Plugin.Test/SszRest/SszCodecTests.cs @@ -824,6 +824,22 @@ public void EncodeGetPayloadV6Response_all_static_fields_land_at_spec_defined_of AssertPragueBuiltPayloadOffsets(w.WrittenSpan, blockValue, expectedShouldOverrideBuilder: 0, version: "V6"); } + /// getPayloadV7 over SSZ is the V6 container plus the claims, which round-trip intact. + [Test] + public void EncodeGetPayloadV7Response_round_trips_the_claims() + { + ExecutionPayloadV4 ep = SszTestData.MakeV4Payload(blockAccessList: [0xc0], slotNumber: 42UL); + Block block = (Block)ep.TryGetBlock(); + OmissionClaim[] claims = [new(TestItem.KeccakA, 0), new(TestItem.KeccakB, 5)]; + block.OmissionClaims = claims; + + ArrayBufferWriter w = new(); + SszCodec.EncodeGetPayloadV7Response(new GetPayloadV7Result(block, UInt256.One, new BlobsBundleV2(block), executionRequests: [], shouldOverrideBuilder: false), w); + GetPayloadResponseV7Wire.Decode(new ReadOnlySequence(w.WrittenMemory), out GetPayloadResponseV7Wire decoded); + + Assert.That(decoded.OmissionClaims.ToClaims(), Is.EqualTo(claims)); + } + [Test] public void EncodeGetPayloadWithWitnessV6Response_embeds_the_built_payload_encoding() { @@ -1080,7 +1096,7 @@ public void EncodePayloadStatusV2_null_inclusion_list_satisfied_is_empty_list() } [Test] - public void DecodeNewPayload_v6_roundtrip_preserves_inclusion_list_and_v5_fields() + public void DecodeNewPayload_v6_roundtrip_preserves_inclusion_lists_claims_and_v5_fields() { byte[] executionRequest = [0xAA, 0xBB]; byte[] ilTx1 = [0x01, 0x02, 0x03]; @@ -1093,7 +1109,8 @@ public void DecodeNewPayload_v6_roundtrip_preserves_inclusion_list_and_v5_fields ExecutionPayload = new SszExecutionPayloadV4(SszTestData.MakeV4Payload(blockAccessList, slotNumber)), ParentBeaconBlockRoot = TestItem.KeccakD, ExecutionRequests = [new SszTransaction { Bytes = executionRequest }], - InclusionListTransactions = [new SszTransaction { Bytes = ilTx1 }, new SszTransaction { Bytes = ilTx2 }] + InclusionLists = [new SszInclusionList { Transactions = [new SszTransaction { Bytes = ilTx1 }] }, new SszInclusionList(), new SszInclusionList { Transactions = [new SszTransaction { Bytes = ilTx2 }, new SszTransaction { Bytes = ilTx1 }] }], + OmissionClaims = [new OmissionClaimWire { TransactionHash = TestItem.KeccakA, EvaluationIndex = 3 }] }; byte[] encoded = NewPayloadV6RequestWire.Encode(wire); @@ -1101,7 +1118,7 @@ public void DecodeNewPayload_v6_roundtrip_preserves_inclusion_list_and_v5_fields NewPayloadV6RequestWire.Decode(encoded, out NewPayloadV6RequestWire decoded); ExecutionPayloadV4 payload = decoded.ExecutionPayload.AsExecutionPayload(); byte[][]? requests = decoded.ExecutionRequests.ToExecutionRequests(); - byte[][]? inclusionListTxs = decoded.InclusionListTransactions.ToExecutionRequests(); + byte[][][]? inclusionLists = decoded.InclusionLists.ToInclusionLists(); using (Assert.EnterMultipleScope()) { @@ -1110,7 +1127,8 @@ public void DecodeNewPayload_v6_roundtrip_preserves_inclusion_list_and_v5_fields Assert.That(payload.BlockHash, Is.EqualTo(TestItem.KeccakE)); Assert.That(decoded.ParentBeaconBlockRoot, Is.EqualTo(TestItem.KeccakD)); Assert.That(requests, Is.EqualTo(new[] { executionRequest })); - Assert.That(inclusionListTxs, Is.EqualTo(new[] { ilTx1, ilTx2 })); + Assert.That(inclusionLists, Is.EqualTo(new[] { new[] { ilTx1 }, [], new[] { ilTx2, ilTx1 } })); + Assert.That(decoded.OmissionClaims.ToClaims(), Is.EqualTo(new[] { new OmissionClaim(TestItem.KeccakA, 3) })); } } @@ -1140,7 +1158,7 @@ public void DecodeFcuV5Request_roundtrips_slot_target_gas_and_inclusion_list() ParentBeaconBlockRoot = TestItem.KeccakE, SlotNumber = expectedSlot, TargetGasLimit = expectedTargetGasLimit, - InclusionListTransactions = [new SszTransaction { Bytes = ilTx }] + InclusionLists = [new SszInclusionList(), new SszInclusionList { Transactions = [new SszTransaction { Bytes = ilTx }] }] } ] }; @@ -1160,7 +1178,7 @@ public void DecodeFcuV5Request_roundtrips_slot_target_gas_and_inclusion_list() Assert.That(attrs.SlotNumber, Is.EqualTo(expectedSlot)); Assert.That(attrs.TargetGasLimit, Is.EqualTo(expectedTargetGasLimit)); Assert.That(attrs.SuggestedFeeRecipient, Is.EqualTo(TestItem.AddressB)); - Assert.That(attrs.InclusionListTransactions, Is.EqualTo(new[] { ilTx })); + Assert.That(attrs.InclusionLists, Is.EqualTo(new[] { [], new[] { ilTx } })); } } diff --git a/src/Nethermind/Nethermind.Merge.Plugin.Test/SszRest/SszMiddlewareTests.cs b/src/Nethermind/Nethermind.Merge.Plugin.Test/SszRest/SszMiddlewareTests.cs index 86ac750919b6..ba792aad0beb 100644 --- a/src/Nethermind/Nethermind.Merge.Plugin.Test/SszRest/SszMiddlewareTests.cs +++ b/src/Nethermind/Nethermind.Merge.Plugin.Test/SszRest/SszMiddlewareTests.cs @@ -376,12 +376,12 @@ await _engineModule.Received(1).engine_forkchoiceUpdatedV4( [Test] public async Task Forkchoice_v5_passes_custody_columns() { - ForkchoiceUpdatedV2Result fcuResult = new() + ForkchoiceUpdatedV1Result fcuResult = new() { - PayloadStatus = new PayloadStatusV2 { Status = PayloadStatus.Valid, LatestValidHash = TestItem.KeccakA } + PayloadStatus = new PayloadStatusV1 { Status = PayloadStatus.Valid, LatestValidHash = TestItem.KeccakA } }; _engineModule.engine_forkchoiceUpdatedV5(Arg.Any(), Arg.Any(), Arg.Any()) - .Returns(ResultWrapper.Success(fcuResult)); + .Returns(ResultWrapper.Success(fcuResult)); BitArray custodyColumns = CustodyColumnsFixture(); DefaultHttpContext ctx = MakePostContext("/engine/v1/forkchoice", BuildForkchoiceV5Request(custodyColumns), fork: "bogota"); @@ -1152,12 +1152,12 @@ public async Task ForkchoiceV5_validates_payload_fork_against_chain_spec(ulong p _specProvider = CreateChainSpecProvider(); _middleware = BuildMiddleware(); - ForkchoiceUpdatedV2Result fcuResult = new() + ForkchoiceUpdatedV1Result fcuResult = new() { - PayloadStatus = new PayloadStatusV2 { Status = PayloadStatus.Valid, LatestValidHash = TestItem.KeccakA, InclusionListSatisfied = true } + PayloadStatus = new PayloadStatusV1 { Status = PayloadStatus.Valid, LatestValidHash = TestItem.KeccakA } }; _engineModule.engine_forkchoiceUpdatedV5(Arg.Any(), Arg.Any(), Arg.Any()) - .Returns(ResultWrapper.Success(fcuResult)); + .Returns(ResultWrapper.Success(fcuResult)); ForkchoiceUpdatedV5RequestWire request = new() { @@ -1178,7 +1178,7 @@ public async Task ForkchoiceV5_validates_payload_fork_against_chain_spec(ulong p ParentBeaconBlockRoot = Keccak.Zero, SlotNumber = 1, TargetGasLimit = 30_000_000, - InclusionListTransactions = [], + InclusionLists = [], } ], CustodyColumns = [], @@ -1860,7 +1860,7 @@ public async Task NewPayloadV5_empty_block_access_list_returns_invalid_status() public async Task NewPayloadV6_bogota_routes_to_engine_newPayloadV6() { _engineModule.engine_newPayloadV6( - Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any()) + Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any()) .Returns(ResultWrapper.Success(new PayloadStatusV2 { Status = PayloadStatus.Valid, @@ -1883,18 +1883,131 @@ public async Task NewPayloadV6_bogota_routes_to_engine_newPayloadV6() Assert.That(ctx.Response.ContentType, Does.Contain(OctetStream)); } await _engineModule.Received(1).engine_newPayloadV6( - Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any()); + Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any()); + } + + private static readonly byte[][][] InclusionListsFixture = [[[0x01]], [], [[0x02], [0x01]]]; + private static readonly OmissionClaim[] ClaimsFixture = [new(TestItem.KeccakB, 1), new(TestItem.KeccakC, 7)]; + + private static SszInclusionList[] InclusionListsWire() => + [.. InclusionListsFixture.Select(static list => new SszInclusionList { Transactions = [.. list.Select(static tx => new SszTransaction { Bytes = tx })] })]; + + private static NewPayloadV6RequestWire NewPayloadV6WireWithListsAndClaims() => new() + { + ExecutionPayload = new SszExecutionPayloadV4(SszTestData.MakeV4Payload(blockAccessList: [0xc0], slotNumber: 0)), + ParentBeaconBlockRoot = TestItem.KeccakA, + InclusionLists = InclusionListsWire(), + OmissionClaims = ClaimsFixture.ToWire(), + }; + + private static bool InclusionListsMatch(byte[][][]? actual) => + actual is { } lists && lists.Length == InclusionListsFixture.Length + && lists.Zip(InclusionListsFixture).All(static p => p.First.Length == p.Second.Length && p.First.Zip(p.Second).All(static t => t.First.AsSpan().SequenceEqual(t.Second))); + + /// SSZ-REST newPayloadV6 carries the separate lists and claims to the engine exactly as JSON does. + [Test] + public async Task NewPayloadV6_ssz_carries_inclusion_lists_and_claims() + { + _engineModule.engine_newPayloadV6(Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any()) + .Returns(ResultWrapper.Success(new PayloadStatusV2 { Status = PayloadStatus.Valid, LatestValidHash = TestItem.KeccakA, InclusionListSatisfied = true })); + + DefaultHttpContext ctx = MakePostContext("/engine/v1/payloads", NewPayloadV6RequestWire.Encode(NewPayloadV6WireWithListsAndClaims()), fork: "bogota"); + await _middleware.InvokeAsync(ctx); + PayloadStatusV2Wire.Decode(new ReadOnlySequence(ResponseBytes(ctx)), out PayloadStatusV2Wire status); + + using (Assert.EnterMultipleScope()) + { + Assert.That(ctx.Response.StatusCode, Is.EqualTo(StatusCodes.Status200OK)); + Assert.That(status.InclusionListSatisfied, Is.EqualTo(new byte[] { 1 })); + } + await _engineModule.Received(1).engine_newPayloadV6( + Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(), + Arg.Is(lists => InclusionListsMatch(lists)), + Arg.Is(c => c != null && c.SequenceEqual(ClaimsFixture))); + } + + /// An over-cap claim list decodes over SSZ and reaches the engine, so it is answered as the engine's + /// -32602 rather than as an SSZ decode failure. + [Test] + public async Task NewPayloadV6_ssz_reports_over_cap_claims_as_invalid_params() + { + _engineModule.engine_newPayloadV6( + Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(), + Arg.Is(c => c != null && c.Length > Eip8369Constants.MaxOmissionClaims)) + .Returns(ResultWrapper.Fail("Omission claims exceed the maximum", ErrorCodes.InvalidParams)); + + NewPayloadV6RequestWire wire = NewPayloadV6WireWithListsAndClaims(); + wire.OmissionClaims = [.. Enumerable.Repeat(new OmissionClaimWire { TransactionHash = TestItem.KeccakA }, Eip8369Constants.MaxOmissionClaims + 1)]; + DefaultHttpContext ctx = MakePostContext("/engine/v1/payloads", NewPayloadV6RequestWire.Encode(wire), fork: "bogota"); + await _middleware.InvokeAsync(ctx); + + using (Assert.EnterMultipleScope()) + { + string body = System.Text.Encoding.UTF8.GetString(ResponseBytes(ctx)); + Assert.That(ctx.Response.StatusCode, Is.EqualTo(StatusCodes.Status422UnprocessableEntity)); + Assert.That(body, Does.Contain("/engine-api/errors/invalid-body")); + Assert.That(body, Does.Contain("Omission claims exceed the maximum")); + } + } + + /// SSZ-REST newPayloadWithWitnessV6 carries the separate lists and claims to the engine exactly as JSON does. + [Test] + public async Task NewPayloadWithWitnessV6_ssz_carries_inclusion_lists_and_claims() + { + _engineModule.engine_newPayloadWithWitnessV6(Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any()) + .Returns(ResultWrapper.Success(NewPayloadWithWitnessV1Result.FromPayloadStatus( + new PayloadStatusV1 { Status = PayloadStatus.Valid, LatestValidHash = TestItem.KeccakA }, null))); + + DefaultHttpContext ctx = MakePostContext(WitnessPath, NewPayloadV6RequestWire.Encode(NewPayloadV6WireWithListsAndClaims()), fork: "bogota"); + await _middleware.InvokeAsync(ctx); + + await _engineModule.Received(1).engine_newPayloadWithWitnessV6( + Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(), + Arg.Is(lists => InclusionListsMatch(lists)), + Arg.Is(c => c != null && c.SequenceEqual(ClaimsFixture))); + } + + /// SSZ-REST forkchoiceUpdatedV5 carries the attributes' separate lists to the engine. + [Test] + public async Task ForkchoiceUpdatedV5_ssz_carries_inclusion_lists() + { + _specProvider.GetSpec(Arg.Any()).Returns(Bogota.Instance); + _engineModule.engine_forkchoiceUpdatedV5(Arg.Any(), Arg.Any(), Arg.Any()) + .Returns(ResultWrapper.Success(new ForkchoiceUpdatedV1Result + { + PayloadStatus = new PayloadStatusV1 { Status = PayloadStatus.Valid, LatestValidHash = TestItem.KeccakA } + })); + + byte[] body = ForkchoiceUpdatedV5RequestWire.Encode(new ForkchoiceUpdatedV5RequestWire + { + ForkchoiceState = new ForkchoiceStateWire { HeadBlockHash = TestItem.KeccakA, SafeBlockHash = TestItem.KeccakB, FinalizedBlockHash = Keccak.Zero }, + PayloadAttributes = + [ + new PayloadAttributesV5Wire + { + Timestamp = 1, PrevRandao = TestItem.KeccakC, SuggestedFeeRecipient = TestItem.AddressA, Withdrawals = [], + ParentBeaconBlockRoot = TestItem.KeccakD, SlotNumber = 1, TargetGasLimit = 30_000_000, + InclusionLists = InclusionListsWire(), + }, + ], + CustodyColumns = [], + }); + DefaultHttpContext ctx = MakePostContext("/engine/v1/forkchoice", body, fork: "bogota"); + await _middleware.InvokeAsync(ctx); + + await _engineModule.Received(1).engine_forkchoiceUpdatedV5( + Arg.Any(), Arg.Is(pa => pa != null && InclusionListsMatch(pa.InclusionLists)), Arg.Any()); } [Test] public async Task ForkchoiceUpdatedV5_bogota_routes_to_engine_forkchoiceUpdatedV5() { - ForkchoiceUpdatedV2Result fcuResult = new() + ForkchoiceUpdatedV1Result fcuResult = new() { - PayloadStatus = new PayloadStatusV2 { Status = PayloadStatus.Valid, LatestValidHash = TestItem.KeccakA, InclusionListSatisfied = true } + PayloadStatus = new PayloadStatusV1 { Status = PayloadStatus.Valid, LatestValidHash = TestItem.KeccakA } }; _engineModule.engine_forkchoiceUpdatedV5(Arg.Any(), Arg.Any(), Arg.Any()) - .Returns(ResultWrapper.Success(fcuResult)); + .Returns(ResultWrapper.Success(fcuResult)); DefaultHttpContext ctx = MakePostContext("/engine/v1/forkchoice", BuildForkchoiceV5Request(), fork: "bogota"); diff --git a/src/Nethermind/Nethermind.Merge.Plugin/BlockProduction/PostMergeBlockProducer.cs b/src/Nethermind/Nethermind.Merge.Plugin/BlockProduction/PostMergeBlockProducer.cs index f78f69bd07b6..76938d068bf2 100644 --- a/src/Nethermind/Nethermind.Merge.Plugin/BlockProduction/PostMergeBlockProducer.cs +++ b/src/Nethermind/Nethermind.Merge.Plugin/BlockProduction/PostMergeBlockProducer.cs @@ -55,6 +55,7 @@ protected override BlockToProduce PrepareBlock(BlockHeader parent, PayloadAttrib blockToProduce.Transactions = inclusionList; } } + blockToProduce.InclusionListCandidates = inclusionListTxSource?.GetProfile2Candidates(payloadAttributes, _blocksConfig.FocilProfile2MaxVerifyGas); return blockToProduce; } diff --git a/src/Nethermind/Nethermind.Merge.Plugin/Data/ExecutionPayload.cs b/src/Nethermind/Nethermind.Merge.Plugin/Data/ExecutionPayload.cs index 8ce52c7718f0..eaaa615797cf 100644 --- a/src/Nethermind/Nethermind.Merge.Plugin/Data/ExecutionPayload.cs +++ b/src/Nethermind/Nethermind.Merge.Plugin/Data/ExecutionPayload.cs @@ -178,13 +178,6 @@ public byte[][] Transactions [JsonIgnore] public Hash256? ParentBeaconBlockRoot { get; set; } - /// - /// Gets or sets as defined in - /// EIP-7805. - /// - [JsonIgnore] - public virtual byte[][]? InclusionListTransactions { get; set; } - public static ExecutionPayload Create(Block block) => Create(block); protected static TExecutionPayload Create(Block block) where TExecutionPayload : ExecutionPayload, new() diff --git a/src/Nethermind/Nethermind.Merge.Plugin/Data/ExecutionPayloadV3.cs b/src/Nethermind/Nethermind.Merge.Plugin/Data/ExecutionPayloadV3.cs index 3cdea30dd654..28280b1beb18 100644 --- a/src/Nethermind/Nethermind.Merge.Plugin/Data/ExecutionPayloadV3.cs +++ b/src/Nethermind/Nethermind.Merge.Plugin/Data/ExecutionPayloadV3.cs @@ -2,12 +2,10 @@ // SPDX-License-Identifier: LGPL-3.0-only using System.Text.Json.Serialization; -using Nethermind.Consensus.Decoders; using Nethermind.Core; using Nethermind.Core.ExecutionRequest; using Nethermind.Core.Specs; using Nethermind.Int256; -using Nethermind.Serialization.Rlp; namespace Nethermind.Merge.Plugin.Data; @@ -31,7 +29,6 @@ public class ExecutionPayloadV3 : ExecutionPayload, IExecutionPayloadFactory TryGetBlock(UInt256? totalDifficulty = null) block.Header.BlobGasUsed = BlobGasUsed; block.Header.ExcessBlobGas = ExcessBlobGas; block.Header.RequestsHash = ExecutionRequests is not null ? ExecutionRequestExtensions.CalculateHashFromFlatEncodedRequests(ExecutionRequests) : null; - block.InclusionListTransactions = InclusionListTransactions is not null ? TxsDecoder.DecodeTxsBorrowingBuffers(InclusionListTransactions, skipErrors: true).Transactions : null; return baseResult; } diff --git a/src/Nethermind/Nethermind.Merge.Plugin/Data/ForkchoiceUpdatedV2Result.cs b/src/Nethermind/Nethermind.Merge.Plugin/Data/ForkchoiceUpdatedV2Result.cs deleted file mode 100644 index a62ebe90d521..000000000000 --- a/src/Nethermind/Nethermind.Merge.Plugin/Data/ForkchoiceUpdatedV2Result.cs +++ /dev/null @@ -1,32 +0,0 @@ -// SPDX-FileCopyrightText: 2026 Demerzel Solutions Limited -// SPDX-License-Identifier: LGPL-3.0-only - -using System.Text.Json.Serialization; - -namespace Nethermind.Merge.Plugin.Data; - -/// Result of engine_forkchoiceUpdatedV5 (EIP-7805): mirrors -/// but carries a so a VALID head can report inclusion-list compliance. -public class ForkchoiceUpdatedV2Result -{ - /// Fork-choice status, including inclusion-list compliance for a VALID head. - public PayloadStatusV2 PayloadStatus { get; set; } = new() { Status = Data.PayloadStatus.Syncing }; - - /// Identifier of the payload build process, or null if there is none. - [JsonIgnore(Condition = JsonIgnoreCondition.Never)] - public string? PayloadId { get; set; } - - /// Maps a base fork-choice result to the V5 shape, attaching the head block's inclusion-list - /// compliance; is null when it is unknown. - public static ForkchoiceUpdatedV2Result From(ForkchoiceUpdatedV1Result result, bool? inclusionListSatisfied) => new() - { - PayloadId = result.PayloadId, - PayloadStatus = new PayloadStatusV2 - { - Status = result.PayloadStatus.Status, - LatestValidHash = result.PayloadStatus.LatestValidHash, - ValidationError = result.PayloadStatus.ValidationError, - InclusionListSatisfied = inclusionListSatisfied, - } - }; -} diff --git a/src/Nethermind/Nethermind.Merge.Plugin/Data/GetPayloadDirectResponseWriter.cs b/src/Nethermind/Nethermind.Merge.Plugin/Data/GetPayloadDirectResponseWriter.cs index c2bcbf88989e..aace7401fa60 100644 --- a/src/Nethermind/Nethermind.Merge.Plugin/Data/GetPayloadDirectResponseWriter.cs +++ b/src/Nethermind/Nethermind.Merge.Plugin/Data/GetPayloadDirectResponseWriter.cs @@ -40,6 +40,18 @@ public static ValueTask WriteV6Async( CancellationToken cancellationToken) => WriteAsync(writer, block, blockValue, blobsBundle, executionRequests, shouldOverrideBuilder, includeV6Fields: true, cancellationToken); + /// The V6 response plus the build's EIP-7805 omission claims. + public static ValueTask WriteV7Async( + PipeWriter writer, + Block block, + UInt256 blockValue, + BlobsBundleV2 blobsBundle, + byte[][]? executionRequests, + bool shouldOverrideBuilder, + OmissionClaim[] omissionClaims, + CancellationToken cancellationToken) => + WriteAsync(writer, block, blockValue, blobsBundle, executionRequests, shouldOverrideBuilder, includeV6Fields: true, cancellationToken, omissionClaims); + private static async ValueTask WriteAsync( PipeWriter writer, Block block, @@ -48,7 +60,8 @@ private static async ValueTask WriteAsync( byte[][]? executionRequests, bool shouldOverrideBuilder, bool includeV6Fields, - CancellationToken cancellationToken) + CancellationToken cancellationToken, + OmissionClaim[]? omissionClaims = null) { writer.Write("{\"blockValue\":"u8); HexWriter.WriteUInt256HexString(writer, blockValue); @@ -76,9 +89,29 @@ private static async ValueTask WriteAsync( } } + if (omissionClaims is not null) + { + WriteOmissionClaims(writer, omissionClaims); + } + writer.Write("}"u8); } + private static void WriteOmissionClaims(IBufferWriter writer, OmissionClaim[] claims) + { + writer.Write(",\"omissionClaims\":["u8); + for (int i = 0; i < claims.Length; i++) + { + if (i > 0) writer.Write(","u8); + writer.Write("{\"transactionHash\":"u8); + WriteHexString(writer, claims[i].TransactionHash.Bytes, chunked: false); + writer.Write(",\"evaluationIndex\":"u8); + HexWriter.WriteUlongHexString(writer, claims[i].EvaluationIndex); + writer.Write("}"u8); + } + writer.Write("]"u8); + } + private static async ValueTask WriteExecutionPayloadAsync( PipeWriter writer, Block block, diff --git a/src/Nethermind/Nethermind.Merge.Plugin/Data/GetPayloadV7Result.cs b/src/Nethermind/Nethermind.Merge.Plugin/Data/GetPayloadV7Result.cs new file mode 100644 index 000000000000..e6221461962e --- /dev/null +++ b/src/Nethermind/Nethermind.Merge.Plugin/Data/GetPayloadV7Result.cs @@ -0,0 +1,27 @@ +// SPDX-FileCopyrightText: 2026 Demerzel Solutions Limited +// SPDX-License-Identifier: LGPL-3.0-only + +using System.IO.Pipelines; +using System.Threading; +using System.Threading.Tasks; +using Nethermind.Core; +using Nethermind.Int256; +using Nethermind.JsonRpc; + +namespace Nethermind.Merge.Plugin.Data; + +/// The engine_getPayloadV7 response: the V6 response plus the build's EIP-7805 omission claims. +public class GetPayloadV7Result(Block block, UInt256 blockFees, BlobsBundleV2 blobsBundle, byte[][] executionRequests, bool shouldOverrideBuilder) + : GetPayloadV6Result(block, blockFees, blobsBundle, executionRequests, shouldOverrideBuilder) +{ + /// An omission claim for each admitted Profile 2 candidate the build found invalid where it tried to + /// append it, at most . + public OmissionClaim[] OmissionClaims => Block.OmissionClaims ?? []; +} + +public sealed class GetPayloadV7DirectResponse(Block block, UInt256 blockFees, BlobsBundleV2 blobsBundle, byte[][] executionRequests, bool shouldOverrideBuilder) + : GetPayloadV7Result(block, blockFees, blobsBundle, executionRequests, shouldOverrideBuilder), IStreamableResult +{ + public ValueTask WriteToAsync(PipeWriter writer, CancellationToken cancellationToken) => + GetPayloadDirectResponseWriter.WriteV7Async(writer, Block, BlockValue, BlobsBundle, ExecutionRequests, ShouldOverrideBuilder, OmissionClaims, cancellationToken); +} diff --git a/src/Nethermind/Nethermind.Merge.Plugin/Data/IExecutionPayloadParams.cs b/src/Nethermind/Nethermind.Merge.Plugin/Data/IExecutionPayloadParams.cs index bc2f374bebe8..5239a190a819 100644 --- a/src/Nethermind/Nethermind.Merge.Plugin/Data/IExecutionPayloadParams.cs +++ b/src/Nethermind/Nethermind.Merge.Plugin/Data/IExecutionPayloadParams.cs @@ -13,7 +13,6 @@ public interface IExecutionPayloadParams { ExecutionPayload ExecutionPayload { get; } byte[][]? ExecutionRequests { get; set; } - byte[][]? InclusionListTransactions { get; set; } ValidationResult ValidateParams(IReleaseSpec spec, int version, out string? error); /// Validates request parameters and bounds the transaction count before decoding when supported. @@ -34,7 +33,8 @@ public enum ValidationResult : byte { Success, Fail, Invalid }; public class ExecutionPayloadParams( byte[][]? executionRequests = null, - byte[][]? inclusionListTransactions = null) + byte[][][]? inclusionLists = null, + OmissionClaim[]? omissionClaims = null) { /// /// Gets or sets as defined in @@ -42,8 +42,11 @@ public class ExecutionPayloadParams( /// public byte[][]? ExecutionRequests { get; set; } = executionRequests; - /// Inclusion-list entries as defined in EIP-7805. - public byte[][]? InclusionListTransactions { get; set; } = inclusionListTransactions; + /// EIP-7805 separate inclusion lists, one per committee position (). + public byte[][][]? InclusionLists { get; } = inclusionLists; + + /// The EIP-7805 omission claims the builder committed to, in order and with their duplicates. + public OmissionClaim[]? OmissionClaims { get; } = omissionClaims; protected ValidationResult ValidateInitialParams(IReleaseSpec spec, out string? error) { @@ -79,27 +82,28 @@ protected ValidationResult ValidateInitialParams(IReleaseSpec spec, out string? } } + // bogota.md engine_newPayloadV6 point 2. Transaction contents and claims that match nothing are judged by + // the inclusion check, never here. if (spec.InclusionListsEnabled) { - if (InclusionListTransactions is null) + error = Core.InclusionLists.Validate(InclusionLists); + if (error is not null) return ValidationResult.Fail; + + if (OmissionClaims is null) { - error = "Inclusion list must be set"; + error = "Omission claims must be set"; return ValidationResult.Fail; } - // Count is bounded separately from bytes: an empty entry costs no bytes but still allocates a slot. - if (InclusionListTransactions.Length > Eip7805Constants.MaxAggregateInclusionListTransactions) + if (OmissionClaims.Length > Eip8369Constants.MaxOmissionClaims) { - error = "Inclusion list exceeds the maximum number of transactions"; + error = $"Omission claims exceed the maximum of {Eip8369Constants.MaxOmissionClaims}"; return ValidationResult.Fail; } - long totalBytes = 0; - for (int i = 0; i < InclusionListTransactions.Length; i++) - totalBytes += InclusionListTransactions[i]?.Length ?? 0; - if (totalBytes > Eip7805Constants.MaxAggregateInclusionListBytes) + if (Array.Exists(OmissionClaims, static claim => claim.TransactionHash is null)) { - error = "Inclusion list exceeds the maximum aggregate size"; + error = "Omission claim transaction hash must be set"; return ValidationResult.Fail; } } @@ -113,8 +117,9 @@ public class ExecutionPayloadParams( Hash256?[]? blobVersionedHashes, Hash256? parentBeaconBlockRoot, byte[][]? executionRequests = null, - byte[][]? inclusionListTransactions = null) - : ExecutionPayloadParams(executionRequests, inclusionListTransactions), IExecutionPayloadParams where TVersionedExecutionPayload : ExecutionPayload + byte[][][]? inclusionLists = null, + OmissionClaim[]? omissionClaims = null) + : ExecutionPayloadParams(executionRequests, inclusionLists, omissionClaims), IExecutionPayloadParams where TVersionedExecutionPayload : ExecutionPayload { public TVersionedExecutionPayload ExecutionPayload => executionPayload; @@ -322,6 +327,7 @@ public sealed class InclusionListExecutionPayloadParams( Hash256?[]? blobVersionedHashes, Hash256? parentBeaconBlockRoot, byte[][]? executionRequests, - byte[][]? inclusionListTransactions) + byte[][][]? inclusionLists, + OmissionClaim[]? omissionClaims) : ExecutionPayloadParams( - executionPayload, blobVersionedHashes, parentBeaconBlockRoot, executionRequests, inclusionListTransactions); + executionPayload, blobVersionedHashes, parentBeaconBlockRoot, executionRequests, inclusionLists, omissionClaims); diff --git a/src/Nethermind/Nethermind.Merge.Plugin/Data/NewPayloadV1Result.cs b/src/Nethermind/Nethermind.Merge.Plugin/Data/NewPayloadV1Result.cs index e18b3a1c6e31..0c51d34aab6b 100644 --- a/src/Nethermind/Nethermind.Merge.Plugin/Data/NewPayloadV1Result.cs +++ b/src/Nethermind/Nethermind.Merge.Plugin/Data/NewPayloadV1Result.cs @@ -22,7 +22,5 @@ public static ResultWrapper Invalid(string validationError) } public static ResultWrapper Invalid(Hash256? latestValidHash, string? validationError = null) => ResultWrapper.Success(new PayloadStatusV1() { Status = PayloadStatus.Invalid, LatestValidHash = latestValidHash, ValidationError = validationError }); - public static ResultWrapper InclusionListUnsatisfied(Hash256? latestValidHash) => ResultWrapper.Success(new PayloadStatusV1() { Status = PayloadStatus.InclusionListUnsatisfied, LatestValidHash = latestValidHash }); - public static ResultWrapper Valid(Hash256? latestValidHash) => ResultWrapper.Success(new PayloadStatusV1() { Status = PayloadStatus.Valid, LatestValidHash = latestValidHash }); } diff --git a/src/Nethermind/Nethermind.Merge.Plugin/Data/PayloadStatus.cs b/src/Nethermind/Nethermind.Merge.Plugin/Data/PayloadStatus.cs index fceb3d67f134..afbe64b4638e 100644 --- a/src/Nethermind/Nethermind.Merge.Plugin/Data/PayloadStatus.cs +++ b/src/Nethermind/Nethermind.Merge.Plugin/Data/PayloadStatus.cs @@ -24,8 +24,5 @@ public static class PayloadStatus /// Payload was accepted but not executed yet. It can be executed in call. /// public const string Accepted = "ACCEPTED"; - - /// The block executed cleanly but omitted an appendable inclusion-list transaction (EIP-7805). - public const string InclusionListUnsatisfied = "INCLUSION_LIST_UNSATISFIED"; } } diff --git a/src/Nethermind/Nethermind.Merge.Plugin/Data/PayloadStatusV2.cs b/src/Nethermind/Nethermind.Merge.Plugin/Data/PayloadStatusV2.cs index 328e9c889c7e..8da389fc9670 100644 --- a/src/Nethermind/Nethermind.Merge.Plugin/Data/PayloadStatusV2.cs +++ b/src/Nethermind/Nethermind.Merge.Plugin/Data/PayloadStatusV2.cs @@ -6,11 +6,11 @@ namespace Nethermind.Merge.Plugin.Data; /// Result of engine_newPayloadV6 (EIP-7805). -/// A payload that omitted an appendable inclusion-list transaction is still VALID -/// (execution-apis#609). +/// An unsatisfied inclusion list does not change execution validity, so a payload that omitted an +/// appendable inclusion-list transaction is still VALID, with false. public class PayloadStatusV2 : PayloadStatusV1 { - /// Inclusion-list compliance when is VALID; null otherwise. + /// The completed inclusion verdict when the status is VALID; null otherwise. [JsonIgnore(Condition = JsonIgnoreCondition.Never)] public bool? InclusionListSatisfied { get; set; } } diff --git a/src/Nethermind/Nethermind.Merge.Plugin/EngineRpcModule.Bogota.cs b/src/Nethermind/Nethermind.Merge.Plugin/EngineRpcModule.Bogota.cs index 56d33082bdcf..14c8fb191eb5 100644 --- a/src/Nethermind/Nethermind.Merge.Plugin/EngineRpcModule.Bogota.cs +++ b/src/Nethermind/Nethermind.Merge.Plugin/EngineRpcModule.Bogota.cs @@ -1,12 +1,9 @@ // SPDX-FileCopyrightText: 2026 Demerzel Solutions Limited // SPDX-License-Identifier: LGPL-3.0-only -using System; using System.Collections; -using System.Collections.Generic; using System.Threading; using System.Threading.Tasks; -using Nethermind.Blockchain; using Nethermind.Consensus.Producers; using Nethermind.Core; using Nethermind.Core.Crypto; @@ -14,42 +11,27 @@ using Nethermind.JsonRpc; using Nethermind.Merge.Plugin.Data; using Nethermind.Merge.Plugin.Handlers; -using Nethermind.Trie; namespace Nethermind.Merge.Plugin; public partial class EngineRpcModule : IEngineRpcModule { - /// An inclusion list retained for a payload that could not yet be validated. - private readonly record struct RetainedInclusionList(ulong Number, byte[][] Transactions, bool Accepted); - private readonly record struct InclusionListAnswer(ulong Number, bool Satisfied); + private readonly IInclusionChecks _inclusionChecks = inclusionChecks; - private readonly Dictionary _inclusionListAnswers = []; - private readonly Dictionary _retainedInclusionLists = []; - // Keep even non-tip ACCEPTED lists until evaluation/finality to answer a later FCUv5 (bogota.md (2.1)). - // Stalled finality can grow this map with chain length; only best-effort SYNCING lists can be evicted. - private readonly InclusionListInsertionOrder _syncingInclusionListOrder = new(); - // Answers outlive their list, so finality is their normal bound and this one only catches stalled finality. - private readonly InclusionListInsertionOrder _inclusionListAnswerOrder = new(); - private readonly IBlockTree _inclusionListBlockTree = blockTree; - private const int MaxRetainedSyncingInclusionLists = 64; - private const int MaxInclusionListAnswers = 256; - private ulong _finalizedInclusionListNumber; - private Hash256? _finalizedInclusionListHash; - - // A concurrent engine_newPayloadV6 must not have its newer list overwritten by an earlier evaluation. - private readonly Lock _inclusionListLock = new(); + private readonly IAsyncHandler _newPayloadWithWitnessHandlerV6 = newPayloadWithWitnessHandlerV6; - private readonly IInclusionListComplianceEvaluator _inclusionListComplianceEvaluator = inclusionListComplianceEvaluator; + private readonly IAsyncHandler _getPayloadHandlerV7 = getPayloadHandlerV7; - private readonly IAsyncHandler _newPayloadWithWitnessHandlerV6 = newPayloadWithWitnessHandlerV6; + public Task> engine_getPayloadV7(byte[] payloadId) + => _getPayloadHandlerV7.HandleAsync(payloadId); public Task> engine_getInclusionListV1(Hash256? parentBlockHash = null) => getInclusionListTransactionsHandler.Handle(parentBlockHash); - public Task> engine_newPayloadV6(ExecutionPayloadV4 executionPayload, Hash256?[] blobVersionedHashes, Hash256? parentBeaconBlockRoot, byte[][]? executionRequests, byte[][]? inclusionListTransactions) - => NewPayloadWithInclusionList( - new ExecutionPayloadParams(executionPayload, blobVersionedHashes, parentBeaconBlockRoot, executionRequests, inclusionListTransactions), + public Task> engine_newPayloadV6(ExecutionPayloadV4 executionPayload, Hash256?[] blobVersionedHashes, Hash256? parentBeaconBlockRoot, + byte[][]? executionRequests, byte[][][]? inclusionLists, OmissionClaim[]? omissionClaims) + => NewPayloadWithInclusionCheck( + new InclusionListExecutionPayloadParams(executionPayload, blobVersionedHashes, parentBeaconBlockRoot, executionRequests, inclusionLists, omissionClaims), EngineApiVersions.NewPayload.V6); public Task> engine_newPayloadWithWitnessV6( @@ -57,12 +39,16 @@ public Task> engine_newPayloadWithW Hash256?[] blobVersionedHashes, Hash256? parentBeaconBlockRoot, byte[][]? executionRequests, - byte[][]? inclusionListTransactions) + byte[][][]? inclusionLists, + OmissionClaim[]? omissionClaims) => _newPayloadWithWitnessHandlerV6.HandleAsync( - new InclusionListExecutionPayloadParams(executionPayload, blobVersionedHashes, parentBeaconBlockRoot, executionRequests, inclusionListTransactions)); + new InclusionListExecutionPayloadParams(executionPayload, blobVersionedHashes, parentBeaconBlockRoot, executionRequests, inclusionLists, omissionClaims)); - /// Runs and maps its result onto the Bogota shape. - protected async Task> NewPayloadWithInclusionList(IExecutionPayloadParams executionPayloadParams, int version) + /// Runs and, once execution is VALID, completes the inclusion check for + /// this call's inputs before answering (bogota.md § Inclusion checking). + /// A check that cannot be decided, its state or execution gas counters being unavailable, answers + /// SYNCING, since VALID must carry a completed verdict. + protected async Task> NewPayloadWithInclusionCheck(ExecutionPayloadParams executionPayloadParams, int version) { ResultWrapper result = await NewPayload(executionPayloadParams, version); @@ -70,267 +56,51 @@ protected async Task> NewPayloadWithInclusionList return ResultWrapper.Fail(result.Result.Error!, result.ErrorCode, result.IsTemporary); PayloadStatusV1 status = result.Data; - // INCLUSION_LIST_UNSATISFIED is pipeline-internal: on the wire the block is VALID and the - // compliance answer moves into inclusionListSatisfied (execution-apis#609). - bool unsatisfied = status.Status == PayloadStatus.InclusionListUnsatisfied; - bool? inclusionListSatisfied = status.Status switch + PayloadStatusV2 statusV2 = new() { - PayloadStatus.InclusionListUnsatisfied => false, - PayloadStatus.Valid => true, - _ => null + Status = status.Status, + LatestValidHash = status.LatestValidHash, + ValidationError = status.ValidationError }; - if (inclusionListSatisfied is { } satisfied && status.LatestValidHash is { } validHash) - { - SetInclusionListAnswer(validHash, - executionPayloadParams.ExecutionPayload.BlockNumber, satisfied); - } - else if (status.Status is PayloadStatus.Accepted or PayloadStatus.Syncing - && executionPayloadParams is { InclusionListTransactions: { } retained, ExecutionPayload.BlockHash: { } blockHash }) + // newPayload validated both before it could answer VALID. + if (status.Status == PayloadStatus.Valid + && executionPayloadParams is { InclusionLists: { } inclusionLists, OmissionClaims: { } claims }) { - SetRetainedInclusionList(blockHash, - executionPayloadParams.ExecutionPayload.BlockNumber, retained, - status.Status == PayloadStatus.Accepted); + statusV2.InclusionListSatisfied = await _inclusionChecks.CheckAsync(executionPayloadParams.ExecutionPayload, inclusionLists, claims, CancellationToken.None); + if (statusV2.InclusionListSatisfied is null) + { + statusV2.Status = PayloadStatus.Syncing; + statusV2.LatestValidHash = null; + } } - return ResultWrapper.Success(new PayloadStatusV2 - { - Status = unsatisfied ? PayloadStatus.Valid : status.Status, - LatestValidHash = status.LatestValidHash, - ValidationError = status.ValidationError, - InclusionListSatisfied = inclusionListSatisfied - }); + return ResultWrapper.Success(statusV2); } - public Task> engine_forkchoiceUpdatedV5( + public Task> engine_forkchoiceUpdatedV5( ForkchoiceStateV1 forkchoiceState, PayloadAttributes? payloadAttributes = null, BitArray? custodyColumns = null) - => ValidateAndApplyCustodyColumns(custodyColumns) is { } error - ? Task.FromResult(ResultWrapper.Fail(error, ErrorCodes.InvalidParams)) - : ForkchoiceUpdatedWithInclusionList(forkchoiceState, payloadAttributes, EngineApiVersions.Fcu.V5); - - /// Registers any inclusion list for the build, then runs and maps - /// its result onto the Bogota shape. - protected async Task> ForkchoiceUpdatedWithInclusionList( - ForkchoiceStateV1 forkchoiceState, PayloadAttributes? payloadAttributes, int version) - { - // Out of fork the attributes are rejected below with -38005, so don't retain the list at all. - if (payloadAttributes?.InclusionListTransactions is { } ilTxs - && _specProvider.GetSpec(ForkActivation.TimestampOnly(payloadAttributes.Timestamp)) is { IsEip7805Enabled: true } spec) - { - // An oversized IL is a no-op, not a protocol error. Set only registers the list: decoding and - // sender recovery are deferred to the build, so an update that never builds pays nothing. - if (ExceedsAggregateInclusionListBound(ilTxs)) - { - if (_logger.IsWarn) _logger.Warn($"engine_forkchoiceUpdatedV{version}: discarding oversized inclusion list ({ilTxs.Length} entries); building without it."); - } - else - { - inclusionListTxSource.Set(ilTxs, spec); - } - } - - ResultWrapper result = await ForkchoiceUpdatedV3(forkchoiceState, payloadAttributes, version); - if (result.Result.ResultType != ResultType.Success) - return ResultWrapper.Fail(result.Result.Error!, result.ErrorCode, result.IsTemporary); - - if (result.Data.PayloadStatus.Status is PayloadStatus.Valid or PayloadStatus.Syncing) - PruneFinalizedInclusionLists(forkchoiceState.FinalizedBlockHash); - - bool? inclusionListSatisfied = result.Data.PayloadStatus.Status == PayloadStatus.Valid - ? GetInclusionListSatisfied(forkchoiceState.HeadBlockHash) - : null; - - return ResultWrapper.Success(ForkchoiceUpdatedV2Result.From(result.Data, inclusionListSatisfied)); - } - - /// Inclusion-list compliance of a VALID forkchoice head (bogota.md - /// engine_forkchoiceUpdatedV5 (2)). - /// - /// Uses the answer engine_newPayloadV6 already computed, falling back to evaluating the list retained for a - /// payload that resolved to ACCEPTED/SYNCING. Concurrent calls for one head recompute the same value. - /// - /// null when no list was retained for the head, or its state is no longer readable. - private bool? GetInclusionListSatisfied(Hash256 headBlockHash) { - byte[][] retained; - lock (_inclusionListLock) - { - if (_inclusionListAnswers.TryGetValue(headBlockHash, out InclusionListAnswer cached)) return cached.Satisfied; - if (!_retainedInclusionLists.TryGetValue(headBlockHash, out RetainedInclusionList state)) return null; - retained = state.Transactions; - } - - bool? evaluated; - try - { - // Sender recovery and state reads delay the payloadId response; accepted, as only a head newPayloadV6 - // left unanswered pays it, and publishing the answer caps it at once per head. - evaluated = _inclusionListComplianceEvaluator.TryEvaluate(headBlockHash, retained); - } - // The head is already applied and a build may be under way, and bogota.md permits a null answer, so - // a state read that hits a pruned or still-healing subtrie must not fail the forkchoice update. - catch (TrieException exception) - { - _logger.DebugError($"Cannot evaluate the inclusion list of head {headBlockHash}: {exception}"); - return null; - } - catch (Exception exception) - { - if (_logger.IsError) _logger.Error($"Cannot evaluate the inclusion list of head {headBlockHash}: {exception}"); - // bogota.md lets a retained list go only once its payload is no longer a tip, so a failure here - // cannot discard one: the entry survives and the next update to this head retries. - return null; - } - - if (evaluated is not { } answer) - { - // Routine while the head's state is still healing, and the entry survives so the next update retries. - if (_logger.IsDebug) _logger.Debug($"Cannot evaluate the inclusion list of head {headBlockHash}; reporting inclusionListSatisfied as null."); - return null; - } - - PublishInclusionListAnswer(headBlockHash, retained, answer); - - return answer; - } + if (ValidateAndApplyCustodyColumns(custodyColumns) is { } error) + return Task.FromResult(ResultWrapper.Fail(error, ErrorCodes.InvalidParams)); - internal void SetInclusionListAnswer(Hash256 blockHash, ulong number, bool answer) - { - lock (_inclusionListLock) + // bogota.md engine_forkchoiceUpdatedV5 point 1.1 precedes the fork check. Absent lists are left to the + // attributes' own version checks. + if (payloadAttributes?.InclusionLists is { } inclusionLists) { - if (!IsAfterFinalization(blockHash, number)) return; - RemoveRetainedInclusionList(blockHash); - AddInclusionListAnswer(blockHash, number, answer); - } - } + if (InclusionLists.Validate(inclusionLists) is { } attributesError) + return Task.FromResult(ResultWrapper.Fail(attributesError, MergeErrorCodes.InvalidPayloadAttributes)); - internal void SetRetainedInclusionList(Hash256 blockHash, ulong number, byte[][] retained, bool accepted) - { - lock (_inclusionListLock) - { - RemoveInclusionListAnswer(blockHash); - if (!IsAfterFinalization(blockHash, number)) return; - RemoveRetainedInclusionList(blockHash); - _retainedInclusionLists[blockHash] = new RetainedInclusionList(number, retained, accepted); - if (!accepted) - { - _syncingInclusionListOrder.Add(blockHash); - if (_syncingInclusionListOrder.Count > MaxRetainedSyncingInclusionLists) - RemoveRetainedInclusionList(_syncingInclusionListOrder.Oldest); - } + // Out of fork the attributes are rejected with -38005, so the lists are not retained at all. Set only + // registers them: decoding and sender recovery are deferred to the build, so an update that never builds + // pays nothing. + if (_specProvider.GetSpec(ForkActivation.TimestampOnly(payloadAttributes.Timestamp)) is { IsEip7805Enabled: true } spec) + inclusionListTxSource.Set(inclusionLists, spec); } - } - internal bool HasRetainedInclusionList(Hash256 blockHash) - { - lock (_inclusionListLock) return _retainedInclusionLists.ContainsKey(blockHash); - } - - internal int RetainedInclusionListCount - { - get { lock (_inclusionListLock) return _retainedInclusionLists.Count; } - } - - internal bool HasInclusionListAnswer(Hash256 blockHash) - { - lock (_inclusionListLock) return _inclusionListAnswers.ContainsKey(blockHash); - } - - /// Stores what evaluating established for , - /// but only while that is still the list retained for it. - /// A concurrent engine_newPayloadV6 may have retained a newer list, which outranks anything - /// derived from the older one. - private void PublishInclusionListAnswer(Hash256 blockHash, byte[][] retained, bool answer) - { - lock (_inclusionListLock) - { - if (_retainedInclusionLists.TryGetValue(blockHash, out RetainedInclusionList current) - && ReferenceEquals(current.Transactions, retained)) - { - RemoveRetainedInclusionList(blockHash); - if (IsAfterFinalization(blockHash, current.Number)) - AddInclusionListAnswer(blockHash, current.Number, answer); - } - } - } - - private bool IsAfterFinalization(Hash256 blockHash, ulong number) => - _finalizedInclusionListHash is null || number > _finalizedInclusionListNumber || blockHash == _finalizedInclusionListHash; - - private void PruneFinalizedInclusionLists(Hash256 finalizedHash) - { - // Read outside the lock: a stale value only costs the header lookup. - if (finalizedHash == Hash256.Zero || finalizedHash == _finalizedInclusionListHash - || _inclusionListBlockTree.FindHeader(finalizedHash, - BlockTreeLookupOptions.DoNotCreateLevelIfMissing) is not { Number: ulong number }) return; - - lock (_inclusionListLock) - { - if (_finalizedInclusionListHash == finalizedHash) return; - if (_finalizedInclusionListHash is not null && number < _finalizedInclusionListNumber) return; - _finalizedInclusionListNumber = number; - _finalizedInclusionListHash = finalizedHash; - - foreach ((Hash256 hash, RetainedInclusionList entry) in _retainedInclusionLists) - if (entry.Number <= number && hash != finalizedHash) RemoveRetainedInclusionList(hash); - foreach ((Hash256 hash, InclusionListAnswer entry) in _inclusionListAnswers) - if (entry.Number <= number && hash != finalizedHash) RemoveInclusionListAnswer(hash); - } - } - - private void RemoveRetainedInclusionList(Hash256 blockHash) - { - if (!_retainedInclusionLists.Remove(blockHash, out RetainedInclusionList entry)) return; - if (!entry.Accepted) _syncingInclusionListOrder.Remove(blockHash); - } - - private void AddInclusionListAnswer(Hash256 blockHash, ulong number, bool satisfied) - { - _inclusionListAnswers[blockHash] = new InclusionListAnswer(number, satisfied); - _inclusionListAnswerOrder.Add(blockHash); - if (_inclusionListAnswerOrder.Count > MaxInclusionListAnswers) - RemoveInclusionListAnswer(_inclusionListAnswerOrder.Oldest); - } - - private void RemoveInclusionListAnswer(Hash256 blockHash) - { - if (_inclusionListAnswers.Remove(blockHash)) _inclusionListAnswerOrder.Remove(blockHash); - } - - /// Insertion order of a bounded map's keys, so its oldest entry can be found in O(1). - private sealed class InclusionListInsertionOrder - { - private readonly LinkedList _order = new(); - private readonly Dictionary> _nodes = []; - - public int Count => _nodes.Count; - - public Hash256 Oldest => _order.First!.Value; - - public void Add(Hash256 hash) - { - Remove(hash); - _nodes[hash] = _order.AddLast(hash); - } - - public void Remove(Hash256 hash) - { - if (_nodes.Remove(hash, out LinkedListNode? node)) _order.Remove(node); - } - } - - // Mirrors the newPayloadV6 aggregate bound (IExecutionPayloadParams.ValidateInitialParams). - private static bool ExceedsAggregateInclusionListBound(byte[][] inclusionListTransactions) - { - if (inclusionListTransactions.Length > Eip7805Constants.MaxAggregateInclusionListTransactions) return true; - long totalBytes = 0; - for (int i = 0; i < inclusionListTransactions.Length; i++) - { - totalBytes += inclusionListTransactions[i]?.Length ?? 0; - if (totalBytes > Eip7805Constants.MaxAggregateInclusionListBytes) return true; - } - return false; + // Forkchoice updates report execution validity only. + return ForkchoiceUpdatedV3(forkchoiceState, payloadAttributes, EngineApiVersions.Fcu.V5); } } diff --git a/src/Nethermind/Nethermind.Merge.Plugin/EngineRpcModule.Paris.cs b/src/Nethermind/Nethermind.Merge.Plugin/EngineRpcModule.Paris.cs index 8c60d936360f..5c43cb86a586 100644 --- a/src/Nethermind/Nethermind.Merge.Plugin/EngineRpcModule.Paris.cs +++ b/src/Nethermind/Nethermind.Merge.Plugin/EngineRpcModule.Paris.cs @@ -96,7 +96,6 @@ protected async Task> NewPayload(IExecutionPayloa _engineRequestsTracker.OnNewPayloadCalled(); ExecutionPayload executionPayload = executionPayloadParams.ExecutionPayload; executionPayload.ExecutionRequests = executionPayloadParams.ExecutionRequests; - executionPayload.InclusionListTransactions = executionPayloadParams.InclusionListTransactions; if (!executionPayload.ValidateForkOnNewPayload(_specProvider, version)) { diff --git a/src/Nethermind/Nethermind.Merge.Plugin/EngineRpcModule.cs b/src/Nethermind/Nethermind.Merge.Plugin/EngineRpcModule.cs index cd497905f23e..26b2965db1e6 100644 --- a/src/Nethermind/Nethermind.Merge.Plugin/EngineRpcModule.cs +++ b/src/Nethermind/Nethermind.Merge.Plugin/EngineRpcModule.cs @@ -5,7 +5,6 @@ using System.Collections; using System.Collections.Generic; using Nethermind.Api; -using Nethermind.Blockchain; using Nethermind.Consensus.Transactions; using Nethermind.Consensus.Processing; using Nethermind.Core; @@ -27,6 +26,7 @@ public partial class EngineRpcModule( IAsyncHandler getPayloadHandlerV4, IAsyncHandler getPayloadHandlerV5, IAsyncHandler getPayloadHandlerV6, + IAsyncHandler getPayloadHandlerV7, IAsyncHandler newPayloadV1Handler, IForkchoiceUpdatedHandler forkchoiceUpdatedV1Handler, IHandler, IReadOnlyList> executionGetPayloadBodiesByHashV1Handler, @@ -40,7 +40,7 @@ public partial class EngineRpcModule( IGetPayloadBodiesByRangeV2Handler getPayloadBodiesByRangeV2Handler, IHandler getInclusionListTransactionsHandler, IInclusionListTxSource inclusionListTxSource, - IInclusionListComplianceEvaluator inclusionListComplianceEvaluator, + IInclusionChecks inclusionChecks, IAsyncHandler, NewPayloadWithWitnessV1Result> newPayloadWithWitnessHandlerV4, IAsyncHandler, NewPayloadWithWitnessV1Result> newPayloadWithWitnessHandlerV5, IAsyncHandler newPayloadWithWitnessHandlerV6, @@ -50,7 +50,6 @@ public partial class EngineRpcModule( GCKeeper gcKeeper, IBlockProcessingQueue processingQueue, ILogManager logManager, - IBlockTree blockTree, PayloadTransactionCountGuard? transactionCountGuard) : IEngineRpcModule { /// Initializes the module without a . @@ -61,6 +60,7 @@ public EngineRpcModule( IAsyncHandler getPayloadHandlerV4, IAsyncHandler getPayloadHandlerV5, IAsyncHandler getPayloadHandlerV6, + IAsyncHandler getPayloadHandlerV7, IAsyncHandler newPayloadV1Handler, IForkchoiceUpdatedHandler forkchoiceUpdatedV1Handler, IHandler, IReadOnlyList> executionGetPayloadBodiesByHashV1Handler, @@ -74,7 +74,7 @@ public EngineRpcModule( IGetPayloadBodiesByRangeV2Handler getPayloadBodiesByRangeV2Handler, IHandler getInclusionListTransactionsHandler, IInclusionListTxSource inclusionListTxSource, - IInclusionListComplianceEvaluator inclusionListComplianceEvaluator, + IInclusionChecks inclusionChecks, IAsyncHandler, NewPayloadWithWitnessV1Result> newPayloadWithWitnessHandlerV4, IAsyncHandler, NewPayloadWithWitnessV1Result> newPayloadWithWitnessHandlerV5, IAsyncHandler newPayloadWithWitnessHandlerV6, @@ -83,8 +83,7 @@ public EngineRpcModule( ISpecProvider specProvider, GCKeeper gcKeeper, IBlockProcessingQueue processingQueue, - ILogManager logManager, - IBlockTree blockTree) + ILogManager logManager) : this( getPayloadHandlerV1, getPayloadHandlerV2, @@ -92,6 +91,7 @@ public EngineRpcModule( getPayloadHandlerV4, getPayloadHandlerV5, getPayloadHandlerV6, + getPayloadHandlerV7, newPayloadV1Handler, forkchoiceUpdatedV1Handler, executionGetPayloadBodiesByHashV1Handler, @@ -105,7 +105,7 @@ public EngineRpcModule( getPayloadBodiesByRangeV2Handler, getInclusionListTransactionsHandler, inclusionListTxSource, - inclusionListComplianceEvaluator, + inclusionChecks, newPayloadWithWitnessHandlerV4, newPayloadWithWitnessHandlerV5, newPayloadWithWitnessHandlerV6, @@ -115,7 +115,6 @@ public EngineRpcModule( gcKeeper, processingQueue, logManager, - blockTree, null) { } @@ -129,6 +128,7 @@ public EngineRpcModule( IAsyncHandler getPayloadHandlerV4, IAsyncHandler getPayloadHandlerV5, IAsyncHandler getPayloadHandlerV6, + IAsyncHandler getPayloadHandlerV7, IAsyncHandler newPayloadV1Handler, IForkchoiceUpdatedHandler forkchoiceUpdatedV1Handler, IHandler, IReadOnlyList> executionGetPayloadBodiesByHashV1Handler, @@ -142,7 +142,7 @@ public EngineRpcModule( IGetPayloadBodiesByRangeV2Handler getPayloadBodiesByRangeV2Handler, IHandler getInclusionListTransactionsHandler, IInclusionListTxSource inclusionListTxSource, - IInclusionListComplianceEvaluator inclusionListComplianceEvaluator, + IInclusionChecks inclusionChecks, IAsyncHandler, NewPayloadWithWitnessV1Result> newPayloadWithWitnessHandlerV4, IAsyncHandler, NewPayloadWithWitnessV1Result> newPayloadWithWitnessHandlerV5, IAsyncHandler newPayloadWithWitnessHandlerV6, @@ -150,8 +150,7 @@ public EngineRpcModule( ISpecProvider specProvider, GCKeeper gcKeeper, IBlockProcessingQueue processingQueue, - ILogManager logManager, - IBlockTree blockTree) + ILogManager logManager) : this( getPayloadHandlerV1, getPayloadHandlerV2, @@ -159,6 +158,7 @@ public EngineRpcModule( getPayloadHandlerV4, getPayloadHandlerV5, getPayloadHandlerV6, + getPayloadHandlerV7, newPayloadV1Handler, forkchoiceUpdatedV1Handler, executionGetPayloadBodiesByHashV1Handler, @@ -172,7 +172,7 @@ public EngineRpcModule( getPayloadBodiesByRangeV2Handler, getInclusionListTransactionsHandler, inclusionListTxSource, - inclusionListComplianceEvaluator, + inclusionChecks, newPayloadWithWitnessHandlerV4, newPayloadWithWitnessHandlerV5, newPayloadWithWitnessHandlerV6, @@ -181,8 +181,7 @@ public EngineRpcModule( specProvider, gcKeeper, processingQueue, - logManager, - blockTree) + logManager) { } diff --git a/src/Nethermind/Nethermind.Merge.Plugin/Handlers/EngineRpcCapabilitiesProvider.cs b/src/Nethermind/Nethermind.Merge.Plugin/Handlers/EngineRpcCapabilitiesProvider.cs index 1de34e13e0b9..88fe7a984a43 100644 --- a/src/Nethermind/Nethermind.Merge.Plugin/Handlers/EngineRpcCapabilitiesProvider.cs +++ b/src/Nethermind/Nethermind.Merge.Plugin/Handlers/EngineRpcCapabilitiesProvider.cs @@ -133,6 +133,7 @@ void Configure(string method, string path, RpcCapabilityOptions options) Configure(nameof(IEngineRpcModule.engine_getBlobsV4), SszRestPaths.PostBlobsV4, Gate(spec.IsEip7843Enabled)); // Bogota + Configure(nameof(IEngineRpcModule.engine_getPayloadV7), SszRestPaths.GetPayloads, GateWithWarn(spec.IsEip7805Enabled)); Configure(nameof(IEngineRpcModule.engine_newPayloadV6), SszRestPaths.PostPayloads, GateWithWarn(spec.IsEip7805Enabled)); Configure(nameof(IEngineRpcModule.engine_getInclusionListV1), SszRestPaths.GetInclusionList, GateWithWarn(spec.IsEip7805Enabled)); Configure(nameof(IEngineRpcModule.engine_forkchoiceUpdatedV5), SszRestPaths.PostForkchoice, GateWithWarn(spec.IsEip7805Enabled)); diff --git a/src/Nethermind/Nethermind.Merge.Plugin/Handlers/GetInclusionListTransactionsHandler.cs b/src/Nethermind/Nethermind.Merge.Plugin/Handlers/GetInclusionListTransactionsHandler.cs index e59e1edb140d..7417f765eaa9 100644 --- a/src/Nethermind/Nethermind.Merge.Plugin/Handlers/GetInclusionListTransactionsHandler.cs +++ b/src/Nethermind/Nethermind.Merge.Plugin/Handlers/GetInclusionListTransactionsHandler.cs @@ -2,6 +2,7 @@ // SPDX-License-Identifier: LGPL-3.0-only using Nethermind.Blockchain; +using Nethermind.Config; using Nethermind.Core; using Nethermind.Core.Crypto; using Nethermind.Core.Specs; @@ -20,14 +21,16 @@ namespace Nethermind.Merge.Plugin.Handlers; /// Supplies head state. The pool admits a sender's bucket on any one entry being ready, so only the account /// itself says where that sender's appendable run starts. /// +/// Supplies MAX_VERIFY_GAS_PER_TX, which bounds the frame transactions listed. public class GetInclusionListTransactionsHandler( ITxPool? txPool, IBlockTree blockTree, ISpecProvider specProvider, - IChainHeadInfoProvider chainHeadInfo) : IHandler + IChainHeadInfoProvider chainHeadInfo, + IBlocksConfig blocksConfig) : IHandler { private readonly InclusionListBuilder? _inclusionListBuilder = - txPool is null ? null : new(txPool, blockTree, specProvider, chainHeadInfo.ReadOnlyStateProvider); + txPool is null ? null : new(txPool, blockTree, specProvider, chainHeadInfo.ReadOnlyStateProvider, blocksConfig.FocilProfile2MaxVerifyGas); /// /// Block whose header fixes the next-block base fee the candidates are diff --git a/src/Nethermind/Nethermind.Merge.Plugin/Handlers/GetPayloadV6Handler.cs b/src/Nethermind/Nethermind.Merge.Plugin/Handlers/GetPayloadV6Handler.cs index b90b8df1ee45..b6870da16ec8 100644 --- a/src/Nethermind/Nethermind.Merge.Plugin/Handlers/GetPayloadV6Handler.cs +++ b/src/Nethermind/Nethermind.Merge.Plugin/Handlers/GetPayloadV6Handler.cs @@ -21,7 +21,7 @@ public class GetPayloadV6Handler( IBuilderOverridePolicy builderOverridePolicy) : GetPayloadHandlerBase(EngineApiVersions.GetPayload.V6, payloadPreparationService, specProvider, logManager, builderOverridePolicy) { - protected override bool ValidateFork(IReleaseSpec spec) => spec.BlockLevelAccessListsEnabled; + protected override bool ValidateFork(IReleaseSpec spec) => spec.BlockLevelAccessListsEnabled && !spec.IsEip7805Enabled; protected override GetPayloadV6Result GetPayloadResultFromBlock(IBlockProductionContext context) => new GetPayloadV6DirectResponse(context.CurrentBestBlock!, context.BlockFees, new BlobsBundleV2(context.CurrentBestBlock!), context.CurrentBestBlock!.ExecutionRequests!, ShouldOverrideBuilder(context.CurrentBestBlock!)); } diff --git a/src/Nethermind/Nethermind.Merge.Plugin/Handlers/GetPayloadV7Handler.cs b/src/Nethermind/Nethermind.Merge.Plugin/Handlers/GetPayloadV7Handler.cs new file mode 100644 index 000000000000..e10993eaee89 --- /dev/null +++ b/src/Nethermind/Nethermind.Merge.Plugin/Handlers/GetPayloadV7Handler.cs @@ -0,0 +1,24 @@ +// SPDX-FileCopyrightText: 2026 Demerzel Solutions Limited +// SPDX-License-Identifier: LGPL-3.0-only + +using Nethermind.Consensus.Producers; +using Nethermind.Core; +using Nethermind.Core.Specs; +using Nethermind.Logging; +using Nethermind.Merge.Plugin.BlockProduction; +using Nethermind.Merge.Plugin.Data; + +namespace Nethermind.Merge.Plugin.Handlers; + +/// engine_getPayloadV7: the Bogota payload with the builder's EIP-8369 inclusion-list claims. +public class GetPayloadV7Handler( + IPayloadPreparationService payloadPreparationService, + ISpecProvider specProvider, + ILogManager logManager, + IBuilderOverridePolicy builderOverridePolicy) + : GetPayloadHandlerBase(EngineApiVersions.GetPayload.V7, payloadPreparationService, specProvider, logManager, builderOverridePolicy) +{ + protected override bool ValidateFork(IReleaseSpec spec) => spec.IsEip7805Enabled; + + protected override GetPayloadV7Result GetPayloadResultFromBlock(IBlockProductionContext context) => new GetPayloadV7DirectResponse(context.CurrentBestBlock!, context.BlockFees, new BlobsBundleV2(context.CurrentBestBlock!), context.CurrentBestBlock!.ExecutionRequests!, ShouldOverrideBuilder(context.CurrentBestBlock!)); +} diff --git a/src/Nethermind/Nethermind.Merge.Plugin/Handlers/IInclusionListComplianceEvaluator.cs b/src/Nethermind/Nethermind.Merge.Plugin/Handlers/IInclusionListComplianceEvaluator.cs index 512e467aac71..2fdbe4c16e51 100644 --- a/src/Nethermind/Nethermind.Merge.Plugin/Handlers/IInclusionListComplianceEvaluator.cs +++ b/src/Nethermind/Nethermind.Merge.Plugin/Handlers/IInclusionListComplianceEvaluator.cs @@ -1,22 +1,20 @@ // SPDX-FileCopyrightText: 2026 Demerzel Solutions Limited // SPDX-License-Identifier: LGPL-3.0-only -using Nethermind.Core.Crypto; +using System.Threading; +using System.Threading.Tasks; +using Nethermind.Core; namespace Nethermind.Merge.Plugin.Handlers; -/// Answers an already-committed block's EIP-7805 inclusion-list compliance. -/// -/// Lets engine_forkchoiceUpdatedV5 derive inclusionListSatisfied for a VALID head from -/// the retained list when the head's engine_newPayloadV6 never produced an answer -/// (bogota.md). -/// +/// Runs one EIP-7805 inclusion check against a block whose execution is VALID. public interface IInclusionListComplianceEvaluator { - /// Evaluates compliance of the block identified by against - /// , without re-executing it. - /// Hash of a block this node has committed. - /// Aggregate inclusion list as RLP-encoded EIP-2718 entries. - /// null when the block, state, or execution gas dimensions needed to judge compliance are unavailable. - bool? TryEvaluate(Hash256 blockHash, byte[][] inclusionListTransactions); + /// Whether satisfies under , + /// without re-executing it. + /// A block this node executed as VALID, decoded from the request with its access list. + /// One decoded list per committee position. + /// The builder's committed omission claims. + /// null when the state or the execution gas counters needed to judge it are unavailable. + Task EvaluateAsync(Block block, Transaction[][] inclusionLists, OmissionClaim[] claims, CancellationToken cancellationToken); } diff --git a/src/Nethermind/Nethermind.Merge.Plugin/Handlers/InclusionChecks.cs b/src/Nethermind/Nethermind.Merge.Plugin/Handlers/InclusionChecks.cs new file mode 100644 index 000000000000..dbf21e4fa18e --- /dev/null +++ b/src/Nethermind/Nethermind.Merge.Plugin/Handlers/InclusionChecks.cs @@ -0,0 +1,61 @@ +// SPDX-FileCopyrightText: 2026 Demerzel Solutions Limited +// SPDX-License-Identifier: LGPL-3.0-only + +using System; +using System.Threading; +using System.Threading.Tasks; +using Nethermind.Consensus.Decoders; +using Nethermind.Core; +using Nethermind.Logging; +using Nethermind.Merge.Plugin.Data; + +namespace Nethermind.Merge.Plugin.Handlers; + +/// The EIP-7805 inclusion check engine_newPayloadV6 completes before answering VALID +/// (bogota.md § Inclusion checking). +public interface IInclusionChecks +{ + /// A payload whose execution is VALID, with every field newPayload set. + /// The verdict, or null when it cannot be decided, its state or execution gas counters being + /// unavailable, so the payload is never reported as satisfied or excused. + Task CheckAsync(ExecutionPayload executionPayload, byte[][][] inclusionLists, OmissionClaim[] claims, CancellationToken cancellationToken); +} + +/// +public sealed class InclusionChecks(IInclusionListComplianceEvaluator evaluator, ILogManager logManager) : IInclusionChecks +{ + private readonly ILogger _logger = logManager.GetClassLogger(); + + public async Task CheckAsync(ExecutionPayload executionPayload, byte[][][] inclusionLists, OmissionClaim[] claims, CancellationToken cancellationToken) + { + if (claims.Length == 0 && Array.TrueForAll(inclusionLists, list => list.Length == 0)) return true; + + Result block = executionPayload.TryGetBlock(); + if (block.IsError) + { + if (_logger.IsWarn) _logger.Warn($"Inclusion check cannot rebuild block {executionPayload.BlockHash}: {block.Error}"); + return null; + } + + bool? verdict; + try + { + verdict = await evaluator.EvaluateAsync(block.Data, InclusionListDecoder.DecodeLists(inclusionLists), claims, cancellationToken); + } + catch (OperationCanceledException) when (cancellationToken.IsCancellationRequested) + { + return null; + } + catch (Exception e) + { + if (_logger.IsError) _logger.Error($"Inclusion check for block {executionPayload.BlockHash} failed.", e); + return null; + } + + if (_logger.IsDebug) + _logger.Debug(verdict is null + ? $"Inclusion check for block {executionPayload.BlockHash} is undecidable without its state or execution gas counters." + : $"Inclusion check for block {executionPayload.BlockHash}: inclusionListSatisfied={verdict}."); + return verdict; + } +} diff --git a/src/Nethermind/Nethermind.Merge.Plugin/Handlers/InclusionListBuilder.cs b/src/Nethermind/Nethermind.Merge.Plugin/Handlers/InclusionListBuilder.cs index ad83da243c31..0576a6008999 100644 --- a/src/Nethermind/Nethermind.Merge.Plugin/Handlers/InclusionListBuilder.cs +++ b/src/Nethermind/Nethermind.Merge.Plugin/Handlers/InclusionListBuilder.cs @@ -9,12 +9,16 @@ using Nethermind.Core.Collections; using Nethermind.Core.Specs; using Nethermind.Evm.State; +using Nethermind.Evm.TransactionProcessing; using Nethermind.Int256; using Nethermind.TxPool; namespace Nethermind.Merge.Plugin.Handlers; -internal class InclusionListBuilder(ITxPool txPool, IBlockTree blockTree, ISpecProvider specProvider, IReadOnlyStateProvider headState) +/// EIP-7805 MAX_VERIFY_GAS_PER_TX, above which a frame transaction is no +/// Profile 2 candidate; 0 lifts the cap. +internal class InclusionListBuilder(ITxPool txPool, IBlockTree blockTree, ISpecProvider specProvider, IReadOnlyStateProvider headState, + ulong maxVerifyGasPerTx = Eip8369Constants.MaxVerifyGasPerTx) { // Conservative lower bound for an encoded transaction's size. private const int MinTransactionSizeBytes = 32; @@ -32,7 +36,8 @@ public InclusionListBytes GetInclusionList(BlockHeader? parent = null) /// Draws candidate transactions for the list, round-robin across the drawn senders. /// Restricted to each sender's appendable run, since nothing else could be appended. Drawn - /// uniformly, not by fee: a fee-ordered draw drops what a builder passes over. + /// uniformly, not by fee: a fee-ordered draw drops what a builder passes over. Once EIP-7805's Profile 2 is + /// active, each ready Profile 2 candidate frame transaction is drawn as a run of its own beside the senders. /// Not gated on pool revalidation: the ready-tx snapshot applies no per-transaction spec check, so around a /// fork the draw can include entries the new spec rejects — either because the pool's background revalidation /// is still catching up, or because the target block is the activation slot itself, whose timestamp is @@ -41,24 +46,24 @@ private ArrayPoolListRef SampleAppendableTxs(BlockHeader? parent) { const int capacity = SenderSampleCapacity; Random rnd = Random.Shared; - UInt256 baseFee = NextBlockBaseFee(parent); + parent ??= blockTree.Head?.Header; + IReleaseSpec? spec = NextBlockSpec(parent); + UInt256 baseFee = parent is null ? UInt256.Zero : BaseFeeCalculator.Calculate(parent, spec!); // Reservoir over senders rather than over their runs, so the pool's size costs no allocation and no // state read: only the drawn senders below pay for one. - using ArrayPoolListRef drawn = new(capacity); + using ArrayPoolListRef drawn = new(capacity); int seen = 0; - // The pool routes blob txs to separate storage this snapshot never reads. Frame txs can remain in - // mixed sender buckets and are removed below. - foreach (Transaction[] pending in txPool.GetPendingTransactionsBySenderWithReadyNonFrameTx(baseFee).Values) + foreach (Draw draw in Draws(parent, spec, baseFee)) { if (drawn.Count < capacity) { - drawn.Add(pending); + drawn.Add(draw); } else { int j = rnd.Next(seen + 1); - if (j < capacity) drawn[j] = pending; + if (j < capacity) drawn[j] = draw; } seen++; } @@ -76,9 +81,11 @@ private ArrayPoolListRef SampleAppendableTxs(BlockHeader? parent) try { using ArrayPoolListRef runs = new(capacity); - foreach (Transaction[] pending in drawn) + foreach (Draw draw in drawn) { - Run run = AppendableRun(pending, in baseFee, ref filtered); + Run run = draw.FrameCandidate is { } candidate + ? ReadyCandidateRun(candidate, ref filtered) + : AppendableRun(draw.Bucket!, in baseFee, ref filtered); if (run.Length > 0) runs.Add(run); } @@ -109,6 +116,53 @@ private ArrayPoolListRef SampleAppendableTxs(BlockHeader? parent) /// A sender's appendable run, as a range over its bucket or over the shared filtered buffer. private readonly record struct Run(Transaction[]? Bucket, int Start, int Length); + /// One reservoir entry: a sender's bucket, or a Profile 2 candidate frame transaction. + private readonly record struct Draw(Transaction[]? Bucket, Transaction? FrameCandidate); + + /// What the reservoir draws from: the senders with a ready non-frame transaction, then, once Profile 2 is + /// active, the pool's Profile 2 candidates. + private IEnumerable Draws(BlockHeader? parent, IReleaseSpec? spec, UInt256 baseFee) + { + // The pool routes blob txs to separate storage this snapshot never reads. Frame txs can remain in + // mixed sender buckets and are removed below. + foreach (Transaction[] pending in txPool.GetPendingTransactionsBySenderWithReadyNonFrameTx(baseFee).Values) + { + yield return new Draw(pending, null); + } + + if (parent is null || spec is null || !Eip8369Profile2.IsActive(spec)) yield break; + + foreach (Transaction tx in txPool.GetPendingTransactions()) + { + if (IsProfile2Candidate(tx, in baseFee, parent.Timestamp)) yield return new Draw(null, tx); + } + } + + /// Whether is a Profile 2 candidate worth listing, judged without reading state. + /// EIP-7805 § IL Building: a member should leave out a candidate whose expiry deadline is already behind + /// the target slot. The slot's timestamp is not known here, so only one at or behind the parent's is. + private bool IsProfile2Candidate(Transaction tx, in UInt256 baseFee, ulong parentTimestamp) => + tx.SupportsFrames + && tx.SenderAddress is not null + && tx.CanPayBaseFee(baseFee) + && Eip8369Profile2.Classify(tx, maxVerifyGasPerTx) == Profile2Exclusion.None + && Eip8369Profile2.VerifyBudgetCost(tx) <= Eip8369Constants.MaxVerifyGasPerIl + && !(FrameTxValidation.TryGetExpiryDeadline(tx, out ulong deadline) && deadline <= parentTimestamp); + + /// A drawn Profile 2 candidate as a run of its own, empty unless its nonce is the next one at the head. + /// An EIP-8250 keyed transaction is judged on its own keys, an account-domain one on the account nonce. + private Run ReadyCandidateRun(Transaction candidate, ref ArrayPoolListRef filtered) + { + Address sender = candidate.SenderAddress!; + bool ready = KeyedNonceManager.UsesKeyedNonce(candidate) + ? KeyedNonceManager.IsNonceSetValid(headState, sender, candidate.NonceKeys!, candidate.Nonce) + : headState.GetNonce(sender) == candidate.Nonce; + if (!ready) return default; + + filtered.Add(candidate); + return new Run(null, filtered.Count - 1, 1); + } + /// The transactions of the next block could append, in order. /// The pool vouches only that some bucket entry is ready, so the run is rebuilt here against the /// account: frame transactions removed, spent nonces skipped, anchored at the account's next nonce, cut at the @@ -161,14 +215,11 @@ private static ReadOnlySpan WithoutFrameTxs(Transaction[] bySender, return filtered.AsSpan().Slice(start, kept); } - /// The base fee the next block will charge. + /// The spec of the next block, which fixes its base fee and whether Profile 2 is active. /// Approximate at a fork boundary: the next timestamp is not derivable here, so the parent's - /// stands in and pre-fork EIP-1559 parameters are resolved for a post-fork block. - private UInt256 NextBlockBaseFee(BlockHeader? parent) - { - parent ??= blockTree.Head?.Header; - return parent is null ? UInt256.Zero : BaseFeeCalculator.Calculate(parent, specProvider.GetSpec(parent.Number + 1, parent.Timestamp)); - } + /// stands in and the pre-fork spec is resolved for a post-fork block. + private IReleaseSpec? NextBlockSpec(BlockHeader? parent) => + parent is null ? null : specProvider.GetSpec(parent.Number + 1, parent.Timestamp); private static InclusionListBytes EncodeTransactionsUpToLimit(in ArrayPoolListRef txs) { @@ -176,23 +227,32 @@ private static InclusionListBytes EncodeTransactionsUpToLimit(in ArrayPoolListRe try { int size = 0; + // EIP-7805 § IL Building: a member should keep its Profile 2 candidates' total VERIFY budget cost + // within MAX_VERIFY_GAS_PER_IL, which also has every one of them admitted whatever the fill's order. + ulong verifyBudget = Eip8369Constants.MaxVerifyGasPerIl; // The sample orders each sender's run by ascending nonce, so once one entry is skipped the rest // of that run is excused whenever the skipped one is absent: budget spent for no extra coverage. + // A frame candidate is a run of its own, so skipping it drops nothing else. HashSet? droppedSenders = null; foreach (Transaction tx in txs) { - if (droppedSenders is not null && droppedSenders.Contains(tx.SenderAddress!)) continue; + bool frameCandidate = tx.SupportsFrames; + if (!frameCandidate && droppedSenders is not null && droppedSenders.Contains(tx.SenderAddress!)) continue; + + ulong verifyCost = frameCandidate ? Eip8369Profile2.VerifyBudgetCost(tx) : 0; + if (verifyCost > verifyBudget) continue; ArrayPoolList txBytes = InclusionListDecoder.EncodePooled(tx); if (size + txBytes.Count > Eip7805Constants.MaxBytesPerInclusionList) { txBytes.Dispose(); - (droppedSenders ??= []).Add(tx.SenderAddress!); + if (!frameCandidate) (droppedSenders ??= []).Add(tx.SenderAddress!); continue; } size += txBytes.Count; + verifyBudget -= verifyCost; result.Add(txBytes); // No possible tx can fit in the remaining space. diff --git a/src/Nethermind/Nethermind.Merge.Plugin/Handlers/NewPayloadHandler.cs b/src/Nethermind/Nethermind.Merge.Plugin/Handlers/NewPayloadHandler.cs index 3f9473aa0df0..4c67b66b3651 100644 --- a/src/Nethermind/Nethermind.Merge.Plugin/Handlers/NewPayloadHandler.cs +++ b/src/Nethermind/Nethermind.Merge.Plugin/Handlers/NewPayloadHandler.cs @@ -17,7 +17,6 @@ using Nethermind.Consensus.Validators; using Nethermind.Core; using Nethermind.Core.BlockAccessLists; -using Nethermind.Core.Buffers; using Nethermind.Core.Exceptions; using Nethermind.Core.Caching; using Nethermind.Core.Crypto; @@ -33,7 +32,6 @@ using Nethermind.Merge.Plugin.InvalidChainTracker; using Nethermind.Merge.Plugin.Synchronization; using Nethermind.Serialization.FluentRlp; -using Nethermind.Serialization.Rlp; using Nethermind.State; using Nethermind.Synchronization; using Nethermind.TxPool; @@ -61,6 +59,7 @@ public sealed class NewPayloadHandler : IAsyncHandler? _latestBlocks; @@ -70,15 +69,6 @@ public sealed class NewPayloadHandler : IAsyncHandler _blockValidationTasks = new(); - /// The copies this handler handed to the processing queue that have not left it yet. - /// - /// The engine API runs one newPayload at a time, so a request finds here what the requests before it left - /// behind. The lock is uncontended then; it keeps the list whole on a node that serves newPayload through two - /// engine modules, each with its own request lock. - /// - private readonly List _queuedCopies = []; - private readonly Lock _queuedCopiesLock = new(); - private ulong _lastBlockNumber; private ulong _lastBlockGasLimit; private readonly bool _simulateBlockProduction; @@ -101,6 +91,7 @@ public NewPayloadHandler( ISpecProvider specProvider, ITxValidator txValidator, ILogManager logManager, + IProfile2EligibilityReplayer? profile2Replayer = null, TimeProvider? timeProvider = null, IBlockAccessListStore? blockAccessListStore = null) { @@ -118,6 +109,7 @@ public NewPayloadHandler( _blockAccessListStore = blockAccessListStore; _specProvider = specProvider; _txValidator = txValidator; + _profile2Replayer = profile2Replayer; _senderRecovery = senderRecovery; _logger = logManager.GetClassLogger(); _defaultProcessingOptions = receiptConfig.StoreReceipts ? ProcessingOptions.EthereumMerge | ProcessingOptions.StoreReceipts : ProcessingOptions.EthereumMerge; @@ -302,51 +294,20 @@ public async Task> HandleAsync(ExecutionPayload r } // we need to check if the head is greater than block.Number. In fast sync we could return Valid to CL without this if - // An IL is a per-call parameter not bound to block.Hash, so never short-circuit when one is supplied. - // Only a block this node executed is answered from the canonical marker: the IL arm reads state by root, - // which cannot tell this block's committed state from another block's with the same root. + // Only a block this node executed is answered from the canonical marker. bool isCanonicalBehindHead = _blockTree.IsOnMainChainBehindOrEqualHead(block.Header); - bool hasInclusionList = HasInclusionList(block); if (isCanonicalBehindHead && WasExecuted(block)) { - if (!hasInclusionList) + // A re-executed block is already marked processed, so it can become head before its restored state + // commits; wait for that commit before reading the state again. + if (IsVerdictServiceable(block) + || (await WriteReceivedIfWaiting(receivedLine, _processingQueue.WaitForExecutedCopyAsync(block.Hash!, RemainingBudget(deadline), _timeProvider)) && IsVerdictServiceable(block))) { - // A re-executed block is already marked processed, so it can become head before its restored state - // commits; wait for that commit before reading the state again. - if (IsVerdictServiceable(block) - || (await WriteReceivedIfWaiting(receivedLine, _processingQueue.WaitForExecutedCopyAsync(block.Hash!, RemainingBudget(deadline), _timeProvider)) && IsVerdictServiceable(block))) - { - if (_logger.IsInfo) _logger.Info($"Valid... A new payload ignored. Block {block.ToString(Block.Format.Short)} found in main chain."); - return NewPayloadV1Result.Valid(block.Hash); - } - - // Fall through: the ancestry check below decides whether re-execution is safe. + if (_logger.IsInfo) _logger.Info($"Valid... A new payload ignored. Block {block.ToString(Block.Format.Short)} found in main chain."); + return NewPayloadV1Result.Valid(block.Hash); } - else - { - // bogota.md newPayloadV6 (2.1): a VALID response must carry a compliance answer, so reuse a - // cached one only while the verdict is serviceable. - if (IsVerdictServiceable(block) && TryGetCachedResult(block, out ResultWrapper? cachedResult)) - { - if (_logger.IsInfo) _logger.Info($"Valid... A new payload with a known inclusion-list result. Block {block.ToString(Block.Format.Short)} found in main chain."); - return cachedResult; - } - // The re-execution restoring this state may still be committing, so wait for it before judging. - if (_stateReader.HasStateForBlock(block.Header) - || (await WriteReceivedIfWaiting(receivedLine, _processingQueue.WaitForExecutedCopyAsync(block.Hash!, RemainingBudget(deadline), _timeProvider)) && _stateReader.HasStateForBlock(block.Header))) - { - if (EvaluateInclusionListFromState(block) is { } fromState) - { - if (_logger.IsInfo) _logger.Info($"Valid... A new payload re-checked against its own state. Block {block.ToString(Block.Format.Short)} found in main chain."); - return fromState; - } - - // Fall through: only execution recovers the EIP-8037 dimensions this answer needs, and where - // re-executing is unsafe the ancestry check below answers SYNCING — bogota.md newPayloadV6 - // (2.2) leaves `inclusionListSatisfied` null there, which (2.1) would not allow for VALID. - } - } + // Fall through: the ancestry check below decides whether re-execution is safe. } // The parent may have been answered VALID a moment ago and still be committing: its processed flag and its @@ -443,11 +404,6 @@ public async Task> HandleAsync(ExecutionPayload r _invalidChainTracker.OnInvalidBlock(block.Hash!, block.ParentHash); return ResultWrapper.Success(BuildInvalidPayloadStatusV1(request, message)); } - case ValidationResult.InclusionListUnsatisfied: - { - if (_logger.IsInfo) _logger.Info($"Inclusion list unsatisfied. Result of {requestStr}."); - return NewPayloadV1Result.InclusionListUnsatisfied(block.Hash); - } case ValidationResult.Valid: { if (_logger.IsDebug) _logger.Debug($"Valid. Result of {requestStr}."); @@ -463,8 +419,6 @@ public async Task> HandleAsync(ExecutionPayload r private ResultWrapper ThrowUnknownValidationResult(ValidationResult result) => throw new InvalidOperationException($"Unknown validation result {result}."); - private static bool HasInclusionList(Block block) => block.InclusionListTransactions is { Length: > 0 }; - /// Whether this node executed , rather than sync placing it on the main chain unrun. private bool WasExecuted(Block block) => _blockTree.GetInfo(block.Number, block.Hash!).Info is { WasProcessed: true }; @@ -496,71 +450,61 @@ private bool WasExecuted(Block block) => private bool IsVerdictServiceable(Block block) => _stateReader.HasStateForBlock(block.Header) || _blockTree.IsOnMainChainBehindFinalized(block.Header); - // An absent IL digests to default, matching non-IL cache entries. - private static ValueHash256 ComputeInclusionListDigest(Block block) - { - if (block.InclusionListTransactions is not { Length: > 0 } il) return default; - - using ArrayPoolDisposableReturn _ = ArrayPoolDisposableReturn.Rent(il.Length * Keccak.Size, out byte[] buffer); - Span span = buffer.AsSpan(0, il.Length * Keccak.Size); - for (int i = 0; i < il.Length; i++) - (il[i].Hash ?? Keccak.Zero).Bytes.CopyTo(span.Slice(i * Keccak.Size, Keccak.Size)); - - return ValueKeccak.Compute(span); - } - - /// Answers an already-committed block's inclusion-list compliance without re-executing it. + /// /// - /// EIP-7805 appendability uses the transaction boundary. The validated BAL reverses finalization's - /// account changes; a field with no earlier BAL value is read from the parent state. - /// Null when required BAL or parent state is unavailable, or EIP-8037 leaves the gas dimensions undecidable. - /// The caller must fall through to execution rather than guess. - /// After cache loss or restart, even resending the current head can therefore answer SYNCING. + /// VALID is answered before the block's state commits, so the check first waits for its executed copy to + /// leave the processing queue. EIP-7805 judges appendability at the transaction boundary: the state the block + /// committed, read at its own state root, with the validated BAL reversing finalization's account changes and a + /// field with no earlier BAL value read from the parent state. Omission claims are fit against the gas its + /// execution recorded. Null when the BAL or parent state is unavailable. /// - private ResultWrapper? EvaluateInclusionListFromState(Block block) + public async Task EvaluateAsync(Block block, Transaction[][] inclusionLists, OmissionClaim[] claims, CancellationToken cancellationToken) { Hash256 hash = block.GetOrCalculateHash(); + if (!_stateReader.HasStateForBlock(block.Header)) + { + await _processingQueue.WaitUntilExecutedCopyRemovedAsync(hash).AsTask().WaitAsync(cancellationToken); + if (!_stateReader.HasStateForBlock(block.Header)) return null; + } + + cancellationToken.ThrowIfCancellationRequested(); // A decoded payload has no EIP-8037 dimensions, and neither the state root nor the header's // max(execution, state) carries them back, so without what execution recorded this would answer on a - // coarser gas rule than the processing path and could report real censorship as absent. + // coarser gas rule than execution and could report real censorship as absent. block.Header.GasUsedPerDimension = RecordedGasDimensions(hash); - bool? satisfied = IsInclusionListSatisfied(block, block.InclusionListTransactions!); - if (satisfied is null) return null; - - ValidationResult result = satisfied.Value ? ValidationResult.Valid : ValidationResult.InclusionListUnsatisfied; - - _latestBlocks?.Set(hash, new CachedPayloadResult(result, null, ComputeInclusionListDigest(block), block.Header.GasUsedPerDimension)); - return result == ValidationResult.Valid - ? NewPayloadV1Result.Valid(block.Hash) - : NewPayloadV1Result.InclusionListUnsatisfied(block.Hash); + block.GasUsedBeforeTransactions = RecordedGasUsedBefore(hash); + return IsInclusionListSatisfied(block, inclusionLists, claims); } - /// - /// Without EIP-8037 gas dimensions, answers only when every possible assignment gives the same verdict. - public bool? TryEvaluate(Hash256 blockHash, byte[][] inclusionListTransactions) - { - Block? block = _blockTree.FindBlock(blockHash, BlockTreeLookupOptions.TotalDifficultyNotNeeded); - if (block is null || !WasExecuted(block) || !_stateReader.HasStateForBlock(block.Header)) return null; - // Gas bounds must not mutate the tree's shared header while another request reads it. - block = block.WithReplacedBodyCloned(block.Body); - block.Header.GasUsedPerDimension = RecordedGasDimensions(blockHash); - - // Undecodable entries are dropped rather than failing the answer: a censoring proposer must not be - // able to escape the check by having one bad entry gossiped into the aggregate. - return IsInclusionListSatisfied(block, TxsDecoder.DecodeTxs(inclusionListTransactions, skipErrors: true).Transactions); - } - - private bool? IsInclusionListSatisfied(Block block, Transaction[] inclusionList) + /// A claim before the end of the payload is fit against the gas execution recorded before its index. Once + /// that record is gone it is judged at both bounds of that gas, none and the whole block's, and answered only when + /// they agree. Fitting more can only condemn more, so an unsatisfied verdict at the whole block's gas stands. + private bool? IsInclusionListSatisfied(Block block, Transaction[][] inclusionLists, OmissionClaim[] claims) { IReleaseSpec spec = _specProvider.GetSpec(block.Header); - _senderRecovery.RecoverData(inclusionList, spec, skipErrors: true); + _senderRecovery.RecoverData(InclusionLists.Distinct(inclusionLists), spec, skipErrors: true); - InclusionListCommittedState state = new(new SpecificBlockReadOnlyStateProvider(_stateReader, block.Header), + InclusionListCommittedState committed = new(new SpecificBlockReadOnlyStateProvider(_stateReader, block.Header), (uint)block.Transactions.Length + 1, ReadList, ReadParent); - bool? satisfied = spec.IsEip8037Enabled && block.Header.GasUsedPerDimension is null - ? EvaluateWithUnknownGasDimensions(block, inclusionList, state, spec) - : InclusionListValidator.IsSatisfied(block, inclusionList, state, spec, _txValidator); - return state.Available ? satisfied : null; + IReadOnlyStateProvider state = committed; + ulong transactionCount = (ulong)block.Transactions.Length; + bool earlyClaims = Eip8369Profile2.IsActive(spec) + && Array.Exists(claims, claim => claim.EvaluationIndex < transactionCount); + if (earlyClaims && block.GasUsedBeforeTransactions is { } recorded && recorded.Length == block.Transactions.Length) + return Answer(Evaluate(block, inclusionLists, claims, state, spec, _profile2Replayer, recorded)); + IProfile2EligibilityReplayer? replayer = _profile2Replayer; + if (earlyClaims) + { + state = new CachedAccountStateProvider(state); + replayer = replayer is null ? null : new RequestReplayer(replayer); + } + + bool? satisfied = Evaluate(block, inclusionLists, claims, state, spec, replayer, null); + if (satisfied is not true || !earlyClaims) return Answer(satisfied); + + return Answer(Evaluate(block, inclusionLists, claims, state, spec, replayer, new (ulong, ulong)[block.Transactions.Length]) is true ? true : null); + + bool? Answer(bool? verdict) => committed.Available ? verdict : null; ReadOnlyBlockAccessList? ReadList() { @@ -586,33 +530,113 @@ private static ValueHash256 ComputeInclusionListDigest(Block block) } } + private bool? Evaluate(Block block, Transaction[][] inclusionLists, OmissionClaim[] claims, IReadOnlyStateProvider state, IReleaseSpec spec, + IProfile2EligibilityReplayer? replayer, (ulong Execution, ulong State)[]? gasUsedBefore) => + spec.IsEip8037Enabled && block.Header.GasUsedPerDimension is null + ? EvaluateWithUnknownGasDimensions(block, inclusionLists, claims, state, spec, replayer, gasUsedBefore) + : InclusionListValidator.Evaluate(block, inclusionLists, state, spec, _txValidator, Eip8369Constants.MaxVerifyGasPerTx, claims, replayer, gasUsedBefore); + /// Answers only when every possible gas-dimension assignment gives the same verdict. /// Account reads are shared across the gas bounds. - private bool? EvaluateWithUnknownGasDimensions(Block block, Transaction[] inclusionList, IReadOnlyStateProvider state, IReleaseSpec spec) + private bool? EvaluateWithUnknownGasDimensions(Block block, Transaction[][] inclusionLists, OmissionClaim[] claims, IReadOnlyStateProvider state, IReleaseSpec spec, + IProfile2EligibilityReplayer? replayer, (ulong Execution, ulong State)[]? gasUsedBefore) { + state = state as CachedAccountStateProvider ?? new CachedAccountStateProvider(state); + replayer = replayer is null or RequestReplayer ? replayer : new RequestReplayer(replayer); // EIP-8037 stores max(execution, state). Appendability decreases as either used dimension increases. try { block.Header.GasUsedPerDimension = (block.GasUsed, block.GasUsed); - if (!InclusionListValidator.IsSatisfied(block, inclusionList, state, spec, _txValidator)) return false; + bool? atMaximum = InclusionListValidator.Evaluate(block, inclusionLists, state, spec, _txValidator, Eip8369Constants.MaxVerifyGasPerTx, claims, replayer, gasUsedBefore); + if (atMaximum is not true) return atMaximum; block.Header.GasUsedPerDimension = (block.GasUsed, 0); - if (!InclusionListValidator.IsSatisfied(block, inclusionList, state, spec, _txValidator)) return null; + if (InclusionListValidator.Evaluate(block, inclusionLists, state, spec, _txValidator, Eip8369Constants.MaxVerifyGasPerTx, claims, replayer, gasUsedBefore) is not true) return null; block.Header.GasUsedPerDimension = (0, block.GasUsed); - return InclusionListValidator.IsSatisfied(block, inclusionList, state, spec, _txValidator) ? true : null; + return InclusionListValidator.Evaluate(block, inclusionLists, state, spec, _txValidator, Eip8369Constants.MaxVerifyGasPerTx, claims, replayer, gasUsedBefore) is true ? true : null; } finally { - // Bounds must never escape as recorded execution totals, including through the payload cache. + // Bounds must never escape as recorded execution totals. block.Header.GasUsedPerDimension = null; } } + private sealed class RequestReplayer(IProfile2EligibilityReplayer inner) : IProfile2EligibilityReplayer + { + private readonly Dictionary<(Transaction Transaction, int Index), bool> _verdicts = []; + + public bool AreSignaturesValid(Transaction transaction, IReleaseSpec spec) => inner.AreSignaturesValid(transaction, spec); + + public bool?[] AreEligible(Block block, IReadOnlyList<(Transaction Transaction, int Index)> requests, IReleaseSpec spec) + { + List<(Transaction Transaction, int Index)> missing = []; + foreach ((Transaction transaction, int index) in requests) + if (!_verdicts.ContainsKey((transaction, index))) missing.Add((transaction, index)); + + if (missing.Count > 0) + { + bool?[] evaluated = inner.AreEligible(block, missing, spec); + for (int i = 0; i < missing.Count; i++) + if (evaluated[i] is { } verdict) _verdicts[missing[i]] = verdict; + } + + bool?[] verdicts = new bool?[requests.Count]; + for (int i = 0; i < requests.Count; i++) + verdicts[i] = _verdicts.TryGetValue(requests[i], out bool known) ? known : null; + return verdicts; + } + } + + /// Shares account reads across one request's inclusion-list checks. + private sealed class CachedAccountStateProvider(IReadOnlyStateProvider state) : IReadOnlyStateProvider + { + private Dictionary? _accounts; + + /// + public Hash256 StateRoot => state.StateRoot; + + /// + public bool TryGetAccount(Address address, out AccountStruct account) + { + _accounts ??= []; + if (!_accounts.TryGetValue(address, out (bool Exists, AccountStruct Account) cached)) + { + bool exists = state.TryGetAccount(address, out account); + cached = (exists, account); + _accounts.Add(address, cached); + } + account = cached.Account; + return cached.Exists; + } + + /// + public ReadOnlyMemory GetCode(Address address) + { + TryGetAccount(address, out AccountStruct account); + return !account.HasCode ? Array.Empty() : state.GetCode(account.CodeHash); + } + + /// + public ReadOnlyMemory GetCode(in ValueHash256 codeHash) => state.GetCode(in codeHash); + + /// + public bool IsContract(Address address) => state.IsContract(address); + + /// + public bool AccountExists(Address address) => state.AccountExists(address); + + /// + public bool IsDeadAccount(Address address) => state.IsDeadAccount(address); + + /// + public void Get(in StorageCell storageCell, out UInt256 value) => state.Get(in storageCell, out value); + } + /// The EIP-8037 gas dimensions execution recorded for the block names. - /// Two in-memory copies outlive the payload the dimensions were recorded from — the cached answer, - /// which a resend under a different inclusion list misses only once evicted, and the tree's own block, which - /// BranchProcessor stamps. Null once neither is left: nothing persists them, and + /// Two in-memory copies outlive the payload the dimensions were recorded from — the cached answer and + /// the tree's own block, which BranchProcessor stamps. Null once neither is left: nothing persists them, and /// reduces them to a maximum that cannot be inverted. private (ulong Execution, ulong State)? RecordedGasDimensions(Hash256 hash) => (_latestBlocks is not null && _latestBlocks.TryGet(hash, out CachedPayloadResult cached) @@ -620,24 +644,10 @@ private static ValueHash256 ComputeInclusionListDigest(Block block) : null) ?? _blockTree.FindHeader(hash, BlockTreeLookupOptions.TotalDifficultyNotNeeded)?.GasUsedPerDimension; - // Only a "valid block" outcome short-circuits: never resurrect a stale Invalid/Syncing for a block - // the tree treats as canonical. - private bool TryGetCachedResult(Block block, [NotNullWhen(true)] out ResultWrapper? result) - { - result = null; - if (_latestBlocks is null - || !_latestBlocks.TryGet(block.GetOrCalculateHash(), out CachedPayloadResult cached) - || cached.InclusionListDigest != ComputeInclusionListDigest(block)) - return false; - - result = cached.Result switch - { - ValidationResult.Valid => NewPayloadV1Result.Valid(block.Hash), - ValidationResult.InclusionListUnsatisfied => NewPayloadV1Result.InclusionListUnsatisfied(block.Hash), - _ => null - }; - return result is not null; - } + /// The gas execution recorded the block names using before each of its transactions, + /// kept only by the cached answer. + private (ulong Execution, ulong State)[]? RecordedGasUsedBefore(Hash256 hash) => + _latestBlocks is not null && _latestBlocks.TryGet(hash, out CachedPayloadResult cached) ? cached.GasUsedBefore : null; /// Records a block rejected before BranchProcessor ever runs. /// @@ -766,16 +776,14 @@ private TimeSpan RemainingBudget(long deadline) private async Task<(ValidationResult, string?)> ValidateBlockAndProcess(Block block, BlockHeader parent, ProcessingOptions processingOptions, long deadline, ParallelUnbalancedWork.WorkerGroup workers, ReceivedLine? receivedLine) { - ValueHash256 ilDigest = ComputeInclusionListDigest(block); - ValidationCompletion? completion = null; ValidationResult TryCacheResult(ValidationResult result, string? errorMessage) { // Cache terminal outcomes only; SYNCING isn't terminal (we haven't processed the block yet). - if (result is ValidationResult.Invalid or ValidationResult.Valid or ValidationResult.InclusionListUnsatisfied) + if (result is ValidationResult.Invalid or ValidationResult.Valid) { - _latestBlocks?.Set(block.GetOrCalculateHash(), new CachedPayloadResult(result, errorMessage, ilDigest, block.Header.GasUsedPerDimension)); + _latestBlocks?.Set(block.GetOrCalculateHash(), new CachedPayloadResult(result, errorMessage, block.Header.GasUsedPerDimension, block.GasUsedBeforeTransactions)); // The verdict is given before the commit, so the block can be gone without committing by the time // this runs. Whichever of the two marks the completion first, the other takes the entry back out. if (completion?.MarkAnswerCached() == false) _latestBlocks?.Delete(block.GetOrCalculateHash()); @@ -789,7 +797,6 @@ ValidationResult TryCacheResult(ValidationResult result, string? errorMessage) // If duplicate, reuse results. Invalidity is permanent; any other verdict only while it stays serviceable. if (_latestBlocks is not null && _latestBlocks.TryGet(block.Hash!, out CachedPayloadResult cachedResult) - && cachedResult.InclusionListDigest == ilDigest && (cachedResult.Result == ValidationResult.Invalid || IsVerdictServiceable(block))) { if (cachedResult.Result == ValidationResult.Invalid) @@ -823,17 +830,18 @@ ValidationResult TryCacheResult(ValidationResult result, string? errorMessage) { // The suggest goes on without this request, and a block it adds would otherwise sit in the tree // unqueued until the CL re-sends the payload. - TrackQueuedCopy(block.Hash!, inclusionListDigest: null, EnqueueOnceAddedAsync(suggest, block, processingOptions, blockProcessed, workers)); + _ = EnqueueOnceAddedAsync(suggest, block, processingOptions, blockProcessed, workers); throw; } // A payload sent again while its first copy is between verdict and removal is known, and marked processed // only part way through that window. Queued again before the copy is gone it would be skipped as not - // better than head and answered INVALID, or answered by the copy's removal without its own inclusion - // list ever judged, so let the first copy finish first. A copy already gone costs nothing here. + // better than head and answered INVALID, so let the first copy finish first. Only a copy that has its + // verdict is worth waiting for; one that is merely queued is left to answer this request through the + // shared completion, and a copy already gone costs nothing here. if (addResult == AddBlockResult.AlreadyKnown) { - Task removed = WaitForEarlierCopiesAsync(block.Hash!, ilDigest); + Task removed = _processingQueue.WaitUntilRemovedAsync(block.Hash!, executedOnly: true).AsTask(); if (await WriteReceivedIfWaiting(receivedLine, Task.WhenAny(removed, timeoutTask)) == timeoutTask) throw new TimeoutException(); // The first copy's own verdict and removal land on whatever completion is registered for the hash, // so if they consumed this one it must not stand in for the answer to this request. A fault is that @@ -855,9 +863,8 @@ ValidationResult TryCacheResult(ValidationResult result, string? errorMessage) // the block was processed and returned invalid but this wasn't saved anywhere or the block was // processed and marked as valid. // if marked as processed by the block tree then return VALID, otherwise null so that it's processed a few lines below - // an IL-bearing payload bypasses this shortcut so that the current call's IL is re-validated // Re-read serviceability: the commit this block awaits can land after the cache check above. - AddBlockResult.AlreadyKnown => !HasInclusionList(block) && WasExecuted(block) && IsVerdictServiceable(block) + AddBlockResult.AlreadyKnown => WasExecuted(block) && IsVerdictServiceable(block) ? ValidationResult.Valid : null, _ => null @@ -883,7 +890,7 @@ ValidationResult TryCacheResult(ValidationResult result, string? errorMessage) // Enqueue, on the caller's thread, and hands it back only once the block is committed - after the // verdict this request only needs to see. The processing loop raises its own thread's priority, so // nothing is lost by not inheriting this one's. A failure to enqueue fails the request (EnqueueAsync). - TrackQueuedCopy(block.Hash!, ilDigest, Task.Run(() => EnqueueAsync(block, processingOptions, blockProcessed, workers))); + _ = Task.Run(() => EnqueueAsync(block, processingOptions, blockProcessed, workers)); // The block is on its way to the queue, so the line costs the verdict nothing from here. receivedLine?.Write(); (result, validationMessage) = await blockProcessed.Task.TimeoutOn(timeoutTask, cts); @@ -924,11 +931,9 @@ private void GetProcessingQueueOnBlockExecuted(object? o, BlockVerdictEventArgs // that fails next needs the completion to stop that entry from standing. if (!_blockValidationTasks.TryGetValue(e.BlockHash, out ValidationCompletion? blockProcessed)) return; - ValidationResult result = e.ProcessingResult == ProcessingResult.InclusionListUnsatisfied - ? ValidationResult.InclusionListUnsatisfied - : ValidationResult.Valid; blockProcessed.MarkVerdictGiven(); - if (blockProcessed.TrySetResult((result, null))) e.Answered = true; + // An unsatisfied inclusion list is no execution failure, and this handler checks inclusion apart from execution. + if (blockProcessed.TrySetResult((ValidationResult.Valid, null))) e.Answered = true; } /// Whether the tree has the block as processed, so a removal that failed was some other copy's. @@ -940,43 +945,6 @@ private bool HasCommitted(Hash256 blockHash) => _blockTree.FindHeader(blockHash, BlockTreeLookupOptions.TotalDifficultyNotNeeded) is { Number: ulong number } && _blockTree.WasProcessed(number, blockHash); - /// - /// Waits out the copies of the block whose verdict cannot answer a request carrying . - /// A copy this handler queued with the same list answers through the shared completion, so only one that already - /// has its verdict is waited for. A copy with another list is waited for from the moment its request handed it - /// over, which is before the queue has taken it. So is a copy still waiting on a suggest that outlived its request, - /// whatever its list. A copy queued by sync is untracked and counts as carrying no list. - /// - private Task WaitForEarlierCopiesAsync(Hash256 blockHash, in ValueHash256 ilDigest) - { - bool tracked = false; - List? anotherList = null; - lock (_queuedCopiesLock) - { - foreach (QueuedCopy copy in _queuedCopies) - { - if (copy.BlockHash != blockHash || copy.Left.IsCompleted) continue; - tracked = true; - if (copy.InclusionListDigest != ilDigest) (anotherList ??= []).Add(copy.Left); - } - } - - bool carriesSameList = anotherList is null && (tracked || ilDigest == default); - Task inQueue = _processingQueue.WaitUntilRemovedAsync(blockHash, executedOnly: carriesSameList).AsTask(); - if (anotherList is null) return inQueue; - anotherList.Add(inQueue); - return Task.WhenAll(anotherList); - } - - private void TrackQueuedCopy(Hash256 blockHash, ValueHash256? inclusionListDigest, Task left) - { - lock (_queuedCopiesLock) - { - _queuedCopies.RemoveAll(static copy => copy.Left.IsCompleted); - _queuedCopies.Add(new QueuedCopy(blockHash, inclusionListDigest, left)); - } - } - private async Task EnqueueOnceAddedAsync(Task suggest, Block block, ProcessingOptions processingOptions, ValidationCompletion blockProcessed, ParallelUnbalancedWork.WorkerGroup workers) { try @@ -1000,7 +968,6 @@ private async Task EnqueueAsync(Block block, ProcessingOptions processingOptions ValueTask enqueue; using (workers.Enter()) enqueue = _processingQueue.Enqueue(block, processingOptions); await enqueue; - await _processingQueue.WaitUntilRemovedAsync(block.Hash!); } catch (Exception e) { @@ -1019,7 +986,7 @@ private void GetProcessingQueueOnBlockRemoved(object? o, BlockRemovedEventArgs e // answered: the commit, the prewarm join and the BlockProcessed subscribers all arrive here as an exception, // including the one kind that would otherwise have been reported as the block being invalid. Any of them // leaves a VALID that was already given standing for a block that is not there. - bool failed = e.ProcessingResult is not (ProcessingResult.Success or ProcessingResult.InclusionListUnsatisfied); + bool failed = e.ProcessingResult is not ProcessingResult.Success; bool found = _blockValidationTasks.TryRemove(e.BlockHash, out ValidationCompletion? blockProcessed); // The completion that received the verdict arbitrates with its own request over the cache entry, below. @@ -1050,7 +1017,6 @@ private void GetProcessingQueueOnBlockRemoved(object? o, BlockRemovedEventArgs e { ProcessingResult.Success => ValidationResult.Valid, ProcessingResult.ProcessingError => ValidationResult.Invalid, - ProcessingResult.InclusionListUnsatisfied => ValidationResult.InclusionListUnsatisfied, _ => null }; @@ -1138,8 +1104,7 @@ internal enum ValidationResult { Invalid, Valid, - Syncing, - InclusionListUnsatisfied + Syncing } /// One request's completion, and the arbiter of whether its answer may stay cached. @@ -1172,20 +1137,13 @@ private sealed class ValidationCompletion() public bool MarkBlockUncommitted() => Interlocked.Exchange(ref _state, Uncommitted) == Cached; } - /// A copy this handler handed to the processing queue and the inclusion list it carries, so a resend knows whether that copy's verdict is its own. - /// - /// Null for a copy handed over while its suggest was still pending: sync may add the block first and queue a copy - /// without the list, so no resend may take the verdict that follows for its own. - /// - /// Completes once the copy is out of the queue, or never got into it. - private readonly record struct QueuedCopy(Hash256 BlockHash, ValueHash256? InclusionListDigest, Task Left); - - // The IL digest disambiguates a resubmission of the same block with a different, per-call IL. - /// What execution recorded for this block, so a re-validation under a - /// different inclusion list judges appendability on the same EIP-8037 gas the processing path did. + /// What execution recorded for this block, so a deferred inclusion check + /// judges appendability on the same EIP-8037 gas execution did. + /// The gas execution recorded before each transaction, which an omission claim before + /// the end of the payload is fit against. private readonly record struct CachedPayloadResult( ValidationResult Result, string? Message, - ValueHash256 InclusionListDigest, - (ulong Execution, ulong State)? GasUsedPerDimension); + (ulong Execution, ulong State)? GasUsedPerDimension, + (ulong Execution, ulong State)[]? GasUsedBefore); } diff --git a/src/Nethermind/Nethermind.Merge.Plugin/Handlers/NewPayloadWithWitnessHandler.cs b/src/Nethermind/Nethermind.Merge.Plugin/Handlers/NewPayloadWithWitnessHandler.cs index 7f22db4f67f6..c58d07071a4c 100644 --- a/src/Nethermind/Nethermind.Merge.Plugin/Handlers/NewPayloadWithWitnessHandler.cs +++ b/src/Nethermind/Nethermind.Merge.Plugin/Handlers/NewPayloadWithWitnessHandler.cs @@ -59,8 +59,7 @@ public Task> HandleAsync(ExecutionP payload.ParentBeaconBlockRoot, payload.ExecutionRequests)); - /// Inclusion-list compliance is not part of the witness contract, so the V5 response shape is - /// kept and callers read compliance for this head off engine_forkchoiceUpdatedV5. + /// Inclusion is not part of the witness contract, so the V5 response shape is kept. public Task> HandleAsync(InclusionListExecutionPayloadParams request) => HandleAsync( request, @@ -72,7 +71,8 @@ static async (module, payload) => payload.BlobVersionedHashes!, payload.ParentBeaconBlockRoot, payload.ExecutionRequests, - payload.InclusionListTransactions); + payload.InclusionLists, + payload.OmissionClaims); return ResultWrapper.From(result); }); diff --git a/src/Nethermind/Nethermind.Merge.Plugin/IEngineRpcModule.Bogota.cs b/src/Nethermind/Nethermind.Merge.Plugin/IEngineRpcModule.Bogota.cs index 0eabc35581e1..3bb69404420f 100644 --- a/src/Nethermind/Nethermind.Merge.Plugin/IEngineRpcModule.Bogota.cs +++ b/src/Nethermind/Nethermind.Merge.Plugin/IEngineRpcModule.Bogota.cs @@ -4,6 +4,7 @@ using System.Collections; using System.Threading.Tasks; using Nethermind.Consensus.Producers; +using Nethermind.Core; using Nethermind.Core.Crypto; using Nethermind.JsonRpc; using Nethermind.JsonRpc.Modules; @@ -21,22 +22,28 @@ public partial interface IEngineRpcModule : IRpcModule Task> engine_getInclusionListV1(Hash256? parentBlockHash = null); [JsonRpcMethod( - Description = "Verifies the payload according to the execution environment rules and returns the verification status (including inclusion-list compliance) and hash of the last valid block.", + Description = "Returns the most recent version of an execution payload, with the build's EIP-7805 omission claims.", IsSharable = true, IsImplemented = true)] - Task> engine_newPayloadV6(ExecutionPayloadV4 executionPayload, Hash256?[] blobVersionedHashes, Hash256? parentBeaconBlockRoot, byte[][]? executionRequests, byte[][]? inclusionListTransactions); + Task> engine_getPayloadV7(byte[] payloadId); + + [JsonRpcMethod( + Description = "Verifies the payload according to the execution environment rules and returns its execution status, with the EIP-7805 verdict of the separate inclusion lists under the builder's omission claims.", + IsSharable = true, + IsImplemented = true)] + Task> engine_newPayloadV6(ExecutionPayloadV4 executionPayload, Hash256?[] blobVersionedHashes, Hash256? parentBeaconBlockRoot, byte[][]? executionRequests, byte[][][]? inclusionLists, OmissionClaim[]? omissionClaims); [JsonRpcMethod( Description = "Verifies the payload according to the execution environment rules and returns the verification status, hash of the last valid block, and the execution witness when the payload is valid.", IsSharable = true, IsImplemented = true)] - Task> engine_newPayloadWithWitnessV6(ExecutionPayloadV4 executionPayload, Hash256?[] blobVersionedHashes, Hash256? parentBeaconBlockRoot, byte[][]? executionRequests, byte[][]? inclusionListTransactions); + Task> engine_newPayloadWithWitnessV6(ExecutionPayloadV4 executionPayload, Hash256?[] blobVersionedHashes, Hash256? parentBeaconBlockRoot, byte[][]? executionRequests, byte[][][]? inclusionLists, OmissionClaim[]? omissionClaims); [JsonRpcMethod( Description = "Applies fork choice and starts building a new block if payload attributes are present.", IsSharable = true, IsImplemented = true)] - Task> engine_forkchoiceUpdatedV5( + Task> engine_forkchoiceUpdatedV5( ForkchoiceStateV1 forkchoiceState, PayloadAttributes? payloadAttributes = null, [JsonRpcParameter(ConverterType = typeof(BlobCellBitArrayConverter))] BitArray? custodyColumns = null); diff --git a/src/Nethermind/Nethermind.Merge.Plugin/MergePlugin.cs b/src/Nethermind/Nethermind.Merge.Plugin/MergePlugin.cs index 5f87bb8c2422..57b3af8333e4 100644 --- a/src/Nethermind/Nethermind.Merge.Plugin/MergePlugin.cs +++ b/src/Nethermind/Nethermind.Merge.Plugin/MergePlugin.cs @@ -182,9 +182,11 @@ protected override void Load(ContainerBuilder builder) => builder .AddSingleton, GetPayloadV4Handler>() .AddSingleton, GetPayloadV5Handler>() .AddSingleton, GetPayloadV6Handler>() + .AddSingleton, GetPayloadV7Handler>() .AddSingleton() .Bind, NewPayloadHandler>() .Bind() + .AddSingleton() .AddSingleton() .AddDecorator() .AddSingleton, IReadOnlyList>, GetPayloadBodiesByHashV1Handler>() diff --git a/src/Nethermind/Nethermind.Merge.Plugin/SszRest/Handlers/ForkchoiceUpdatedV5SszHandler.cs b/src/Nethermind/Nethermind.Merge.Plugin/SszRest/Handlers/ForkchoiceUpdatedV5SszHandler.cs deleted file mode 100644 index 90593a63dee7..000000000000 --- a/src/Nethermind/Nethermind.Merge.Plugin/SszRest/Handlers/ForkchoiceUpdatedV5SszHandler.cs +++ /dev/null @@ -1,56 +0,0 @@ -// SPDX-FileCopyrightText: 2026 Demerzel Solutions Limited -// SPDX-License-Identifier: LGPL-3.0-only - -using System.Collections; -using System; -using System.Buffers; -using System.Threading.Tasks; -using Microsoft.AspNetCore.Http; -using Nethermind.Consensus.Producers; -using Nethermind.Core; -using Nethermind.Core.Specs; -using Nethermind.JsonRpc; -using Nethermind.Merge.Plugin.Data; - -namespace Nethermind.Merge.Plugin.SszRest.Handlers; - -/// SSZ-REST equivalent of engine_forkchoiceUpdatedV5. -/// Dedicated rather than a descriptor -/// because V5 alone returns . -public sealed class ForkchoiceUpdatedV5SszHandler(IEngineRpcModule engineModule, ISpecProvider specProvider) : SszEndpointHandlerBase -{ - public override string HttpMethod => "POST"; - public override string Resource => SszRestPaths.Forkchoice; - public override int? Version => EngineApiVersions.Fcu.V5; - - public override async Task HandleAsync(HttpContext ctx, int version, ReadOnlyMemory extra, ReadOnlySequence body) - { - ForkchoiceUpdatedV5RequestWire.Decode(body, out ForkchoiceUpdatedV5RequestWire wire); - - if (GetForkMismatchMessage(ctx, ForkchoiceUpdatedHelpers.FirstTimestamp(wire.PayloadAttributes)) is { } mismatch) - { - await WriteErrorAsync(ctx, StatusCodes.Status400BadRequest, mismatch, MergeErrorCodes.UnsupportedFork); - return; - } - - ForkchoiceStateV1 state = SszCodec.ForkchoiceStateV1FromWire(wire.ForkchoiceState); - PayloadAttributes? attrs = wire.PayloadAttributes is { Length: > 0 } a ? SszCodec.PayloadAttributesFromWire(a[0]) : null; - BitArray? custody = wire.CustodyColumns is { Length: > 0 } c ? c[0].Bits : null; - - ResultWrapper result = await engineModule.engine_forkchoiceUpdatedV5(state, attrs, custody); - await WriteSszResultAsync(ctx, result, SszCodec.EncodeForkchoiceUpdatedResponseV2); - } - - // Mirrors ForkchoiceUpdatedSszHandler's fork check (that handler is generic over V1-returning descriptors). - private string? GetForkMismatchMessage(HttpContext ctx, ulong? timestamp) - { - if (!timestamp.HasValue || GetRequestedFork(ctx) is not { } requestedFork) - return null; - - IReleaseSpec payloadSpec = specProvider.GetSpec(ForkActivation.TimestampOnly(timestamp.Value)); - string payloadForkSegment = SszRestPaths.GetEngineApiForkName(payloadSpec); - return string.Equals(payloadForkSegment, requestedFork, StringComparison.OrdinalIgnoreCase) - ? null - : $"Eth-Execution-Version fork '{requestedFork}' does not match the fork for timestamp {timestamp.Value}"; - } -} diff --git a/src/Nethermind/Nethermind.Merge.Plugin/SszRest/Handlers/NewPayloadV6SszHandler.cs b/src/Nethermind/Nethermind.Merge.Plugin/SszRest/Handlers/NewPayloadV6SszHandler.cs index b4a8ad70a6e3..9745a5e19bd9 100644 --- a/src/Nethermind/Nethermind.Merge.Plugin/SszRest/Handlers/NewPayloadV6SszHandler.cs +++ b/src/Nethermind/Nethermind.Merge.Plugin/SszRest/Handlers/NewPayloadV6SszHandler.cs @@ -29,7 +29,8 @@ public override async Task HandleAsync(HttpContext ctx, int version, ReadOnlyMem SszCodec.GetBlobVersionedHashes(ep), wire.ParentBeaconBlockRoot, wire.ExecutionRequests.ToExecutionRequests(), - wire.InclusionListTransactions.ToExecutionRequests()); + wire.InclusionLists.ToInclusionLists(), + wire.OmissionClaims.ToClaims()); await WriteSszResultAsync(ctx, result, SszCodec.EncodePayloadStatusV2); } } diff --git a/src/Nethermind/Nethermind.Merge.Plugin/SszRest/Handlers/SszRestPaths.cs b/src/Nethermind/Nethermind.Merge.Plugin/SszRest/Handlers/SszRestPaths.cs index 6e15e9b4606d..940756b3e347 100644 --- a/src/Nethermind/Nethermind.Merge.Plugin/SszRest/Handlers/SszRestPaths.cs +++ b/src/Nethermind/Nethermind.Merge.Plugin/SszRest/Handlers/SszRestPaths.cs @@ -141,7 +141,7 @@ public static ResourceScoping GetScoping(ReadOnlySpan resource) [PayloadBodiesByRange] = static spec => spec.EngineApiPayloadBodiesByRangeVersion, [InclusionList] = static spec => spec.IsEip7805Enabled ? 1 : null, // Like the POST witness endpoint: the getPayload version, from the EIP-7928 fork onward. - [BuiltPayloadWithWitness] = static spec => spec.IsEip7928Enabled ? spec.EngineApiGetPayloadVersion : null, + [BuiltPayloadWithWitness] = static spec => spec.IsEip7928Enabled && !spec.IsEip7805Enabled ? spec.EngineApiGetPayloadVersion : null, }.ToFrozenDictionary(StringComparer.OrdinalIgnoreCase); /// Every recognized fork-scoped (HTTP method, resource) pair, derived from the tables above. diff --git a/src/Nethermind/Nethermind.Merge.Plugin/SszRest/Handlers/SszVersionDescriptors.cs b/src/Nethermind/Nethermind.Merge.Plugin/SszRest/Handlers/SszVersionDescriptors.cs index 18f30fbdf4a9..fbf9d9976c73 100644 --- a/src/Nethermind/Nethermind.Merge.Plugin/SszRest/Handlers/SszVersionDescriptors.cs +++ b/src/Nethermind/Nethermind.Merge.Plugin/SszRest/Handlers/SszVersionDescriptors.cs @@ -93,7 +93,8 @@ public static Task> Call(IEngineRpc public static Task> Call(IEngineRpcModule engine, in NewPayloadV6RequestWire wire) { ExecutionPayloadV4 ep = wire.ExecutionPayload.AsExecutionPayload(); - return engine.engine_newPayloadWithWitnessV6(ep, SszCodec.GetBlobVersionedHashes(ep), wire.ParentBeaconBlockRoot, wire.ExecutionRequests.ToExecutionRequests(), wire.InclusionListTransactions.ToExecutionRequests()); + return engine.engine_newPayloadWithWitnessV6(ep, SszCodec.GetBlobVersionedHashes(ep), wire.ParentBeaconBlockRoot, wire.ExecutionRequests.ToExecutionRequests(), + wire.InclusionLists.ToInclusionLists(), wire.OmissionClaims.ToClaims()); } } @@ -168,6 +169,20 @@ public static Task> Call(IEngineRpcModu ForkchoiceUpdatedHelpers.FirstTimestamp(wire.PayloadAttributes); } +public readonly struct ForkchoiceUpdatedDescriptorV5 : IForkchoiceUpdatedVersion +{ + public static int VersionNumber => EngineApiVersions.Fcu.V5; + public static Task> Call(IEngineRpcModule engine, in ForkchoiceUpdatedV5RequestWire wire) + { + ForkchoiceStateV1 state = SszCodec.ForkchoiceStateV1FromWire(wire.ForkchoiceState); + PayloadAttributes? attrs = wire.PayloadAttributes is { Length: > 0 } a ? SszCodec.PayloadAttributesFromWire(a[0]) : null; + BitArray? custody = wire.CustodyColumns is { Length: > 0 } c ? c[0].Bits : null; + return engine.engine_forkchoiceUpdatedV5(state, attrs, custody); + } + public static ulong? GetTimestamp(in ForkchoiceUpdatedV5RequestWire wire) => + ForkchoiceUpdatedHelpers.FirstTimestamp(wire.PayloadAttributes); +} + // Paris (V1 routing) needs block_value, which engine_getPayloadV1 doesn't return — call V2. public readonly struct GetPayloadDescriptorV1 : IGetPayloadVersion { @@ -223,6 +238,15 @@ public static int Encode(GetPayloadV6Result result, IBufferWriter writer) => SszCodec.EncodeGetPayloadV6Response(result, writer); } +public readonly struct GetPayloadDescriptorV7 : IGetPayloadVersion +{ + public static int VersionNumber => EngineApiVersions.GetPayload.V7; + public static Task> Call(IEngineRpcModule engine, byte[] id) + => engine.engine_getPayloadV7(id); + public static int Encode(GetPayloadV7Result result, IBufferWriter writer) + => SszCodec.EncodeGetPayloadV7Response(result, writer); +} + public interface IPayloadBodiesByHashVersion where TResult : class { static abstract int VersionNumber { get; } diff --git a/src/Nethermind/Nethermind.Merge.Plugin/SszRest/SszCodec.cs b/src/Nethermind/Nethermind.Merge.Plugin/SszRest/SszCodec.cs index 762e99980c21..e41e8af517ba 100644 --- a/src/Nethermind/Nethermind.Merge.Plugin/SszRest/SszCodec.cs +++ b/src/Nethermind/Nethermind.Merge.Plugin/SszRest/SszCodec.cs @@ -51,13 +51,6 @@ private static PayloadStatusV2Wire BuildPayloadStatusV2Wire(PayloadStatusV2 ps) }; } - public static int EncodeForkchoiceUpdatedResponseV2(ForkchoiceUpdatedV2Result resp, IBufferWriter writer) - => EncodeToWriter(new ForkchoiceUpdatedResponseWireV2 - { - PayloadStatus = BuildPayloadStatusV2Wire(resp.PayloadStatus), - PayloadId = BuildPayloadIdList(resp.PayloadId) - }, writer); - public static int EncodeInclusionListResponse(InclusionListBytes inclusionList, IBufferWriter writer) { int count = inclusionList.Count; @@ -202,6 +195,17 @@ public static int EncodeGetPayloadWithWitnessV6Response(GetPayloadV6Result r, Wi ShouldOverrideBuilder = r.ShouldOverrideBuilder }; + public static int EncodeGetPayloadV7Response(GetPayloadV7Result? r, IBufferWriter writer) + => EncodeToWriter(new GetPayloadResponseV7Wire + { + ExecutionPayload = new SszExecutionPayloadV4(r!.ExecutionPayload), + BlockValue = r.BlockValue, + BlobsBundle = r.BlobsBundle.ToWire(), + ExecutionRequests = r.ExecutionRequests.ToExecutionRequestsWire(), + ShouldOverrideBuilder = r.ShouldOverrideBuilder, + OmissionClaims = r.OmissionClaims.ToWire() + }, writer); + public static byte[][] DecodeGetBlobsRequest(ReadOnlySequence buf) { GetBlobsRequestWire.Decode(buf, out GetBlobsRequestWire wire); @@ -464,7 +468,7 @@ internal static PayloadAttributes PayloadAttributesFromWire(PayloadAttributesV5W parentBeaconBlockRoot: pa.ParentBeaconBlockRoot, slotNumber: pa.SlotNumber, targetGasLimit: pa.TargetGasLimit); - attributes.InclusionListTransactions = pa.InclusionListTransactions.ToExecutionRequests(); + attributes.InclusionLists = pa.InclusionLists.ToInclusionLists(); return attributes; } diff --git a/src/Nethermind/Nethermind.Merge.Plugin/SszRest/SszMiddlewareConfigurer.cs b/src/Nethermind/Nethermind.Merge.Plugin/SszRest/SszMiddlewareConfigurer.cs index c38d556302f5..b9b3667eb9d0 100644 --- a/src/Nethermind/Nethermind.Merge.Plugin/SszRest/SszMiddlewareConfigurer.cs +++ b/src/Nethermind/Nethermind.Merge.Plugin/SszRest/SszMiddlewareConfigurer.cs @@ -53,7 +53,7 @@ public void Configure(IServiceCollection services) services.AddSingleton>(); services.AddSingleton>(); services.AddSingleton>(); - services.AddSingleton(); + services.AddSingleton>(); services.AddSingleton>(); services.AddSingleton>(); @@ -61,6 +61,7 @@ public void Configure(IServiceCollection services) services.AddSingleton>(); services.AddSingleton>(); services.AddSingleton>(); + services.AddSingleton>(); services.AddSingleton(); diff --git a/src/Nethermind/Nethermind.Merge.Plugin/SszRest/SszWireTypes.cs b/src/Nethermind/Nethermind.Merge.Plugin/SszRest/SszWireTypes.cs index 565b6b783b37..b901a4333813 100644 --- a/src/Nethermind/Nethermind.Merge.Plugin/SszRest/SszWireTypes.cs +++ b/src/Nethermind/Nethermind.Merge.Plugin/SszRest/SszWireTypes.cs @@ -60,7 +60,7 @@ public partial struct PayloadStatusWire [SszList(1)] public SszValidationError[]? ValidationError { get; set; } } -// InclusionListSatisfied follows the Optional[T] = List[T, 1] pattern used above: 0/1 = false/true, empty = null. +// InclusionListSatisfied follows the Optional[T] = List[T, 1] pattern used above: 0/1 = false/true, and empty = null. [SszContainer] public partial struct PayloadStatusV2Wire { @@ -138,8 +138,24 @@ public partial struct PayloadAttributesV5Wire : ISszPayloadAttributesWire public Hash256 ParentBeaconBlockRoot { get; set; } public ulong SlotNumber { get; set; } public ulong TargetGasLimit { get; set; } - // Flattened aggregate: the per-member cap would reject aggregates the JSON path accepts. - [SszList(Eip7805Constants.MaxAggregateInclusionListTransactions)] public SszTransaction[]? InclusionListTransactions { get; set; } + // A list rather than a vector, so a wrong count is answered as the JSON path answers it. + [SszList(Eip7805Constants.InclusionListCommitteeSize)] public SszInclusionList[]? InclusionLists { get; set; } +} + +/// One committee position's inclusion list, in its original order with its duplicates. +/// The byte cap is checked by the engine, which answers it as it answers the JSON path. +[SszContainer(isCollectionItself: true)] +public partial struct SszInclusionList +{ + [SszList(Eip7805Constants.MaxTransactionsPerInclusionList)] public SszTransaction[]? Transactions { get; set; } +} + +/// An EIP-7805 omission claim, OmissionClaimV1. +[SszContainer] +public partial struct OmissionClaimWire +{ + public Hash256 TransactionHash { get; set; } + public ulong EvaluationIndex { get; set; } } [SszContainer] @@ -198,14 +214,6 @@ public partial struct ForkchoiceUpdatedResponseWire [SszList(1)] public SszPayloadId[]? PayloadId { get; set; } } -// Carries PayloadStatusV2 so a VALID head can report inclusionListSatisfied (execution-apis#609). -[SszContainer] -public partial struct ForkchoiceUpdatedResponseWireV2 -{ - public PayloadStatusV2Wire PayloadStatus { get; set; } - [SszList(1)] public SszPayloadId[]? PayloadId { get; set; } -} - [SszContainer] public partial struct NewPayloadV1RequestWire { @@ -247,8 +255,10 @@ public partial struct NewPayloadV6RequestWire public SszExecutionPayloadV4 ExecutionPayload { get; set; } public Hash256 ParentBeaconBlockRoot { get; set; } [SszList(256)] public SszTransaction[]? ExecutionRequests { get; set; } - // Flattened aggregate: the per-member cap would reject aggregates the JSON path accepts. - [SszList(Eip7805Constants.MaxAggregateInclusionListTransactions)] public SszTransaction[]? InclusionListTransactions { get; set; } + [SszList(Eip7805Constants.InclusionListCommitteeSize)] public SszInclusionList[]? InclusionLists { get; set; } + // Decoded past MAX_OMISSION_CLAIMS so the engine answers an over-cap list with -32602, as over JSON; one claim + // per entry the lists can carry is the transport's own bound. + [SszList(Eip7805Constants.MaxAggregateInclusionListTransactions)] public OmissionClaimWire[]? OmissionClaims { get; set; } } [SszContainer] @@ -333,6 +343,17 @@ public partial struct GetPayloadResponseV6Wire public bool ShouldOverrideBuilder { get; set; } } +[SszContainer] +public partial struct GetPayloadResponseV7Wire +{ + public SszExecutionPayloadV4 ExecutionPayload { get; set; } + public UInt256 BlockValue { get; set; } + public BlobsBundleV2Wire BlobsBundle { get; set; } + [SszList(256)] public SszTransaction[]? ExecutionRequests { get; set; } + public bool ShouldOverrideBuilder { get; set; } + [SszList(Eip8369Constants.MaxOmissionClaims)] public OmissionClaimWire[]? OmissionClaims { get; set; } +} + [SszContainer] public partial struct GetBlobsRequestWire { diff --git a/src/Nethermind/Nethermind.Merge.Plugin/SszRest/WireConversionExtensions.cs b/src/Nethermind/Nethermind.Merge.Plugin/SszRest/WireConversionExtensions.cs index 1b0cd721da91..da8c300618ea 100644 --- a/src/Nethermind/Nethermind.Merge.Plugin/SszRest/WireConversionExtensions.cs +++ b/src/Nethermind/Nethermind.Merge.Plugin/SszRest/WireConversionExtensions.cs @@ -81,6 +81,30 @@ public static SszTransaction[] ToExecutionRequestsWire(this byte[][]? reqs) return result; } + public static byte[][][]? ToInclusionLists(this SszInclusionList[]? inclusionLists) + { + if (inclusionLists is null) return null; + byte[][][] result = new byte[inclusionLists.Length][][]; + for (int i = 0; i < inclusionLists.Length; i++) result[i] = inclusionLists[i].Transactions.ToExecutionRequests() ?? []; + return result; + } + + public static OmissionClaim[]? ToClaims(this OmissionClaimWire[]? claims) + { + if (claims is null) return null; + OmissionClaim[] result = new OmissionClaim[claims.Length]; + for (int i = 0; i < claims.Length; i++) result[i] = new OmissionClaim(claims[i].TransactionHash, claims[i].EvaluationIndex); + return result; + } + + public static OmissionClaimWire[] ToWire(this OmissionClaim[] claims) + { + OmissionClaimWire[] result = new OmissionClaimWire[claims.Length]; + for (int i = 0; i < claims.Length; i++) + result[i] = new OmissionClaimWire { TransactionHash = claims[i].TransactionHash, EvaluationIndex = claims[i].EvaluationIndex }; + return result; + } + public static byte[][]? ToExecutionRequests(this SszTransaction[]? reqs) => reqs switch { null => null, diff --git a/src/Nethermind/Nethermind.Merge.Plugin/Synchronization/FinalizedBlockAccessListProcessor.cs b/src/Nethermind/Nethermind.Merge.Plugin/Synchronization/FinalizedBlockAccessListProcessor.cs index 7cedd3209ab5..893108365426 100644 --- a/src/Nethermind/Nethermind.Merge.Plugin/Synchronization/FinalizedBlockAccessListProcessor.cs +++ b/src/Nethermind/Nethermind.Merge.Plugin/Synchronization/FinalizedBlockAccessListProcessor.cs @@ -42,10 +42,7 @@ public event Action? TransactionsExecuted { const ProcessingOptions excluded = ProcessingOptions.ReadOnlyChain | ProcessingOptions.ForceProcessing | ProcessingOptions.NoValidation | ProcessingOptions.DoNotUpdateHead | ProcessingOptions.ForceSequentialBlockAccessList; - // EIP-8037 dimensions are not recoverable from a BAL or the header's combined gas total. - bool needsGasDimensions = spec.IsEip8037Enabled && block.InclusionListTransactions is { Length: > 0 } - && block.GasUsed != 0 && block.Header.GasUsedPerDimension is null; - if ((options & excluded) != 0 || needsGasDimensions || blockTracer != NullBlockTracer.Instance || !policy.CanReconstruct(block.Header)) + if ((options & excluded) != 0 || blockTracer != NullBlockTracer.Instance || !policy.CanReconstruct(block.Header)) return inner.ProcessOne(block, options, blockTracer, spec, token); // Queued processing attaches a stored list only when it matches the header's commitment. diff --git a/src/Nethermind/Nethermind.Runner/Ethereum/StartupPipelineWarmer.cs b/src/Nethermind/Nethermind.Runner/Ethereum/StartupPipelineWarmer.cs index cc94693ac977..dc14f3e8620d 100644 --- a/src/Nethermind/Nethermind.Runner/Ethereum/StartupPipelineWarmer.cs +++ b/src/Nethermind/Nethermind.Runner/Ethereum/StartupPipelineWarmer.cs @@ -512,13 +512,21 @@ private static (string Method, object[] Parameters) CreatePayloadRequest(Block b ExecutionPayload payload = spec.IsEip7928Enabled ? ExecutionPayloadV4.Create(block) : ExecutionPayloadV3.Create(block); object[] parameters = spec.IsEip7805Enabled - ? [payload, Array.Empty(), Keccak.Zero, Array.Empty(), Array.Empty()] + ? [payload, Array.Empty(), Keccak.Zero, Array.Empty(), EmptyInclusionLists(), Array.Empty()] : spec.RequestsEnabled ? [payload, Array.Empty(), Keccak.Zero, Array.Empty()] : spec.IsEip4844Enabled ? [payload, Array.Empty(), Keccak.Zero] : [payload]; return (method, parameters); } + /// One empty list per EIP-7805 committee position, as engine_newPayloadV6 requires. + private static byte[][][] EmptyInclusionLists() + { + byte[][][] inclusionLists = new byte[Eip7805Constants.InclusionListCommitteeSize][][]; + Array.Fill(inclusionLists, []); + return inclusionLists; + } + private static async Task SendForkchoiceUpdatedAsync(HttpClient client, EthereumJsonSerializer serializer, string address, Block block, IReleaseSpec spec, CancellationToken cancellationToken) { string forkchoiceUpdated = spec.IsEip7805Enabled ? "engine_forkchoiceUpdatedV5" diff --git a/src/Nethermind/Nethermind.Specs.Test/ChainSpecStyle/GethGenesisLoaderTests.cs b/src/Nethermind/Nethermind.Specs.Test/ChainSpecStyle/GethGenesisLoaderTests.cs index 0125bbf0fe46..99dbd678dffa 100644 --- a/src/Nethermind/Nethermind.Specs.Test/ChainSpecStyle/GethGenesisLoaderTests.cs +++ b/src/Nethermind/Nethermind.Specs.Test/ChainSpecStyle/GethGenesisLoaderTests.cs @@ -54,7 +54,8 @@ public class GethGenesisLoaderTests ]; // Fork classes that are not real Geth fork names and therefore have no genesis config property - private static readonly HashSet ForkClassesWithoutConfigProp = [nameof(FramesDevnet1)]; + // FramesDevnet1 and Eip8369Prototype exist for fixture runs only and are scheduled on no network. + private static readonly HashSet ForkClassesWithoutConfigProp = [nameof(FramesDevnet1), nameof(Eip8369Prototype)]; private const string ForksThroughShanghaiAtGenesis = "\"byzantiumBlock\": 0, \"constantinopleBlock\": 0, \"petersburgBlock\": 0, \"istanbulBlock\": 0, \"berlinBlock\": 0, \"londonBlock\": 0, \"shanghaiTime\": 0"; diff --git a/src/Nethermind/Nethermind.Specs.Test/ChainSpecStyle/GethGenesisParityTests.cs b/src/Nethermind/Nethermind.Specs.Test/ChainSpecStyle/GethGenesisParityTests.cs index c7a25de15df8..05ebdcda0be8 100644 --- a/src/Nethermind/Nethermind.Specs.Test/ChainSpecStyle/GethGenesisParityTests.cs +++ b/src/Nethermind/Nethermind.Specs.Test/ChainSpecStyle/GethGenesisParityTests.cs @@ -42,6 +42,7 @@ public class GethGenesisParityTests // Names the EIP set frames-devnet-1 runs; geth genesis generators only emit the per-prototype labels. // Its parent's eip8141PrototypeTime schedules frame transactions, these labels the EIPs on top. [nameof(FramesDevnet1)] = [nameof(Eip8250Prototype), nameof(Eip8272Prototype), nameof(Eip7906Prototype)], + [nameof(Eip8369Prototype)] = [nameof(Eip8141Prototype), nameof(Eip8250Prototype), nameof(Eip8272Prototype)], }; /// diff --git a/src/Nethermind/Nethermind.Specs.Test/ForkTests.cs b/src/Nethermind/Nethermind.Specs.Test/ForkTests.cs index 88076a01d869..af1995cf0711 100644 --- a/src/Nethermind/Nethermind.Specs.Test/ForkTests.cs +++ b/src/Nethermind/Nethermind.Specs.Test/ForkTests.cs @@ -166,4 +166,19 @@ public void Bogota_enables_inclusion_lists_without_frame_transactions() Assert.That(Amsterdam.Instance.IsEip7805Enabled, Is.False); } } + + [Test] + public void Eip8369Prototype_combines_inclusion_lists_with_frame_transactions_and_their_extensions() + { + using (Assert.EnterMultipleScope()) + { + Assert.That(Eip8369Prototype.Instance.Parent, Is.SameAs(Bogota.Instance)); + Assert.That(Eip8369Prototype.Instance.IsEip7805Enabled, Is.True); + Assert.That(Eip8369Prototype.Instance.IsEip8141Enabled, Is.True); + Assert.That(Eip8369Prototype.Instance.IsEip8250Enabled, Is.True); + Assert.That(Eip8369Prototype.Instance.IsEip8272Enabled, Is.True); + Assert.That(Eip8369Prototype.Instance.IsEip7906Enabled, Is.False); + Assert.That(SpecNameParser.Parse(nameof(Eip8369Prototype)), Is.SameAs(Eip8369Prototype.Instance)); + } + } } diff --git a/src/Nethermind/Nethermind.Specs/Forks/26_Bogota.cs b/src/Nethermind/Nethermind.Specs/Forks/26_Bogota.cs index 469f9767ab7d..a34462bbf378 100644 --- a/src/Nethermind/Nethermind.Specs/Forks/26_Bogota.cs +++ b/src/Nethermind/Nethermind.Specs/Forks/26_Bogota.cs @@ -17,6 +17,7 @@ public override void Apply(NamedReleaseSpec spec) spec.Name = "Bogota"; spec.IsEip7805Enabled = true; spec.EngineApiNewPayloadVersion = EngineApiVersions.NewPayload.V6; + spec.EngineApiGetPayloadVersion = EngineApiVersions.GetPayload.V7; spec.EngineApiForkchoiceVersion = EngineApiVersions.Fcu.V5; } } diff --git a/src/Nethermind/Nethermind.Specs/Forks/Eip8369Prototype.cs b/src/Nethermind/Nethermind.Specs/Forks/Eip8369Prototype.cs new file mode 100644 index 000000000000..bb6bc11ee6bf --- /dev/null +++ b/src/Nethermind/Nethermind.Specs/Forks/Eip8369Prototype.cs @@ -0,0 +1,20 @@ +// SPDX-FileCopyrightText: 2026 Demerzel Solutions Limited +// SPDX-License-Identifier: LGPL-3.0-only + +namespace Nethermind.Specs.Forks; + +/// +/// Prototype fork for EIP-8369 Profile 2 enforcement: 's EIP-7805 inclusion lists with +/// EIP-8141 frame transactions, EIP-8250 keyed nonces and EIP-8272 recent roots. Not scheduled on any network; +/// exists so fixtures whose Bogota combines all four can be run through --forkAlias Bogota=Eip8369Prototype. +/// +public class Eip8369Prototype() : NamedReleaseSpec(Bogota.Instance) +{ + public override void Apply(NamedReleaseSpec spec) + { + spec.Name = "Eip8369Prototype"; + spec.IsEip8141Enabled = true; + spec.IsEip8250Enabled = true; + spec.IsEip8272Enabled = true; + } +} diff --git a/src/Nethermind/Nethermind.Specs/SpecNameParser.cs b/src/Nethermind/Nethermind.Specs/SpecNameParser.cs index d206047df21d..f1179ae3ca5b 100644 --- a/src/Nethermind/Nethermind.Specs/SpecNameParser.cs +++ b/src/Nethermind/Nethermind.Specs/SpecNameParser.cs @@ -69,6 +69,7 @@ private static IReleaseSpec ParseUncached(string specName) nameof(Eip7906Prototype) => Eip7906Prototype.Instance, nameof(Eip4758Prototype) => Eip4758Prototype.Instance, nameof(FramesDevnet1) => FramesDevnet1.Instance, + nameof(Eip8369Prototype) => Eip8369Prototype.Instance, nameof(BogotaDevnet2) => BogotaDevnet2.Instance, _ => throw new NotSupportedException(specName == unambiguousSpecName ? $"Unknown fork name '{specName}'" diff --git a/src/Nethermind/Nethermind.Taiko.Test/CertainBatchLookupTests.cs b/src/Nethermind/Nethermind.Taiko.Test/CertainBatchLookupTests.cs index 5d4e72fa3705..7bb6aadc34a8 100644 --- a/src/Nethermind/Nethermind.Taiko.Test/CertainBatchLookupTests.cs +++ b/src/Nethermind/Nethermind.Taiko.Test/CertainBatchLookupTests.cs @@ -436,6 +436,7 @@ private static TaikoEngineRpcModule CreateRpcModule(IL1OriginStore l1OriginStore Substitute.For>(), Substitute.For>(), Substitute.For>(), + Substitute.For>(), Substitute.For>(), Substitute.For(), Substitute.For, IReadOnlyList>>(), @@ -449,7 +450,7 @@ private static TaikoEngineRpcModule CreateRpcModule(IL1OriginStore l1OriginStore Substitute.For(), Substitute.For>(), Substitute.For(), - Substitute.For(), + Substitute.For(), Substitute.For, NewPayloadWithWitnessV1Result>>(), Substitute.For, NewPayloadWithWitnessV1Result>>(), Substitute.For>(), @@ -461,7 +462,6 @@ private static TaikoEngineRpcModule CreateRpcModule(IL1OriginStore l1OriginStore Substitute.For(), Substitute.For(), blockFinder ?? Substitute.For(), - Substitute.For(), Substitute.For(), TxDecoder.Instance, l1OriginStore, diff --git a/src/Nethermind/Nethermind.Taiko.Test/TxPoolContentListsTests.cs b/src/Nethermind/Nethermind.Taiko.Test/TxPoolContentListsTests.cs index 6ac162c5a830..327535ef14da 100644 --- a/src/Nethermind/Nethermind.Taiko.Test/TxPoolContentListsTests.cs +++ b/src/Nethermind/Nethermind.Taiko.Test/TxPoolContentListsTests.cs @@ -255,6 +255,7 @@ private static TaikoEngineRpcModule CreateRpcModule( Substitute.For>(), Substitute.For>(), Substitute.For>(), + Substitute.For>(), Substitute.For>(), Substitute.For(), Substitute.For, IReadOnlyList>>(), @@ -268,7 +269,7 @@ private static TaikoEngineRpcModule CreateRpcModule( Substitute.For(), Substitute.For>(), Substitute.For(), - Substitute.For(), + Substitute.For(), Substitute.For, NewPayloadWithWitnessV1Result>>(), Substitute.For, NewPayloadWithWitnessV1Result>>(), Substitute.For>(), @@ -280,7 +281,6 @@ private static TaikoEngineRpcModule CreateRpcModule( Substitute.For(), txPool, blockFinder, - Substitute.For(), shareableTxProcessor, TxDecoder.Instance, Substitute.For(), diff --git a/src/Nethermind/Nethermind.Taiko/Rpc/TaikoEngineRpcModule.cs b/src/Nethermind/Nethermind.Taiko/Rpc/TaikoEngineRpcModule.cs index 2f0e616a0f2a..132dc4bf7a48 100644 --- a/src/Nethermind/Nethermind.Taiko/Rpc/TaikoEngineRpcModule.cs +++ b/src/Nethermind/Nethermind.Taiko/Rpc/TaikoEngineRpcModule.cs @@ -44,6 +44,7 @@ public class TaikoEngineRpcModule(IAsyncHandler getPa IAsyncHandler getPayloadHandlerV4, IAsyncHandler getPayloadHandlerV5, IAsyncHandler getPayloadHandlerV6, + IAsyncHandler getPayloadHandlerV7, IAsyncHandler newPayloadV1Handler, IForkchoiceUpdatedHandler forkchoiceUpdatedV1Handler, IHandler, IReadOnlyList> executionGetPayloadBodiesByHashV1Handler, @@ -57,7 +58,7 @@ public class TaikoEngineRpcModule(IAsyncHandler getPa IGetPayloadBodiesByRangeV2Handler getPayloadBodiesByRangeV2Handler, IHandler getInclusionListTransactionsHandler, IInclusionListTxSource inclusionListTxSource, - IInclusionListComplianceEvaluator inclusionListComplianceEvaluator, + IInclusionChecks inclusionChecks, IAsyncHandler, NewPayloadWithWitnessV1Result> newPayloadWithWitnessHandlerV4, IAsyncHandler, NewPayloadWithWitnessV1Result> newPayloadWithWitnessHandlerV5, IAsyncHandler newPayloadWithWitnessHandlerV6, @@ -69,7 +70,6 @@ public class TaikoEngineRpcModule(IAsyncHandler getPa ILogManager logManager, ITxPool txPool, IBlockFinder blockFinder, - IBlockTree blockTree, IShareableTxProcessorSource txProcessorSource, IRlpDecoder txDecoder, IL1OriginStore l1OriginStore, @@ -80,6 +80,7 @@ public class TaikoEngineRpcModule(IAsyncHandler getPa getPayloadHandlerV4, getPayloadHandlerV5, getPayloadHandlerV6, + getPayloadHandlerV7, newPayloadV1Handler, forkchoiceUpdatedV1Handler, executionGetPayloadBodiesByHashV1Handler, @@ -93,7 +94,7 @@ public class TaikoEngineRpcModule(IAsyncHandler getPa getPayloadBodiesByRangeV2Handler, getInclusionListTransactionsHandler, inclusionListTxSource, - inclusionListComplianceEvaluator, + inclusionChecks, newPayloadWithWitnessHandlerV4, newPayloadWithWitnessHandlerV5, newPayloadWithWitnessHandlerV6, @@ -102,8 +103,7 @@ public class TaikoEngineRpcModule(IAsyncHandler getPa specProvider, gcKeeper, processingQueue, - logManager, - blockTree), ITaikoEngineRpcModule + logManager), ITaikoEngineRpcModule { /// Initializes the module with module-local blob custody tracking. /// Use the overload accepting when custody state must be shared with networking. @@ -114,6 +114,7 @@ public TaikoEngineRpcModule( IAsyncHandler getPayloadHandlerV4, IAsyncHandler getPayloadHandlerV5, IAsyncHandler getPayloadHandlerV6, + IAsyncHandler getPayloadHandlerV7, IAsyncHandler newPayloadV1Handler, IForkchoiceUpdatedHandler forkchoiceUpdatedV1Handler, IHandler, IReadOnlyList> executionGetPayloadBodiesByHashV1Handler, @@ -127,7 +128,7 @@ public TaikoEngineRpcModule( IGetPayloadBodiesByRangeV2Handler getPayloadBodiesByRangeV2Handler, IHandler getInclusionListTransactionsHandler, IInclusionListTxSource inclusionListTxSource, - IInclusionListComplianceEvaluator inclusionListComplianceEvaluator, + IInclusionChecks inclusionChecks, IAsyncHandler, NewPayloadWithWitnessV1Result> newPayloadWithWitnessHandlerV4, IAsyncHandler, NewPayloadWithWitnessV1Result> newPayloadWithWitnessHandlerV5, IAsyncHandler newPayloadWithWitnessHandlerV6, @@ -138,7 +139,6 @@ public TaikoEngineRpcModule( ILogManager logManager, ITxPool txPool, IBlockFinder blockFinder, - IBlockTree blockTree, IShareableTxProcessorSource txProcessorSource, IRlpDecoder txDecoder, IL1OriginStore l1OriginStore, @@ -150,6 +150,7 @@ public TaikoEngineRpcModule( getPayloadHandlerV4, getPayloadHandlerV5, getPayloadHandlerV6, + getPayloadHandlerV7, newPayloadV1Handler, forkchoiceUpdatedV1Handler, executionGetPayloadBodiesByHashV1Handler, @@ -163,7 +164,7 @@ public TaikoEngineRpcModule( getPayloadBodiesByRangeV2Handler, getInclusionListTransactionsHandler, inclusionListTxSource, - inclusionListComplianceEvaluator, + inclusionChecks, newPayloadWithWitnessHandlerV4, newPayloadWithWitnessHandlerV5, newPayloadWithWitnessHandlerV6, @@ -175,7 +176,6 @@ public TaikoEngineRpcModule( logManager, txPool, blockFinder, - blockTree, txProcessorSource, txDecoder, l1OriginStore, From 82cb885028ae04d154299d0490362b4087299ef6 Mon Sep 17 00:00:00 2001 From: Daniil Ankushin <71745946+AnkushinDaniil@users.noreply.github.com> Date: Sat, 28 Nov 2026 20:11:31 +0100 Subject: [PATCH 2/4] Build Profile 2 candidates and claims under the fork's MAX_VERIFY_GAS_PER_TX in block production --- .../InclusionListTxSourceTests.cs | 15 ++++++--------- .../Transactions/InclusionListTxSource.cs | 8 ++------ .../Nethermind.Core/Eip8369Constants.cs | 5 +++-- .../EngineModuleTests.Eip8369.cs | 17 +++++++++++++++++ .../BlockProduction/PostMergeBlockProducer.cs | 2 +- 5 files changed, 29 insertions(+), 18 deletions(-) diff --git a/src/Nethermind/Nethermind.Consensus.Test/InclusionListTxSourceTests.cs b/src/Nethermind/Nethermind.Consensus.Test/InclusionListTxSourceTests.cs index e940572541c6..ab4d97be2d33 100644 --- a/src/Nethermind/Nethermind.Consensus.Test/InclusionListTxSourceTests.cs +++ b/src/Nethermind/Nethermind.Consensus.Test/InclusionListTxSourceTests.cs @@ -3,7 +3,6 @@ using System.Collections.Generic; using System.Linq; -using Nethermind.Config; using Nethermind.Consensus.Producers; using Nethermind.Consensus.Transactions; using Nethermind.Consensus.Validators; @@ -257,13 +256,12 @@ public void Frame_transaction_admitted_at_another_position_is_offered() Assert.That(GetTransactions(source, Attributes(il)).Select(tx => tx.Hash), Is.EquivalentTo(frameTxs.Select(tx => tx.CalculateHash()))); } - [TestCase(0UL, 2, TestName = "Lifting MAX_VERIFY_GAS_PER_TX admits the costlier entry")] - [TestCase(Eip8369Constants.MaxVerifyGasPerTx, 1, TestName = "An entry over MAX_VERIFY_GAS_PER_TX is not offered")] - public void Frame_transaction_over_the_per_tx_cap_is_not_offered(ulong maxVerifyGasPerTx, int expected) + [Test] + public void Frame_transaction_over_the_per_tx_cap_is_not_offered() { Transaction admitted = Profile2FrameTx(TestItem.AddressB, 100_000); Transaction overCap = Profile2FrameTx(TestItem.AddressC, Eip8369Constants.MaxVerifyGasPerTx + 1); - InclusionListTxSource source = CreateProfile2Source(new BlocksConfig { FocilProfile2MaxVerifyGas = maxVerifyGasPerTx }); + InclusionListTxSource source = CreateProfile2Source(); byte[][][] il = AtPosition0([Encode(overCap), Encode(admitted)]); source.Set(il, Eip8369Prototype.Instance); @@ -271,17 +269,16 @@ public void Frame_transaction_over_the_per_tx_cap_is_not_offered(ulong maxVerify using (Assert.EnterMultipleScope()) { - Assert.That(offered, Has.Count.EqualTo(expected)); + Assert.That(offered, Has.Count.EqualTo(1)); Assert.That(offered.Select(tx => tx.Hash), Does.Contain(admitted.CalculateHash())); } } - private static InclusionListTxSource CreateProfile2Source(IBlocksConfig blocksConfig = null) => new( + private static InclusionListTxSource CreateProfile2Source() => new( new EthereumEcdsa(MainnetSpecProvider.Instance.ChainId), new CustomSpecProvider(((ForkActivation)0, Eip8369Prototype.Instance)), AcceptAll(), - LimboLogs.Instance, - blocksConfig: blocksConfig); + LimboLogs.Instance); private static ITxValidator AcceptAll() { diff --git a/src/Nethermind/Nethermind.Consensus/Transactions/InclusionListTxSource.cs b/src/Nethermind/Nethermind.Consensus/Transactions/InclusionListTxSource.cs index ff906cc64475..4869a6e14ec4 100644 --- a/src/Nethermind/Nethermind.Consensus/Transactions/InclusionListTxSource.cs +++ b/src/Nethermind/Nethermind.Consensus/Transactions/InclusionListTxSource.cs @@ -6,7 +6,6 @@ using System.Diagnostics.CodeAnalysis; using System.Linq; using System.Runtime.CompilerServices; -using Nethermind.Config; using Nethermind.Consensus.Decoders; using Nethermind.Consensus.Processing; using Nethermind.Consensus.Producers; @@ -26,8 +25,7 @@ public class InclusionListTxSource( ISpecProvider specProvider, ITxValidator txValidator, ILogManager logManager, - IProfile2EligibilityReplayer? profile2Replayer = null, - IBlocksConfig? blocksConfig = null) : IInclusionListTxSource + IProfile2EligibilityReplayer? profile2Replayer = null) : IInclusionListTxSource { // Lazy defaults to ExecutionAndPublication: constructed once even under racing FCUs. private readonly Lazy _decoder = new(() => new InclusionListDecoder(ecdsa, specProvider, logManager)); @@ -45,8 +43,6 @@ private sealed record DecodedInclusionLists(Transaction[] ForProduction, Transac public (ulong MaxVerifyGasPerTx, IReadOnlySet? Candidates)? Profile2Candidates; } - private readonly ulong _maxVerifyGasPerTx = blocksConfig?.FocilProfile2MaxVerifyGas ?? Eip8369Constants.MaxVerifyGasPerTx; - /// /// Once Profile 2 is active, a frame transaction no committee position's VERIFY budget fill admits is /// not offered: its omission is excused (EIP-8369 § Profile 2 omission claims), so the build never runs its VERIFY. @@ -56,7 +52,7 @@ public IEnumerable GetTransactions(BlockHeader parent, BlockHeader if (!TryGetDecoded(payloadAttributes, out DecodedInclusionLists? decoded)) return []; if (!Eip8369Profile2.IsActive(decoded.Spec)) return decoded.ForProduction; - IReadOnlySet? admitted = GetProfile2Candidates(payloadAttributes, _maxVerifyGasPerTx); + IReadOnlySet? admitted = GetProfile2Candidates(payloadAttributes, Eip8369Constants.MaxVerifyGasPerTx); return decoded.ForProduction.Where(tx => !tx.SupportsFrames || (admitted is not null && tx.Hash is not null && admitted.Contains(tx.Hash))); } diff --git a/src/Nethermind/Nethermind.Core/Eip8369Constants.cs b/src/Nethermind/Nethermind.Core/Eip8369Constants.cs index 9ccad2983dc8..bddeab5fce01 100644 --- a/src/Nethermind/Nethermind.Core/Eip8369Constants.cs +++ b/src/Nethermind/Nethermind.Core/Eip8369Constants.cs @@ -9,8 +9,9 @@ namespace Nethermind.Core; /// /// /// EIP-8369 is Informational and leaves its budget caps to the Standards Track EIP that enforces them; EIP-7805 -/// § Profile 2 omission claims and per IL budgets fixes the values here. IBlocksConfig.FocilProfile2MaxVerifyGas -/// is the operator-facing mirror, as ITxPoolConfig.FrameTxMaxVerifyGas is for EIP-8141's own cap. +/// § Profile 2 omission claims and per IL budgets fixes the values here. Block building and validation both use +/// them as they are; IBlocksConfig.FocilProfile2MaxVerifyGas only bounds what this node lists when building +/// an inclusion list. /// public static class Eip8369Constants { diff --git a/src/Nethermind/Nethermind.Merge.Plugin.Test/EngineModuleTests.Eip8369.cs b/src/Nethermind/Nethermind.Merge.Plugin.Test/EngineModuleTests.Eip8369.cs index 5d800af457ae..ecd7dbb6717d 100644 --- a/src/Nethermind/Nethermind.Merge.Plugin.Test/EngineModuleTests.Eip8369.cs +++ b/src/Nethermind/Nethermind.Merge.Plugin.Test/EngineModuleTests.Eip8369.cs @@ -95,6 +95,23 @@ public async Task NewPayloadV6_classifies_candidates_by_the_forks_verify_gas_cap Assert.That(newPayload.Data.InclusionListSatisfied, Is.False, newPayload.Result.Error); } + [Test] + public async Task NewPayloadV6_accepts_the_claims_of_a_block_built_under_a_lower_local_cap() + { + using MergeTestBlockchain chain = await CreateProfile2Blockchain( + configure: builder => builder.AddSingleton(new BlocksConfig { FocilProfile2MaxVerifyGas = 1 })); + (GetPayloadV7Result built, byte[] frameTx, byte[] enabler, _) = await BuildProfile2Payload(chain); + + ResultWrapper newPayload = await chain.EngineRpcModule.engine_newPayloadV6( + built.ExecutionPayload, [], Keccak.Zero, built.ExecutionRequests, AtPositions([frameTx, enabler]), built.OmissionClaims); + + using (Assert.EnterMultipleScope()) + { + Assert.That(built.OmissionClaims, Is.EqualTo(new[] { new OmissionClaim(Keccak.Compute(frameTx), 0) })); + Assert.That(newPayload.Data.InclusionListSatisfied, Is.True, newPayload.Result.Error); + } + } + [Test] public async Task NewPayloadV6_does_not_reuse_a_verdict_checked_under_other_claims() { diff --git a/src/Nethermind/Nethermind.Merge.Plugin/BlockProduction/PostMergeBlockProducer.cs b/src/Nethermind/Nethermind.Merge.Plugin/BlockProduction/PostMergeBlockProducer.cs index 76938d068bf2..74cf5b73fcb9 100644 --- a/src/Nethermind/Nethermind.Merge.Plugin/BlockProduction/PostMergeBlockProducer.cs +++ b/src/Nethermind/Nethermind.Merge.Plugin/BlockProduction/PostMergeBlockProducer.cs @@ -55,7 +55,7 @@ protected override BlockToProduce PrepareBlock(BlockHeader parent, PayloadAttrib blockToProduce.Transactions = inclusionList; } } - blockToProduce.InclusionListCandidates = inclusionListTxSource?.GetProfile2Candidates(payloadAttributes, _blocksConfig.FocilProfile2MaxVerifyGas); + blockToProduce.InclusionListCandidates = inclusionListTxSource?.GetProfile2Candidates(payloadAttributes, Eip8369Constants.MaxVerifyGasPerTx); return blockToProduce; } From 520f3c7dbd66b4c52102198d637f3ff1b50db258 Mon Sep 17 00:00:00 2001 From: Daniil Ankushin <71745946+AnkushinDaniil@users.noreply.github.com> Date: Sun, 29 Nov 2026 00:01:17 +0100 Subject: [PATCH 3/4] Profile 2 replay: refuse SETCODEFROM only when it runs, not when a target's code holds it The public-mempool HasMutableCode check refuses any target whose bytecode contains SETCODEFROM, because a mempool must not admit a tx whose validity another tx can flip. EIP-8369 replay judges one fixed state, so that check let EXTCODEHASH on an undelegated contract holding SETCODEFROM wrongly excuse an omission. Replay now skips the bytecode-presence check and still refuses executing SETCODEFROM in the prefix. --- .../Profile2EligibilityReplayerTests.cs | 33 +++++++++++++++++-- .../Processing/Profile2EligibilityReplayer.cs | 3 +- .../Tracing/FrameTxValidationTracer.cs | 7 ++-- 3 files changed, 38 insertions(+), 5 deletions(-) diff --git a/src/Nethermind/Nethermind.Blockchain.Test/Profile2EligibilityReplayerTests.cs b/src/Nethermind/Nethermind.Blockchain.Test/Profile2EligibilityReplayerTests.cs index 00b89a53ccfa..7debfeca74bf 100644 --- a/src/Nethermind/Nethermind.Blockchain.Test/Profile2EligibilityReplayerTests.cs +++ b/src/Nethermind/Nethermind.Blockchain.Test/Profile2EligibilityReplayerTests.cs @@ -36,6 +36,7 @@ public class Profile2EligibilityReplayerTests { private static readonly Address Sender = TestItem.AddressD; private static readonly IReleaseSpec Spec = new OverridableReleaseSpec(Eip8141Prototype.Instance) { IsEip8272Enabled = true }; + private static readonly IReleaseSpec Eip8298Spec = new OverridableReleaseSpec(Eip8141Prototype.Instance) { IsEip8272Enabled = true, IsEip8298Enabled = true }; private const ulong BlockSlot = 10_000; public static IEnumerable Cases @@ -153,6 +154,34 @@ public async Task Recent_roots_are_anchored_at_the_blocks_own_slot(ulong referen Assert.That(IsEligible(replayer, ChildOfHead(chain, new ReadOnlyBlockAccessList([Changes()], 1)), tx, 0), Is.EqualTo(eligible)); } + public enum SetCodeFromTarget { HashRead, CalledPastIt, CalledIntoIt } + + /// EIP-8369 replay judges one fixed state, so a target whose code merely holds SETCODEFROM cannot excuse + /// an omission; running SETCODEFROM in the prefix still makes the candidate ineligible. + [TestCase(SetCodeFromTarget.HashRead, true, TestName = "EXTCODEHASH of an undelegated contract holding SETCODEFROM is eligible")] + [TestCase(SetCodeFromTarget.CalledPastIt, true, TestName = "Call into a contract that stops before its SETCODEFROM is eligible")] + [TestCase(SetCodeFromTarget.CalledIntoIt, false, TestName = "Call into a contract that runs SETCODEFROM is ineligible")] + public async Task Code_holding_SETCODEFROM_does_not_excuse_an_omission_unless_it_runs(SetCodeFromTarget kind, bool eligible) + { + Address target = TestItem.AddressE; + byte[] targetCode = kind == SetCodeFromTarget.CalledIntoIt + ? Prepare.EvmCode.SETCODEFROM(TestItem.AddressF).STOP().Done + : Prepare.EvmCode.STOP().SETCODEFROM(TestItem.AddressF).Done; + Prepare touch = kind == SetCodeFromTarget.HashRead + ? Prepare.EvmCode.PushData(target).Op(Instruction.EXTCODEHASH).Op(Instruction.POP) + : Prepare.EvmCode.Call(target, 50_000).Op(Instruction.POP); + byte[] approve = [(byte)Instruction.PUSH1, (byte)FrameFlags.ApproveExecutionAndPayment, (byte)Instruction.PUSH1, 0, (byte)Instruction.PUSH1, 0, (byte)Instruction.APPROVE]; + using BasicTestBlockchain chain = await CreateChain([.. touch.Done, .. approve], worldState => + { + worldState.CreateAccount(target, 0); + worldState.InsertCode(target, targetCode, Eip8298Spec); + }, spec: Eip8298Spec); + IProfile2EligibilityReplayer replayer = chain.Container.Resolve(); + Block block = ChildOfHead(chain, new ReadOnlyBlockAccessList([Changes()], 1)); + + Assert.That(replayer.AreEligible(block, [(FrameTx(), 0)], Eip8298Spec)[0], Is.EqualTo(eligible)); + } + public enum DeployFactory { Contract, Codeless, Delegated } /// EIP-7805 replay: the deploy frame's factory is a dependency of the deployment, so it must be a contract @@ -252,9 +281,9 @@ public bool TryBuildAtTarget(BlockHeader targetBlock, [NotNullWhen(true)] out IR private static Task CreateChain(byte slot) => CreateChain(ApproveWhileSlotIsZero(slot)); - private static Task CreateChain(byte[] senderCode, Action? genesis = null, ulong? localMaxVerifyGas = null) => BasicTestBlockchain.Create(builder => + private static Task CreateChain(byte[] senderCode, Action? genesis = null, ulong? localMaxVerifyGas = null, IReleaseSpec? spec = null) => BasicTestBlockchain.Create(builder => { - builder.AddSingleton(new TestSpecProvider(Spec)); + builder.AddSingleton(new TestSpecProvider(spec ?? Spec)); if (localMaxVerifyGas is { } cap) builder.AddSingleton(new BlocksConfig { FocilProfile2MaxVerifyGas = cap }); builder.AddScoped((worldState, specProvider) => new FunctionalGenesisPostProcessor(_ => diff --git a/src/Nethermind/Nethermind.Consensus/Processing/Profile2EligibilityReplayer.cs b/src/Nethermind/Nethermind.Consensus/Processing/Profile2EligibilityReplayer.cs index e76d878b4ae4..fe5d2c15bb13 100644 --- a/src/Nethermind/Nethermind.Consensus/Processing/Profile2EligibilityReplayer.cs +++ b/src/Nethermind/Nethermind.Consensus/Processing/Profile2EligibilityReplayer.cs @@ -131,7 +131,8 @@ private bool Replay(IWorldState state, ITransactionProcessor processor, Transact FrameTxValidationTracer tracer = new(sender, Eip8141Constants.ExpiryVerifierAddress, state, spec, maxVerifyGas: Eip8369Constants.MaxVerifyGasPerTx, payer: sender, storageSlotBound: Eip8369Constants.AaVopsSlotCount, createInDeployFrame: true, - maxCodeBodies: Eip8369Constants.MaxReplayCodeBodies, maxCodeBytes: Eip8369Constants.MaxReplayCodeBytes); + maxCodeBodies: Eip8369Constants.MaxReplayCodeBodies, maxCodeBytes: Eip8369Constants.MaxReplayCodeBytes, + refuseMutableCode: false); try { // Prefix-only simulation restores its own snapshot, so the reconstructed state serves the next candidate. diff --git a/src/Nethermind/Nethermind.Evm/Tracing/FrameTxValidationTracer.cs b/src/Nethermind/Nethermind.Evm/Tracing/FrameTxValidationTracer.cs index bda02927bcb0..83ec4fdb091a 100644 --- a/src/Nethermind/Nethermind.Evm/Tracing/FrameTxValidationTracer.cs +++ b/src/Nethermind/Nethermind.Evm/Tracing/FrameTxValidationTracer.cs @@ -39,6 +39,8 @@ namespace Nethermind.Evm.Tracing; /// The prefix's VERIFY gas bound; EIP-8141's MAX_VERIFY_GAS by default. /// The most distinct accounts may hold; recording one /// more violates the prefix. +/// Whether a target whose code holds SETCODEFROM is refused, as the public mempool must; +/// a replay judges one fixed state, so it refuses only SETCODEFROM run in the prefix. public sealed class FrameTxValidationTracer( Address sender, Address expiryVerifier, @@ -54,7 +56,8 @@ public sealed class FrameTxValidationTracer( UInt256 storageSlotBound = default, bool createInDeployFrame = false, int maxCodeBodies = 0, - long maxCodeBytes = 0) + long maxCodeBytes = 0, + bool refuseMutableCode = true) : TxTracer, ITxTracer, IFrameTxReceiptTracer, IFrameTxPrefixTracer, IInstructionTracingFilter { /// The opcodes that reach ; every other opcode runs untraced. @@ -468,7 +471,7 @@ private bool IsForbiddenCallTarget(Address target) /// private bool HasMutableCode(Address target) { - if (!spec.IsEip8298Enabled || target == sender || spec.IsPrecompile(target)) return false; + if (!refuseMutableCode || !spec.IsEip8298Enabled || target == sender || spec.IsPrecompile(target)) return false; ValueHash256 codeHash = state.GetCodeHash(target); (ValueHash256, bool) key = (codeHash, spec.IsEip8024Enabled); From 37298e5c2bcc14cfb06d64c6c64121ee4575594e Mon Sep 17 00:00:00 2001 From: Daniil Ankushin <71745946+AnkushinDaniil@users.noreply.github.com> Date: Sun, 29 Nov 2026 00:01:18 +0100 Subject: [PATCH 4/4] Drop the unused maxVerifyGasPerTx parameter of GetProfile2Candidates and move a misplaced test summary Every caller passed the fork cap, so the candidate fill always runs under MAX_VERIFY_GAS_PER_TX. --- .../Transactions/IInclusionListTxSource.cs | 2 +- .../Transactions/InclusionListTxSource.cs | 14 +++++++------- .../EngineModuleTests.Eip8369.cs | 2 +- .../EngineModuleTests.V7.cs | 4 ++-- .../BlockProduction/PostMergeBlockProducer.cs | 2 +- 5 files changed, 12 insertions(+), 12 deletions(-) diff --git a/src/Nethermind/Nethermind.Consensus/Transactions/IInclusionListTxSource.cs b/src/Nethermind/Nethermind.Consensus/Transactions/IInclusionListTxSource.cs index b544e6c468f2..1183905ce29f 100644 --- a/src/Nethermind/Nethermind.Consensus/Transactions/IInclusionListTxSource.cs +++ b/src/Nethermind/Nethermind.Consensus/Transactions/IInclusionListTxSource.cs @@ -18,5 +18,5 @@ public interface IInclusionListTxSource : ITxSource /// The build's Profile 2 candidates that some committee position's VERIFY budget fill admits, so the /// build answers each it fails to append with an omission claim; null when there are none. - IReadOnlySet? GetProfile2Candidates(PayloadAttributes? payloadAttributes, ulong maxVerifyGasPerTx); + IReadOnlySet? GetProfile2Candidates(PayloadAttributes? payloadAttributes); } diff --git a/src/Nethermind/Nethermind.Consensus/Transactions/InclusionListTxSource.cs b/src/Nethermind/Nethermind.Consensus/Transactions/InclusionListTxSource.cs index 4869a6e14ec4..f9e4d94fb0d5 100644 --- a/src/Nethermind/Nethermind.Consensus/Transactions/InclusionListTxSource.cs +++ b/src/Nethermind/Nethermind.Consensus/Transactions/InclusionListTxSource.cs @@ -39,8 +39,8 @@ public class InclusionListTxSource( /// position by position for the per-IL VERIFY budget fill. private sealed record DecodedInclusionLists(Transaction[] ForProduction, Transaction[][] ByPosition, IReleaseSpec Spec) { - /// The fill under the cap it ran with; every improvement of one build asks again. - public (ulong MaxVerifyGasPerTx, IReadOnlySet? Candidates)? Profile2Candidates; + /// The fill, computed once; every improvement of one build asks again. + public StrongBox?>? Profile2Candidates; } /// @@ -52,14 +52,14 @@ public IEnumerable GetTransactions(BlockHeader parent, BlockHeader if (!TryGetDecoded(payloadAttributes, out DecodedInclusionLists? decoded)) return []; if (!Eip8369Profile2.IsActive(decoded.Spec)) return decoded.ForProduction; - IReadOnlySet? admitted = GetProfile2Candidates(payloadAttributes, Eip8369Constants.MaxVerifyGasPerTx); + IReadOnlySet? admitted = GetProfile2Candidates(payloadAttributes); return decoded.ForProduction.Where(tx => !tx.SupportsFrames || (admitted is not null && tx.Hash is not null && admitted.Contains(tx.Hash))); } - public IReadOnlySet? GetProfile2Candidates(PayloadAttributes? payloadAttributes, ulong maxVerifyGasPerTx) + public IReadOnlySet? GetProfile2Candidates(PayloadAttributes? payloadAttributes) { if (!TryGetDecoded(payloadAttributes, out DecodedInclusionLists? decoded)) return null; - if (decoded.Profile2Candidates is { } cached && cached.MaxVerifyGasPerTx == maxVerifyGasPerTx) return cached.Candidates; + if (decoded.Profile2Candidates is { } cached) return cached.Value; IReleaseSpec spec = decoded.Spec; // EIP-7805: before Profile 2 is active no entry is a candidate, so the build claims nothing. @@ -67,10 +67,10 @@ public IEnumerable GetTransactions(BlockHeader parent, BlockHeader Func signaturesValid = profile2Replayer is not null ? tx => profile2Replayer.AreSignaturesValid(tx, spec) : tx => Profile2EligibilityReplayer.AreSignaturesValid(tx, ecdsa, spec); - HashSet admitted = Eip8369Profile2.AdmitByVerifyBudget(InclusionLists.InFillOrder(decoded.ByPosition), maxVerifyGasPerTx, signaturesValid, + HashSet admitted = Eip8369Profile2.AdmitByVerifyBudget(InclusionLists.InFillOrder(decoded.ByPosition), Eip8369Constants.MaxVerifyGasPerTx, signaturesValid, tx => InclusionListValidator.Profile2StaticChecks.IsWellFormed(tx, spec)); IReadOnlySet? candidates = admitted.Count > 0 ? admitted : null; - decoded.Profile2Candidates = (maxVerifyGasPerTx, candidates); + decoded.Profile2Candidates = new(candidates); return candidates; } diff --git a/src/Nethermind/Nethermind.Merge.Plugin.Test/EngineModuleTests.Eip8369.cs b/src/Nethermind/Nethermind.Merge.Plugin.Test/EngineModuleTests.Eip8369.cs index ecd7dbb6717d..c34607ae0c9f 100644 --- a/src/Nethermind/Nethermind.Merge.Plugin.Test/EngineModuleTests.Eip8369.cs +++ b/src/Nethermind/Nethermind.Merge.Plugin.Test/EngineModuleTests.Eip8369.cs @@ -81,7 +81,6 @@ public async Task NewPayloadWithWitnessV6_carries_inclusion_lists_and_claims(boo Assert.That(newPayload.Data.Status, Is.EqualTo(PayloadStatus.Valid), newPayload.Result.Error); } - /// Claims change the verdict, so the same block and lists under other claims are another check. [Test] public async Task NewPayloadV6_classifies_candidates_by_the_forks_verify_gas_cap_whatever_the_local_cap() { @@ -112,6 +111,7 @@ public async Task NewPayloadV6_accepts_the_claims_of_a_block_built_under_a_lower } } + /// Claims change the verdict, so the same block and lists under other claims are another check. [Test] public async Task NewPayloadV6_does_not_reuse_a_verdict_checked_under_other_claims() { diff --git a/src/Nethermind/Nethermind.Merge.Plugin.Test/EngineModuleTests.V7.cs b/src/Nethermind/Nethermind.Merge.Plugin.Test/EngineModuleTests.V7.cs index 521cd3e9a270..51552e7d9c70 100644 --- a/src/Nethermind/Nethermind.Merge.Plugin.Test/EngineModuleTests.V7.cs +++ b/src/Nethermind/Nethermind.Merge.Plugin.Test/EngineModuleTests.V7.cs @@ -1157,8 +1157,8 @@ public IEnumerable GetTransactions(BlockHeader parent, BlockHeader public void Set(byte[][][] inclusionLists, IReleaseSpec spec) => inner.Set(inclusionLists, spec); - public IReadOnlySet? GetProfile2Candidates(PayloadAttributes? payloadAttributes, ulong maxVerifyGasPerTx) => - inner.GetProfile2Candidates(payloadAttributes, maxVerifyGasPerTx); + public IReadOnlySet? GetProfile2Candidates(PayloadAttributes? payloadAttributes) => + inner.GetProfile2Candidates(payloadAttributes); } // A canonical block this node ran is VALID, and its inclusion check is judged against its own state; once that diff --git a/src/Nethermind/Nethermind.Merge.Plugin/BlockProduction/PostMergeBlockProducer.cs b/src/Nethermind/Nethermind.Merge.Plugin/BlockProduction/PostMergeBlockProducer.cs index 74cf5b73fcb9..4a4ff84bb059 100644 --- a/src/Nethermind/Nethermind.Merge.Plugin/BlockProduction/PostMergeBlockProducer.cs +++ b/src/Nethermind/Nethermind.Merge.Plugin/BlockProduction/PostMergeBlockProducer.cs @@ -55,7 +55,7 @@ protected override BlockToProduce PrepareBlock(BlockHeader parent, PayloadAttrib blockToProduce.Transactions = inclusionList; } } - blockToProduce.InclusionListCandidates = inclusionListTxSource?.GetProfile2Candidates(payloadAttributes, Eip8369Constants.MaxVerifyGasPerTx); + blockToProduce.InclusionListCandidates = inclusionListTxSource?.GetProfile2Candidates(payloadAttributes); return blockToProduce; }