-
Notifications
You must be signed in to change notification settings - Fork 698
Expand file tree
/
Copy pathBlockReceiptsTracer.cs
More file actions
322 lines (255 loc) · 13.4 KB
/
BlockReceiptsTracer.cs
File metadata and controls
322 lines (255 loc) · 13.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
// SPDX-FileCopyrightText: 2022 Demerzel Solutions Limited
// SPDX-License-Identifier: LGPL-3.0-only
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Runtime.InteropServices;
using Nethermind.Core;
using Nethermind.Core.Crypto;
using Nethermind.Evm;
using Nethermind.Evm.Tracing;
using Nethermind.Evm.TransactionProcessing;
using Nethermind.Int256;
namespace Nethermind.Blockchain.Tracing;
public class BlockReceiptsTracer(bool parallel = false) : IBlockTracer, ITxTracer, IJournal<int>, ITxTracerWrapper
{
private IBlockTracer _otherTracer = NullBlockTracer.Instance;
protected Block Block = null!;
public bool IsTracingReceipt => true;
public bool IsTracingActions => _currentTxTracer.IsTracingActions;
public bool IsTracingOpLevelStorage => _currentTxTracer.IsTracingOpLevelStorage;
public bool IsTracingMemory => _currentTxTracer.IsTracingMemory;
public bool IsTracingInstructions => _currentTxTracer.IsTracingInstructions;
public bool IsTracingRefunds => _currentTxTracer.IsTracingRefunds;
public bool IsTracingCode => _currentTxTracer.IsTracingCode;
public bool IsTracingStack => _currentTxTracer.IsTracingStack;
public bool IsTracingState => _currentTxTracer.IsTracingState;
public bool IsTracingStorage => _currentTxTracer.IsTracingStorage;
public bool IsTracingBlockHash => _currentTxTracer.IsTracingBlockHash;
public bool IsTracingAccess => _currentTxTracer.IsTracingAccess;
public bool IsTracingFees => _currentTxTracer.IsTracingFees;
public bool IsTracingLogs => _currentTxTracer.IsTracingLogs;
public void MarkAsSuccess(Address recipient, in GasConsumed gasSpent, byte[] output, LogEntry[] logs, Hash256? stateRoot = null)
{
_txReceipts.Add(BuildReceipt(recipient, gasSpent, StatusCode.Success, logs, stateRoot));
// hacky way to support nested receipt tracers
if (_otherTracer is ITxTracer otherTxTracer)
{
otherTxTracer.MarkAsSuccess(recipient, gasSpent, output, logs, stateRoot);
}
if (_currentTxTracer.IsTracingReceipt)
{
_currentTxTracer.MarkAsSuccess(recipient, gasSpent, output, logs, stateRoot);
}
}
public void MarkAsFailed(Address recipient, in GasConsumed gasSpent, byte[] output, string? error, Hash256? stateRoot = null)
{
_txReceipts.Add(BuildFailedReceipt(recipient, gasSpent, error, stateRoot));
// hacky way to support nested receipt tracers
if (_otherTracer is ITxTracer otherTxTracer)
{
otherTxTracer.MarkAsFailed(recipient, gasSpent, output, error, stateRoot);
}
if (_currentTxTracer.IsTracingReceipt)
{
_currentTxTracer.MarkAsFailed(recipient, gasSpent, output, error, stateRoot);
}
}
protected TxReceipt BuildFailedReceipt(Address recipient, in GasConsumed gasSpent, string error, Hash256? stateRoot)
{
TxReceipt receipt = BuildReceipt(recipient, gasSpent, StatusCode.Failure, [], stateRoot);
receipt.Error = error;
return receipt;
}
/// <summary>
/// Updates cumulative gas tracking for both block and receipt accounting.
/// EIP-7778: Block gas uses pre-refund values for gas limit accounting,
/// while receipt gas uses post-refund values (what users actually pay).
/// </summary>
/// <returns>The cumulative post-refund gas for receipts</returns>
protected long UpdateCumulativeGasTracking(in GasConsumed gasConsumed)
{
// Track cumulative block gas for restore (regular + EIP-8037 state)
(long prevRegular, long prevState) = _cumulativeBlockGasPerTx.Count > 0 ? _cumulativeBlockGasPerTx[^1] : (0, 0);
long cumulativeBlockGas = prevRegular + gasConsumed.EffectiveBlockGas;
long cumulativeBlockStateGas = prevState + gasConsumed.BlockStateGas;
_cumulativeBlockGasPerTx.Add((cumulativeBlockGas, cumulativeBlockStateGas));
// EIP-8037: block gasUsed = max(sum_regular, sum_state). Override header accumulation.
if (!parallel)
{
Block.Header.GasUsed = Math.Max(cumulativeBlockGas, cumulativeBlockStateGas);
}
// Track cumulative receipt gas (post-refund)
_cumulativeReceiptGas += gasConsumed.SpentGas;
Debug.Assert(_txReceipts.Count + 1 == _cumulativeBlockGasPerTx.Count,
"Receipt and gas tracking lists must remain synchronized");
return _cumulativeReceiptGas;
}
protected virtual TxReceipt BuildReceipt(Address recipient, in GasConsumed gasConsumed, byte statusCode, LogEntry[] logEntries, Hash256? stateRoot)
{
long cumulativeReceiptGas = UpdateCumulativeGasTracking(gasConsumed);
Transaction transaction = CurrentTx!;
TxReceipt txReceipt = new()
{
Logs = logEntries,
TxType = transaction.Type,
// Bloom calculated in parallel with other receipts
GasUsedTotal = cumulativeReceiptGas, // Post-refund cumulative
StatusCode = statusCode,
Recipient = transaction.IsContractCreation ? null : recipient,
BlockHash = Block.Hash,
BlockNumber = Block.Number,
Index = _currentIndex,
GasUsed = gasConsumed.SpentGas, // Post-refund for this tx
Sender = transaction.SenderAddress,
ContractAddress = transaction.IsContractCreation ? recipient : null,
TxHash = transaction.Hash,
PostTransactionState = stateRoot
};
return txReceipt;
}
public void StartOperation(int pc, Instruction opcode, long gas, in ExecutionEnvironment env) =>
_currentTxTracer.StartOperation(pc, opcode, gas, env);
public void ReportOperationError(EvmExceptionType error) =>
_currentTxTracer.ReportOperationError(error);
public void ReportOperationRemainingGas(long gas) =>
_currentTxTracer.ReportOperationRemainingGas(gas);
public void ReportLog(LogEntry log) =>
_currentTxTracer.ReportLog(log);
public void SetOperationMemorySize(ulong newSize) =>
_currentTxTracer.SetOperationMemorySize(newSize);
public void ReportMemoryChange(long offset, in ReadOnlySpan<byte> data) =>
_currentTxTracer.ReportMemoryChange(offset, data);
public void ReportStorageChange(in ReadOnlySpan<byte> key, in ReadOnlySpan<byte> value) =>
_currentTxTracer.ReportStorageChange(key, value);
public void SetOperationStorage(Address address, UInt256 storageIndex, ReadOnlySpan<byte> newValue, ReadOnlySpan<byte> currentValue) =>
_currentTxTracer.SetOperationStorage(address, storageIndex, newValue, currentValue);
public void LoadOperationStorage(Address address, UInt256 storageIndex, ReadOnlySpan<byte> value) =>
_currentTxTracer.LoadOperationStorage(address, storageIndex, value);
public void ReportSelfDestruct(Address address, UInt256 balance, Address refundAddress) =>
_currentTxTracer.ReportSelfDestruct(address, balance, refundAddress);
public void ReportBalanceChange(Address address, UInt256? before, UInt256? after) =>
_currentTxTracer.ReportBalanceChange(address, before, after);
public void ReportCodeChange(Address address, byte[] before, byte[] after) =>
_currentTxTracer.ReportCodeChange(address, before, after);
public void ReportNonceChange(Address address, UInt256? before, UInt256? after) =>
_currentTxTracer.ReportNonceChange(address, before, after);
public void ReportAccountRead(Address address) =>
_currentTxTracer.ReportAccountRead(address);
public void ReportStorageChange(in StorageCell storageCell, byte[] before, byte[] after) =>
_currentTxTracer.ReportStorageChange(storageCell, before, after);
public void ReportStorageRead(in StorageCell storageCell) =>
_currentTxTracer.ReportStorageRead(storageCell);
public void ReportAction(long gas, UInt256 value, Address from, Address to, ReadOnlyMemory<byte> input, ExecutionType callType, bool isPrecompileCall = false) =>
_currentTxTracer.ReportAction(gas, value, from, to, input, callType, isPrecompileCall);
public void ReportActionEnd(long gas, ReadOnlyMemory<byte> output) =>
_currentTxTracer.ReportActionEnd(gas, output);
public void ReportActionError(EvmExceptionType exceptionType) =>
_currentTxTracer.ReportActionError(exceptionType);
public void ReportActionRevert(long gasLeft, ReadOnlyMemory<byte> output) =>
_currentTxTracer.ReportActionRevert(gasLeft, output);
public void ReportActionEnd(long gas, Address deploymentAddress, ReadOnlyMemory<byte> deployedCode) =>
_currentTxTracer.ReportActionEnd(gas, deploymentAddress, deployedCode);
public void ReportByteCode(ReadOnlyMemory<byte> byteCode) =>
_currentTxTracer.ReportByteCode(byteCode);
public void ReportGasUpdateForVmTrace(long refund, long gasAvailable) =>
_currentTxTracer.ReportGasUpdateForVmTrace(refund, gasAvailable);
public void ReportRefund(long refund) =>
_currentTxTracer.ReportRefund(refund);
public void ReportExtraGasPressure(long extraGasPressure) =>
_currentTxTracer.ReportExtraGasPressure(extraGasPressure);
public void ReportAccess(IEnumerable<Address> accessedAddresses, IEnumerable<StorageCell> accessedStorageCells) =>
_currentTxTracer.ReportAccess(accessedAddresses, accessedStorageCells);
public void SetOperationStack(TraceStack stack) =>
_currentTxTracer.SetOperationStack(stack);
public void ReportStackPush(in ReadOnlySpan<byte> stackItem) =>
_currentTxTracer.ReportStackPush(stackItem);
public void ReportBlockHash(Hash256 blockHash) =>
_currentTxTracer.ReportBlockHash(blockHash);
public void SetOperationMemory(TraceMemory memoryTrace) =>
_currentTxTracer.SetOperationMemory(memoryTrace);
public void ReportFees(UInt256 fees, UInt256 burntFees)
{
if (_currentTxTracer.IsTracingFees)
{
_currentTxTracer.ReportFees(fees, burntFees);
}
}
private ITxTracer _currentTxTracer = NullTxTracer.Instance;
protected int _currentIndex { get; private set; }
private readonly List<TxReceipt> _txReceipts = new();
private readonly List<(long Regular, long State)> _cumulativeBlockGasPerTx = new(); // Track pre-refund block gas for restore (regular + EIP-8037 state)
private long _cumulativeReceiptGas; // Track cumulative post-refund gas for receipts
protected Transaction? CurrentTx;
public ReadOnlySpan<TxReceipt> TxReceipts => CollectionsMarshal.AsSpan(_txReceipts);
public TxReceipt LastReceipt => _txReceipts[^1];
public IBlockTracer OtherTracer => _otherTracer;
/// <summary>
/// EIP-8037: cumulative state gas for the last tracked tx.
/// Used by parallel execution to pass state gas back for 2D block gas accounting.
/// </summary>
public long BlockStateGasUsed => _cumulativeBlockGasPerTx.Count > 0 ? _cumulativeBlockGasPerTx[^1].State : 0;
public bool IsTracingRewards => _otherTracer.IsTracingRewards;
public long CumulativeRegularGasUsed => _cumulativeBlockGasPerTx.Count > 0 ? _cumulativeBlockGasPerTx[^1].Regular : 0;
public ITxTracer InnerTracer => _currentTxTracer;
public int TakeSnapshot() => _txReceipts.Count;
public void Restore(int snapshot)
{
int numToRemove = _txReceipts.Count - snapshot;
if (numToRemove > 0)
{
_txReceipts.RemoveRange(snapshot, numToRemove);
_cumulativeBlockGasPerTx.RemoveRange(snapshot, numToRemove);
}
Debug.Assert(_txReceipts.Count == _cumulativeBlockGasPerTx.Count,
"Receipt and gas tracking lists must remain synchronized after restore");
// Restore block gas from tracking: max(cumulative_regular, cumulative_state) for EIP-8037
(long cumulativeRegular, long cumulativeState) = _cumulativeBlockGasPerTx.Count > 0 ? _cumulativeBlockGasPerTx[^1] : (0, 0);
Block.Header.GasUsed = Math.Max(cumulativeRegular, cumulativeState);
// Restore receipt gas from remaining receipts (post-refund)
_cumulativeReceiptGas = _txReceipts.Count > 0 ? _txReceipts[^1].GasUsedTotal : 0;
}
public void ReportReward(Address author, string rewardType, UInt256 rewardValue) =>
_otherTracer.ReportReward(author, rewardType, rewardValue);
public void StartNewBlockTrace(Block block)
{
Block = block;
_currentIndex = 0;
_txReceipts.Clear();
_cumulativeBlockGasPerTx.Clear();
_cumulativeReceiptGas = 0;
_otherTracer.StartNewBlockTrace(block);
}
public ITxTracer StartNewTxTrace(Transaction? tx)
{
CurrentTx = tx;
_currentTxTracer = _otherTracer.StartNewTxTrace(tx);
return _currentTxTracer;
}
public void EndTxTrace()
{
_otherTracer.EndTxTrace();
_currentIndex++;
}
public void EndBlockTrace()
{
_otherTracer.EndBlockTrace();
if (_txReceipts.Count > 0)
{
Bloom blockBloom = new();
Block.Header.Bloom = blockBloom;
for (int index = 0; index < _txReceipts.Count; index++)
{
TxReceipt? receipt = _txReceipts[index];
blockBloom.Accumulate(receipt.Bloom!);
}
}
_otherTracer = NullBlockTracer.Instance;
}
public void SetOtherTracer(IBlockTracer blockTracer)
{
ArgumentNullException.ThrowIfNull(blockTracer);
_otherTracer = blockTracer;
}
public void Dispose() => _currentTxTracer.Dispose();
}