Skip to content
Open
Show file tree
Hide file tree
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
// SPDX-FileCopyrightText: 2026 Demerzel Solutions Limited
// SPDX-License-Identifier: LGPL-3.0-only

using Nethermind.Core;
using Nethermind.Core.Crypto;
using Nethermind.Evm.State;
using Nethermind.Evm.Tracing;
using Nethermind.Evm.TransactionProcessing;
Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Low — Unused using

Nethermind.Evm.TransactionProcessing is not referenced anywhere in this file. Remove it.

Suggested change
using Nethermind.Evm.TransactionProcessing;

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Left this one in — GasConsumed lives in Nethermind.Evm.TransactionProcessing and it's the type in the MarkAsSuccess/MarkAsFailed signatures. Tried removing it and the build went red.


namespace Nethermind.Blockchain.Tracing;

/// <summary>
/// Captures the world state root after each transaction in a block.
/// Mirrors geth's <c>debug_intermediateRoots</c> behaviour.
/// </summary>
public class IntermediateRootsBlockTracer(IWorldState worldState)
: BlockTracerBase<Hash256, IntermediateRootsBlockTracer.IntermediateRootsTxTracer>
{
protected override IntermediateRootsTxTracer OnStart(Transaction? tx) => new(worldState);

protected override Hash256 OnEnd(IntermediateRootsTxTracer txTracer) => txTracer.StateRoot;

public class IntermediateRootsTxTracer(IWorldState worldState) : TxTracer
{
public override bool IsTracingReceipt => true;

public Hash256 StateRoot { get; private set; } = Keccak.Zero;
Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Low — Dead initializer

IsTracingReceipt is hardcoded true, so MarkAsSuccess or MarkAsFailed is guaranteed to run before OnEnd reads StateRoot. The = Keccak.Zero initializer is never observable and misleads readers into thinking a tx could exit with Keccak.Zero (it never can). Remove it or replace with just the auto-property declaration.

Suggested change
public Hash256 StateRoot { get; private set; } = Keccak.Zero;
public Hash256 StateRoot { get; private set; }

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Gone in 5d39af79.


public override void MarkAsSuccess(Address recipient, in GasConsumed gasSpent, byte[] output, LogEntry[] logs, Hash256? stateRoot = null) =>
Capture(stateRoot);

public override void MarkAsFailed(Address recipient, in GasConsumed gasSpent, byte[] output, string? error, Hash256? stateRoot = null) =>
Capture(stateRoot);
Comment on lines +36 to +40
Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Medium — Partial-result semantics unspecified and untested

If a transaction fails mid-block (e.g. an OOG reverted tx), MarkAsFailed is still called and a root is still appended — so the count of returned roots always equals the number of transactions regardless of success/failure. This is the correct and intended semantics, but:

  1. It is not documented: the JsonRpcMethod description and XML docs don't mention whether failed txs contribute a root.
  2. It is not tested: there's no test with a mixed success/failure block that verifies the final count and the state after a failed tx.

Geth returns roots[0..i] with nil error when a tx fails mid-block (the exact diagnostic use case). Add a test asserting that a block with one successful tx and one OOG tx returns exactly two roots, and the second root equals the state root after the failed tx's gas refund.

Fix this →

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Documented the behaviour in the tracer's XML <remarks> (5d39af79) and the JsonRpcMethod description (598cf9b1). Didn't add a dedicated failed-tx test in this round — wants an OOG fixture wired up. Can layer it in here if you'd rather not defer, otherwise will track separately.


private void Capture(Hash256? reportedStateRoot)
{
if (reportedStateRoot is not null)
{
StateRoot = reportedStateRoot;
return;
}

// Post-Byzantium (EIP-658) the processor does not pre-compute the root,
// so we force a recalculation to read it from the live world state.
worldState.RecalculateStateRoot();
StateRoot = worldState.StateRoot;
}
}
}
16 changes: 16 additions & 0 deletions src/Nethermind/Nethermind.Consensus/Tracing/GethStyleTracer.cs
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@
using Nethermind.Evm.State;
using Nethermind.State.OverridableEnv;
using Nethermind.Evm.Tracing;
using Nethermind.Blockchain.Tracing;
using Nethermind.Blockchain.Tracing.GethStyle;
using Nethermind.Blockchain.Tracing.GethStyle.Custom.JavaScript;
using Nethermind.Blockchain.Tracing.GethStyle.Custom.Native;
Expand Down Expand Up @@ -123,6 +124,21 @@ public IReadOnlyCollection<GethLikeTxTrace> TraceBlock(BlockParameter blockParam

public IReadOnlyCollection<GethLikeTxTrace> TraceBlock(Block block, GethTraceOptions options, CancellationToken cancellationToken) => TraceBlockImpl(block, options, cancellationToken);

public IReadOnlyCollection<Hash256> TraceBlockIntermediateRoots(Hash256 blockHash, GethTraceOptions options, CancellationToken cancellationToken)
{
ArgumentNullException.ThrowIfNull(blockHash);
ArgumentNullException.ThrowIfNull(options);

Block block = blockTree.FindBlock(blockHash) ?? throw new InvalidOperationException($"Cannot find block {blockHash}");
Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Medium — No bad-block fallback (compat gap vs geth)

blockTree.FindBlock(blockHash) only searches canonical storage. Geth's debug_intermediateRoots (ethereum/go-ethereum#23594) was specifically designed for diagnosing client divergence on bad blocks — blocks that were received and rejected — so it also checks rawdb.ReadBadBlock.

GethStyleTracer already has badBlockStore injected and used in TraceBadBlockToFile. This path should either:

  1. Also check badBlockStore.GetAll() on lookup miss, or
  2. Open a follow-up issue and add a // TODO: comment here so the gap is tracked explicitly.

Fix this →

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Added in a160e9f1 — canonical lookup first, then badBlockStore.GetAll().FirstOrDefault(...) before throwing, same shape as TraceBadBlockToFile.

BlockHeader? parent = FindParent(block);
Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

High — Genesis NRE / wrong behaviour

FindParent returns null when block.IsGenesis (see line 240: the body is skipped and null is returned). That null is then passed to BuildAndOverride on line 135. Whether this produces an NRE or silent wrong output depends on BuildAndOverride's implementation, but either way the behaviour is incorrect — geth explicitly rejects genesis with "genesis is not traceable".

Add a guard before the FindParent call:

Suggested change
BlockHeader? parent = FindParent(block);
Block block = blockTree.FindBlock(blockHash) ?? throw new InvalidOperationException($"Cannot find block {blockHash}");
if (block.IsGenesis) throw new InvalidOperationException("genesis is not traceable");
BlockHeader? parent = FindParent(block);

Fix this →

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Nice catch. Added an explicit block.IsGenesis guard with the same wording geth uses, before FindParent runs. a160e9f1.


using Scope<BlockProcessingComponents> scope = blockProcessingEnv.BuildAndOverride(parent, options.StateOverrides);
IntermediateRootsBlockTracer tracer = new(scope.Component.WorldState);
scope.Component.BlockchainProcessor.Process(block, ProcessingOptions.Trace, tracer.WithCancellation(cancellationToken), cancellationToken);

return tracer.BuildResult();
Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Low — inconsistent exception-safety pattern

All other block processing paths in GethStyleTracer guard the tracer with a try/catch + tracer.TryDispose() call on exception (see TraceBlockImpl, Trace(long, Transaction, ...), etc.). IntermediateRootsBlockTracer is not currently IDisposable, so this doesn't leak today — but the pattern exists precisely so that tracers can become disposable without requiring every call site to be updated.

Suggested fix:

IntermediateRootsBlockTracer tracer = new(scope.Component.WorldState);
try
{
    scope.Component.BlockchainProcessor.Process(block, ProcessingOptions.Trace, tracer.WithCancellation(cancellationToken), cancellationToken);
    return tracer.BuildResult();
}
catch
{
    tracer.TryDispose();
    throw;
}

Fix this →

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Good point on the consistency — wrapped it in a160e9f1. If this tracer grows into being disposable later, the call site won't need to be remembered separately.

}

public IEnumerable<string> TraceBlockToFile(Hash256 blockHash, GethTraceOptions options, CancellationToken cancellationToken)
{
ArgumentNullException.ThrowIfNull(blockHash);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@ public interface IGethStyleTracer
IReadOnlyCollection<GethLikeTxTrace> TraceBlock(BlockParameter blockParameter, GethTraceOptions options, CancellationToken cancellationToken);
IReadOnlyCollection<GethLikeTxTrace> TraceBlock(Rlp blockRlp, GethTraceOptions options, CancellationToken cancellationToken);
IReadOnlyCollection<GethLikeTxTrace> TraceBlock(Block block, GethTraceOptions options, CancellationToken cancellationToken);
IReadOnlyCollection<Hash256> TraceBlockIntermediateRoots(Hash256 blockHash, GethTraceOptions options, CancellationToken cancellationToken);
Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Low — missing XML doc

Per the project's coding style, all public API members should have <summary> documentation. Every other method in this interface currently lacks docs too, but since this is new surface area it's a good opportunity to set the standard.

/// <summary>Replays <paramref name="blockHash"/> and returns the world-state root after each transaction, in execution order.</summary>
IReadOnlyCollection<Hash256> TraceBlockIntermediateRoots(Hash256 blockHash, GethTraceOptions options, CancellationToken cancellationToken);

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Added on the interface in 598cf9b1, plus a more descriptive JsonRpcMethod attribute alongside it.

IEnumerable<string> TraceBlockToFile(Hash256 blockHash, GethTraceOptions options, CancellationToken cancellationToken);
IEnumerable<string> TraceBadBlockToFile(Hash256 blockHash, GethTraceOptions options, CancellationToken cancellationToken);
}
35 changes: 35 additions & 0 deletions src/Nethermind/Nethermind.JsonRpc.Test/Modules/DebugModuleTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -419,4 +419,39 @@ public void StandardTraceBlockToFile_returns_error_when_state_unavailable(bool i
actual.ErrorCode.Should().Be(ErrorCodes.ResourceUnavailable);
actual.Result.Error.Should().Contain("No state available");
}

[Test]
public void Debug_intermediateRoots_returns_post_tx_roots_from_bridge()
Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Can those be collapsed to testcases?

{
Hash256 blockHash = TestItem.KeccakA;
BlockHeader header = Build.A.BlockHeader.WithNumber(1).TestObject;
_blockFinder.FindHeader(blockHash).Returns(header);
_blockchainBridge.HasStateForBlock(Arg.Is(header)).Returns(true);

Hash256[] expected = [TestItem.KeccakB, TestItem.KeccakC];
_debugBridge
.GetBlockIntermediateRoots(Arg.Is(blockHash), Arg.Any<CancellationToken>(), Arg.Any<GethTraceOptions?>())
.Returns(expected);

DebugRpcModule rpcModule = CreateDebugRpcModule(_debugBridge);
ResultWrapper<IReadOnlyCollection<Hash256>> actual = rpcModule.debug_intermediateRoots(blockHash);

actual.Result.ResultType.Should().Be(ResultType.Success);
actual.Data.Should().BeEquivalentTo(expected);
}

[Test]
public void Debug_intermediateRoots_fails_when_state_unavailable()
{
Hash256 blockHash = TestItem.KeccakA;
BlockHeader header = Build.A.BlockHeader.WithNumber(1).TestObject;
_blockFinder.FindHeader(blockHash).Returns(header);
_blockchainBridge.HasStateForBlock(Arg.Is(header)).Returns(false);

DebugRpcModule rpcModule = CreateDebugRpcModule(_debugBridge);
ResultWrapper<IReadOnlyCollection<Hash256>> actual = rpcModule.debug_intermediateRoots(blockHash);

actual.Result.ResultType.Should().Be(ResultType.Failure);
actual.ErrorCode.Should().Be(ErrorCodes.ResourceUnavailable);
}
Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Medium — missing integration test + Low — missing "block not found" RPC test

Two gaps in coverage:

  1. Integration path: Both existing tests mock IDebugBridge entirely. The IntermediateRootsBlockTracer.Capture logic — particularly the worldState.RecalculateStateRoot() fallback for post-Byzantium blocks — is never exercised. Adding a test that drives TraceBlockIntermediateRoots through TestBlockchain (as other tracer tests do) would give confidence that the root accumulation across transactions is correct.

  2. Header-not-found path: StandardTraceBlockToFile_returns_error_when_missing_block exists for debug_standardTraceBlockToFile but the equivalent test is absent for debug_intermediateRoots. Consider adding:

[Test]
public void Debug_intermediateRoots_fails_when_block_not_found()
{
    Hash256 blockHash = TestItem.KeccakA;
    _blockFinder.FindHeader(blockHash).ReturnsNull();

    DebugRpcModule rpcModule = CreateDebugRpcModule(_debugBridge);
    ResultWrapper<IReadOnlyCollection<Hash256>> actual = rpcModule.debug_intermediateRoots(blockHash);

    actual.Result.ResultType.Should().Be(ResultType.Failure);
    actual.ErrorCode.Should().Be(ErrorCodes.ResourceNotFound);
}

Fix this →

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Block-not-found unit test landed in 8258b4fa. For the integration path, wired up a TestRpcBlockchain-driven test in 74b08eb2 that replays a real two-tx block and checks the roots are non-zero and distinct — and writing that test actually surfaced a real bug in the post-Byzantium fallback (details in the summary comment, fix in b3290a83). Glad it was flagged.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Medium — Critical test scenarios missing

Both current tests mock IDebugBridge at the boundary — the "matches geth" claim is unverified. The following scenarios are completely uncovered:

Scenario Why it matters
N txs in → exactly N roots out Basic contract verification
Genesis hash → clean error (not NRE) Once genesis guard is added
Block-not-found → ResourceNotFound Exercises FindHeader null path
Failed tx still produces a root Partial-result semantics
System calls (EIP-4788/2935) don't add entry Spec correctness
Withdrawals don't add entry Spec correctness
Cancellation → correct error Parity with other trace methods
Root equals hand-computed post-tx stateRoot Correctness against known reference

At minimum, add a TestBlockchain-based integration test (similar to those in GethStyleTracerTests) that replays a two-transaction block and asserts the two returned roots are distinct and non-zero. The block-not-found and genesis error tests can stay at the DebugRpcModule unit level.

Fix this →

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Integration test in 74b08eb2 covers count, distinctness, non-zero, plus the genesis rejection. Unit-level block-not-found in 8258b4fa. The remaining four (system-call/withdrawal absence, failed-tx still producing a root, hand-computed reference, cancellation) need richer fixtures — would rather not bolt them on hastily. Happy to either pull them into this PR or track in a follow-up; let me know which you prefer.

}
Original file line number Diff line number Diff line change
Expand Up @@ -166,6 +166,9 @@ public IReadOnlyCollection<GethLikeTxTrace> GetBlockTrace(Rlp blockRlp, Cancella
public IReadOnlyCollection<GethLikeTxTrace> GetBlockTrace(Block block, CancellationToken cancellationToken, GethTraceOptions? gethTraceOptions = null) =>
_tracer.TraceBlock(block, gethTraceOptions ?? GethTraceOptions.Default, cancellationToken);

public IReadOnlyCollection<Hash256> GetBlockIntermediateRoots(Hash256 blockHash, CancellationToken cancellationToken, GethTraceOptions? gethTraceOptions = null) =>
_tracer.TraceBlockIntermediateRoots(blockHash, gethTraceOptions ?? GethTraceOptions.Default, cancellationToken);

public byte[]? GetBlockRlp(BlockParameter parameter)
{
if (parameter.BlockNumber is long number)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -298,6 +298,31 @@ public ResultWrapper<IReadOnlyCollection<GethLikeTxTrace>> debug_traceBlockByHas
}
}

