Skip to content
Open
Show file tree
Hide file tree
Changes from all 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,201 @@
// SPDX-FileCopyrightText: 2026 Demerzel Solutions Limited
// SPDX-License-Identifier: LGPL-3.0-only

using System;
using System.Buffers;
using System.Collections.Generic;
using System.IO;
using System.Text.Json;
using Nethermind.Core;
using Nethermind.Core.Crypto;
using Nethermind.Core.Extensions;
using Nethermind.Core.Specs;
using Nethermind.Evm;
using Nethermind.Evm.Tracing;
using Nethermind.Evm.TransactionProcessing;
using Nethermind.Int256;
using Nethermind.Serialization.Json;

namespace Nethermind.Blockchain.Tracing.GethStyle.Custom.Native.Call;

/// <summary>Renders the native call tracer's frames in Geth's flat, Parity-style format.</summary>
internal sealed class NativeFlatCallTracer : GethLikeNativeTxTracer, IFrameTxReceiptTracer
{
internal const string FlatCallTracer = "flatCallTracer";
private readonly NativeCallTracer _inner;
private readonly IReleaseSpec _spec;
private readonly GethTraceOptions _options;
private readonly JsonConfig _config;
private readonly Hash256? _blockHash;
private readonly ulong _blockNumber;
private readonly Hash256? _txHash;
private readonly int _position;
private GethLikeTxTrace? _result;

internal NativeFlatCallTracer(Transaction tx, Block block, IReleaseSpec spec, GethTraceOptions options) : base(options)
{
_config = ParseConfig(options.TracerConfig);
_spec = spec;
_options = options;
if (!options.IsTraceCall)
{
_blockHash = block.Hash;
_blockNumber = block.Number;
_txHash = tx.Hash;
_position = Array.IndexOf(block.Transactions, tx);
}
_inner = new NativeCallTracer(tx, spec, options with { Tracer = NativeCallTracer.CallTracer, TracerConfig = null });
IsTracingActions = true;
IsTracingStack = false;
IsTracingOpLevelStorage = false;
IsTracingReturnData = false;
}

internal static JsonConfig ParseConfig(JsonElement? config) =>
GethLikeNativeTracerFactory.ParseConfig<JsonConfig>(config, EthereumJsonSerializer.JsonOptions) ?? new();

internal sealed class JsonConfig
{
public bool? IncludePrecompiles { get; set => field = value ?? field; } = false;
public bool? ConvertParityErrors { get; set => field = value ?? field; } = false;
}

public override bool IsTracingInstructions => false;

public override void ReportAction(ulong gas, UInt256 value, Address from, Address to, ReadOnlyMemory<byte> input, ExecutionType callType, bool isPrecompileCall = false) =>
_inner.ReportAction(gas, value, from, to, input, callType, isPrecompileCall);

public override void ReportRejectedAction(ulong gas, ulong gasLeft, UInt256 value, Address from, Address to, ReadOnlyMemory<byte> input, ExecutionType callType, EvmExceptionType error, bool isPrecompileCall = false) =>
_inner.ReportRejectedAction(gas, gasLeft, value, from, to, input, callType, error, isPrecompileCall);

public override void ReportActionEnd(ulong gas, Address deploymentAddress, ReadOnlyMemory<byte> deployedCode) => _inner.ReportActionEnd(gas, deploymentAddress, deployedCode);
public override void ReportActionEnd(ulong gas, ReadOnlyMemory<byte> output) => _inner.ReportActionEnd(gas, output);
public override void ReportActionError(EvmExceptionType error) => _inner.ReportActionError(error);
public override void ReportActionErrorDetails(string error) => _inner.ReportActionErrorDetails(error);
public override void ReportActionRevert(ulong gas, ReadOnlyMemory<byte> output) => _inner.ReportActionRevert(gas, output);
public override void ReportSelfDestruct(Address address, UInt256 balance, Address refundAddress) => _inner.ReportSelfDestruct(address, balance, refundAddress);
public override void MarkAsSuccess(Address recipient, in GasConsumed gasSpent, byte[] output, LogEntry[] logs, Hash256? stateRoot = null) => _inner.MarkAsSuccess(recipient, gasSpent, output, logs, stateRoot);
public override void MarkAsFailed(Address recipient, in GasConsumed gasSpent, byte[] output, string? error, Hash256? stateRoot = null) => _inner.MarkAsFailed(recipient, gasSpent, output, error, stateRoot);
public void ReportFrameTxReceipt(Address payer, TxFrameReceipt[] frameReceipts) => _inner.ReportFrameTxReceipt(payer, frameReceipts);
public void ReportFrameEnd(int frameIndex, EvmExceptionType? error) => _inner.ReportFrameEnd(frameIndex, error);
public void ReportFramesRolledBack(int fromFrameIndex, int toFrameIndex) => _inner.ReportFramesRolledBack(fromFrameIndex, toFrameIndex);

public override GethLikeTxTrace BuildResult()
{
if (_result is not null) return _result;
using GethLikeTxTrace trace = _inner.BuildResult();
if (trace.CustomTracerResult?.Value is not NativeCallTracerCallFrame root)
throw new InvalidDataException("invalid number of calls");
ArrayBufferWriter<byte> buffer = new();
using (Utf8JsonWriter writer = new(buffer))
{
writer.WriteStartArray();
Stack<(NativeCallTracerCallFrame Frame, int[] Path)> pending = new();
pending.Push((root, []));
while (pending.TryPop(out (NativeCallTracerCallFrame Frame, int[] Path) item))
{
_options.ExecutionCancellationToken.ThrowIfCancellationRequested();
_options.DeadlineScope?.Current?.Token.ThrowIfCancellationRequested();
int children = 0;
foreach (NativeCallTracerCallFrame child in item.Frame.CallsSpan)
if (!Skip(child)) children++;
WriteFrame(writer, item.Frame, item.Path, children);
ReadOnlySpan<NativeCallTracerCallFrame> calls = item.Frame.CallsSpan;
for (int i = calls.Length - 1; i >= 0; i--)
{
NativeCallTracerCallFrame child = calls[i];
if (Skip(child)) continue;
int[] path = new int[item.Path.Length + 1];
item.Path.CopyTo(path, 0);
path[^1] = --children;
pending.Push((child, path));
}
}
writer.WriteEndArray();
}
using JsonDocument document = JsonDocument.Parse(buffer.WrittenMemory);

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: perf. Each tx's output is built three times: written into an ArrayBufferWriter, parsed into a JsonDocument, then Clone()d into another buffer. With large block traces (thousands of frames per tx), this is noticeable overhead. One option: snapshot into a small typed frame list (or a byte[] plus a raw-JSON value holder) before disposing _inner, and let the serializer write it once. Also, Array.IndexOf(block.Transactions, tx) (line 45) runs once per tx, so block tracing is O(n²). The block tracer already knows the index, though passing it through would mean changing the factory signature, so this is optional.

return _result = new GethLikeTxTrace
{
TxHash = trace.TxHash,
CustomTracerResult = new GethLikeCustomTrace { Value = document.RootElement.Clone() }
};
}

private bool Skip(NativeCallTracerCallFrame frame) => _config.IncludePrecompiles != true
&& frame.Type is Instruction.CALL or Instruction.STATICCALL
&& frame.To is { } to && _spec.IsPrecompile(to);

private void WriteFrame(Utf8JsonWriter writer, NativeCallTracerCallFrame frame, int[] path, int children)
{
bool create = frame.Type is Instruction.CREATE or Instruction.CREATE2;
bool suicide = frame.Type == Instruction.SELFDESTRUCT;
if (!create && !suicide && frame.Type is not (Instruction.CALL or Instruction.STATICCALL or Instruction.CALLCODE or Instruction.DELEGATECALL))
throw new InvalidDataException($"unrecognized call frame type: {frame.Type}");
writer.WriteStartObject();
writer.WritePropertyName("action");
writer.WriteStartObject();
if (suicide)
{
writer.WriteString("address", frame.From?.ToString());
writer.WriteString("balance", Quantity(frame.Value ?? UInt256.Zero));
writer.WriteString("refundAddress", frame.To?.ToString());
}
else
{
writer.WriteString(create ? "creationMethod" : "callType", frame.Type.ToString().ToLowerInvariant());
writer.WriteString("from", frame.From?.ToString());
writer.WriteString("gas", Quantity(frame.Gas));
WriteBytes(writer, create ? "init" : "input", frame.Input);
if (!create && frame.To is { } to) writer.WriteString("to", to.ToString());
writer.WriteString("value", Quantity(frame.Value ?? UInt256.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.

Medium: Geth parity, STATICCALL value

Geth's StaticCall calls captureBegin(..., STATICCALL, ..., nil), so callFrame.Value is nil. flatCallAction.Value is *big.Int with json:"value,omitempty", so Geth leaves value out of staticcall actions. NativeCallTracer already copies this: it sets Value = null for STATICCALL (NativeCallTracer.cs:153/464). The ?? UInt256.Zero here puts back "value":"0x0". Debug_traceCall_flatCallTracer_filters_and_renumbers_precompiles asserts that wrong value (rows[2]["action"]["value"] == "0x0" for the staticcall row).

Suggested change
writer.WriteString("value", Quantity(frame.Value ?? UInt256.Zero));
if (frame.Value is { } value) writer.WriteString("value", Quantity(value));

Then update the test to expect no value on the staticcall row.

}
writer.WriteEndObject();
writer.WriteString("blockHash", _blockHash?.ToString());
writer.WriteNumber("blockNumber", _blockNumber);
if (!string.IsNullOrEmpty(frame.Error))
writer.WriteString("error", _config.ConvertParityErrors == true ? ConvertError(frame.Error) : frame.Error);
if (!suicide && (string.IsNullOrEmpty(frame.Error) || frame.Error == "execution reverted"))
{
writer.WritePropertyName("result");
writer.WriteStartObject();
if (create && frame.To is { } address) writer.WriteString("address", address.ToString());
WriteBytes(writer, create ? "code" : "output", frame.Output);
writer.WriteString("gasUsed", Quantity(frame.GasUsed));
writer.WriteEndObject();
}
writer.WriteNumber("subtraces", children);
writer.WritePropertyName("traceAddress");
writer.WriteStartArray();
foreach (int part in path) writer.WriteNumberValue(part);
writer.WriteEndArray();
writer.WriteString("transactionHash", _txHash?.ToString());
writer.WriteNumber("transactionPosition", _position);
writer.WriteString("type", suicide ? "suicide" : create ? "create" : "call");
writer.WriteEndObject();
}

private static string Quantity(UInt256 value) => value.ToHexString(skipLeadingZeros: true);
private static void WriteBytes(Utf8JsonWriter writer, string name, ReadOnlyMemory<byte> value) =>
writer.WriteString(name, "0x" + Convert.ToHexStringLower(value.Span));

/// <remarks>Geth native/call_flat.go maps the call tracer's error text, not the EVM exception categories.</remarks>
private static string ConvertError(string error) => error switch
{
"contract creation code storage out of gas" or "out of gas" or "gas uint64 overflow" or "max code size exceeded" => "Out of gas",
"invalid jump destination" => "Bad jump destination",
"execution reverted" => "Reverted",
"return data out of bounds" => "Out of bounds",
"stack limit reached 1024 (1023)" => "Out of stack",
"precompiled failed" or "invalid input length" => "Built-in failed",
_ when error.StartsWith("out of gas:", StringComparison.Ordinal) => "Out of gas",

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: this mapping isn't in Geth. Geth's parityErrorMappingStartingWith has only invalid opcode: and stack underflow. Nethermind's error text out of gas: not enough gas for reentrancy sentry matches Geth's not enough gas for reentrancy sentry, which Geth does not convert. With convertParityErrors, Geth returns the raw text and this code returns Out of gas. If this is on purpose, add a short comment saying why; if not, remove the line.

_ when error.StartsWith("invalid opcode:", StringComparison.Ordinal) => "Bad instruction",
_ when error.StartsWith("stack underflow", StringComparison.Ordinal) => "Stack underflow",
_ => error
};

public override void Dispose()
{
_inner.Dispose();
base.Dispose();
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,7 @@ private static void RegisterNativeTracers()
_tracers.Add(NativeKeccakPreimageTracer.KeccakPreimageTracer, static (options, _, transaction, _, _) => new NativeKeccakPreimageTracer(transaction, options));
_tracers.Add(NativeNoopTracer.NoopTracer, static (options, _, transaction, _, _) => new NativeNoopTracer(transaction, options));
_tracers.Add(NativePrestateTracer.PrestateTracer, static (options, block, transaction, worldState, releaseSpec) => new NativePrestateTracer(worldState, options, transaction.Hash, transaction.SenderAddress, transaction.To, block.Beneficiary, transaction, releaseSpec, transaction.AuthorizationList));
_tracers.Add(NativeFlatCallTracer.FlatCallTracer, static (options, block, transaction, _, releaseSpec) => new NativeFlatCallTracer(transaction, block, releaseSpec, options));
_tracers.Add(NativeCallTracer.CallTracer, static (options, _, transaction, _, releaseSpec) => new NativeCallTracer(transaction, releaseSpec, options));
_tracers.Add(NativeStateGasTracer.StateGasTracer, static (options, _, transaction, _, releaseSpec) => new NativeStateGasTracer(transaction, releaseSpec, options));
}
Expand Down Expand Up @@ -79,6 +80,9 @@ internal static void ValidateTracerConfig(GethTraceOptions options)
{
switch (options.Tracer)
{
case NativeFlatCallTracer.FlatCallTracer:
NativeFlatCallTracer.ParseConfig(options.TracerConfig);
break;
case NativeCallTracer.CallTracer:
NativeCallTracerConfig.FromJson(options.TracerConfig, EthereumJsonSerializer.JsonOptions);
break;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -44,7 +44,7 @@ private static bool SupportsExecutionDeadline(string tracer, JsonElement? config
{
if (tracer != "muxTracer")
return !GethLikeNativeTracerFactory.IsNativeTracer(tracer)
|| tracer is NativeCallTracer.CallTracer or NativePrestateTracer.PrestateTracer or Native4ByteTracer.FourByteTracer;
|| tracer is NativeCallTracer.CallTracer or NativeFlatCallTracer.FlatCallTracer or NativePrestateTracer.PrestateTracer or Native4ByteTracer.FourByteTracer;

// Leave malformed configurations to the mux factory's existing error mapping.
if (config is not { ValueKind: JsonValueKind.Object } children) return false;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,8 @@ public record GethTraceOptions

public bool EnableReturnData { get; init; }

internal bool IsTraceCall { get; init; }

internal bool CaptureJavaScriptErrors { get; init; }

internal bool EnforceExecutionDeadline { get; init; }
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,7 @@ namespace Nethermind.Blockchain.Tracing;
[JsonSerializable(typeof(FourByteIdCounts))]
[JsonSerializable(typeof(GethLikeTxTraceCollection))]
[JsonSerializable(typeof(NativeCallTracerCallFrame))]
[JsonSerializable(typeof(NativeFlatCallTracer.JsonConfig), TypeInfoPropertyName = "NativeFlatCallTracerJsonConfig")]
[JsonSerializable(typeof(NativeCallTracerConfig))]
[JsonSerializable(typeof(NativeCallTracerConfig.JsonConfig), TypeInfoPropertyName = "NativeCallTracerJsonConfig")]
[JsonSerializable(typeof(NativeCallTracerLogEntry))]
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -544,7 +544,7 @@ public void Trace_by_block_number_rejects_a_negative_index()
/// Selectors outside native registrations and shipped JavaScript tracers are compiled as JavaScript
/// expressions. Evaluation and callback validation are deferred until a transaction is traced.
/// </remarks>
[TestCase("flatCallTracer", true)]
[TestCase("unregisteredTracerForDeferredEvaluation", true)]
[TestCase("_bigInteger", true)]
public async Task Create_options_tracer_defers_valid_javascript_expression_evaluation(string tracer, bool javascript)
{
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -74,6 +74,7 @@ public class GethStyleTracer(

public GethLikeTxTrace? Trace(BlockParameter blockParameter, Transaction tx, GethTraceOptions options, CancellationToken cancellationToken, Utf8JsonWriter? writer = null, PipeWriter? pipeWriter = null)
{
options = options with { IsTraceCall = true };
tx.Hash ??= tx.CalculateHash();
if (options.TxIndex is { } index)
{
Expand Down Expand Up @@ -290,7 +291,7 @@ public ITxTracer StartNewTxTrace(Transaction? transaction)

block = new Block(block.Header.Clone(), BlockBody.WithOneTransactionOnly(tx));
using Scope<BlockProcessingComponents> scope = blockProcessingEnv.BuildAndOverride(block.Header, options.StateOverrides);
IBlockTracer<GethLikeTxTrace> blockTracer = CreateOptionsTracer(block.Header, options with { TxHash = tx.Hash }, scope.Component.WorldState, specProvider, null, cancellationToken);
IBlockTracer<GethLikeTxTrace> blockTracer = CreateOptionsTracer(block.Header, options with { TxHash = tx.Hash, IsTraceCall = true }, scope.Component.WorldState, specProvider, null, cancellationToken);
try
{
scope.Component.BlockchainProcessor.Process(block, TraceProcessingOptions.ReadOnlyReplay, blockTracer.WithCancellation(cancellationToken), cancellationToken);
Expand Down
Loading
Loading