Repository navigation
Add native Geth flatCallTracer #16483
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
base: master
Are you sure you want to change the base?
Changes from all commits
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
| 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); | ||||||
| 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)); | ||||||
|
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Medium: Geth parity, STATICCALL Geth's
Suggested change
Then update the test to expect no |
||||||
| } | ||||||
| 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", | ||||||
|
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Low: this mapping isn't in Geth. Geth's |
||||||
| _ 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(); | ||||||
| } | ||||||
| } | ||||||
There was a problem hiding this comment.
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 aJsonDocument, thenClone()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 abyte[]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.