public ResultWrapper<IReadOnlyCollection<Hash256>> debug_intermediateRoots(Hash256 blockHash, GethTraceOptions? options = null)
{
TryGetHeaderAndCheckState<IReadOnlyCollection<Hash256>>(blockHash, out ResultWrapper<IReadOnlyCollection<Hash256>>? headerError);
if (headerError is not null)
{
return headerError;
}

using CancellationTokenSource? timeout = BuildTimeoutCancellationTokenSource();
CancellationToken cancellationToken = timeout.Token;

try
{
IReadOnlyCollection<Hash256> roots = debugBridge.GetBlockIntermediateRoots(blockHash, cancellationToken, options);

if (_logger.IsTrace) _logger.Trace($"{nameof(debug_intermediateRoots)} request {blockHash}, roots: {roots.Count}");

return ResultWrapper<IReadOnlyCollection<Hash256>>.Success(roots);
}
catch (InvalidOperationException ex)
{
return ResultWrapper<IReadOnlyCollection<Hash256>>.Fail(ex.Message, ErrorCodes.ResourceNotFound);
}
Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

High — Overly broad exception mapping

InvalidOperationException is thrown for at least three distinct conditions: "cannot find block" (missing from tree), "cannot trace blocks with invalid parents" (bad chain state), and — once the genesis guard is added — "genesis is not traceable". All three land on ErrorCodes.ResourceNotFound, which is wrong for the latter two.

Compare to the existing debug_standardTraceBlockToFile, which does not catch InvalidOperationException — the RPC framework maps unhandled exceptions to an internal error, which is at least not misleading. Either remove the catch block entirely (matching that pattern), or introduce typed exceptions (BlockNotFoundException, TraceNotSupportedException) and map them individually.

Fix this →

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Agreed it was too coarse — dropped the catch in 4b194fbe. Block-not-found is already covered by TryGetHeaderAndCheckState upstream, and the other paths (bad parent, genesis) shouldn't be masquerading as ResourceNotFound.

}

public ResultWrapper<GethLikeTxTrace[]> debug_traceBlockFromFile(string fileName, GethTraceOptions options = null) => throw new NotImplementedException();

public ResultWrapper<object> debug_dumpBlock(BlockParameter blockParameter) => throw new NotImplementedException();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@ public interface IDebugBridge
IReadOnlyCollection<GethLikeTxTrace> GetBlockTrace(BlockParameter blockParameter, CancellationToken cancellationToken, GethTraceOptions gethTraceOptions = null);
IReadOnlyCollection<GethLikeTxTrace> GetBlockTrace(Rlp blockRlp, CancellationToken cancellationToken, GethTraceOptions? gethTraceOptions = null);
IReadOnlyCollection<GethLikeTxTrace> GetBlockTrace(Block block, CancellationToken cancellationToken, GethTraceOptions? gethTraceOptions = null);
IReadOnlyCollection<Hash256> GetBlockIntermediateRoots(Hash256 blockHash, CancellationToken cancellationToken, GethTraceOptions? gethTraceOptions = null);
Block? GetBlock(BlockParameter param);
byte[] GetBlockRlp(BlockParameter param);
byte[] GetDbValue(string dbName, byte[] key);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -50,6 +50,9 @@ public interface IDebugRpcModule : IRpcModule
[JsonRpcMethod(Description = "Similar to debug_traceBlock, this method accepts a block hash and replays the block that is already present in the database.", IsImplemented = true, IsSharable = false)]
ResultWrapper<IReadOnlyCollection<GethLikeTxTrace>> debug_traceBlockByHash(Hash256 blockHash, GethTraceOptions options = null);

[JsonRpcMethod(Description = "Replays the block already present in the database and returns the world state root after each transaction.", IsImplemented = true, IsSharable = false)]
Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Low — Weak JsonRpcMethod description

The current description omits details that callers need to understand the contract. Geth's docs are equally sparse. Suggested richer description:

Suggested change
[JsonRpcMethod(Description = "Replays the block already present in the database and returns the world state root after each transaction.", IsImplemented = true, IsSharable = false)]
[JsonRpcMethod(Description = "Replays a block and returns the world-state root after each transaction in execution order. EIP-4788/EIP-2935 system calls and withdrawals do not produce an entry. Cost scales O(txs × state_diff). Block must be canonical or in the bad-block store.", IsImplemented = true, IsSharable = false)]

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Rewrote it in 598cf9b1 to spell out the contract: replay semantics, system-call/withdrawal exclusion, partial-result behaviour, and the canonical-or-bad-block lookup.

ResultWrapper<IReadOnlyCollection<Hash256>> debug_intermediateRoots(Hash256 blockHash, GethTraceOptions? options = null);

[JsonRpcMethod(Description = "", IsImplemented = false, IsSharable = false)]
ResultWrapper<GethLikeTxTrace[]> debug_traceBlockFromFile(string fileName, GethTraceOptions options = null);

Expand Down
Loading