-
Notifications
You must be signed in to change notification settings - Fork 696
Expand file tree
/
Copy pathTransactionProcessor.cs
More file actions
1436 lines (1237 loc) · 68.8 KB
/
TransactionProcessor.cs
File metadata and controls
1436 lines (1237 loc) · 68.8 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
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// SPDX-FileCopyrightText: 2026 Demerzel Solutions Limited
// SPDX-License-Identifier: LGPL-3.0-only
using System;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.IO;
using System.Runtime.CompilerServices;
using System.Threading;
using Nethermind.Core.BlockAccessLists;
using Nethermind.Core;
using Nethermind.Core.Collections;
using Nethermind.Core.Extensions;
using Nethermind.Core.Crypto;
using Nethermind.Core.Messages;
using Nethermind.Core.Specs;
using Nethermind.Crypto;
using Nethermind.Evm.CodeAnalysis;
using Nethermind.Evm.GasPolicy;
using Nethermind.Evm.Tracing;
using Nethermind.Int256;
using Nethermind.Logging;
using Nethermind.Evm.State;
using Nethermind.Evm.Tracing.State;
namespace Nethermind.Evm.TransactionProcessing
{
public sealed class TransactionProcessor<TGasPolicy>(
ITransactionProcessor.IBlobBaseFeeCalculator blobBaseFeeCalculator,
ISpecProvider? specProvider,
IWorldState? worldState,
IVirtualMachine<TGasPolicy>? virtualMachine,
ICodeInfoRepository? codeInfoRepository,
ILogManager? logManager,
bool parallel = false)
: TransactionProcessorBase<TGasPolicy>(blobBaseFeeCalculator, specProvider, worldState, virtualMachine, codeInfoRepository, logManager, parallel)
where TGasPolicy : struct, IGasPolicy<TGasPolicy>
{
public TransactionResult Process(Transaction transaction, ITxTracer txTracer, ExecutionOptions options, in IntrinsicGas<TGasPolicy> intrinsicGas)
=> ExecuteCore(transaction, txTracer, options, in intrinsicGas);
}
/// <summary>
/// Non-generic TransactionProcessor for backward compatibility with EthereumGasPolicy.
/// </summary>
public sealed class EthereumTransactionProcessor(
ITransactionProcessor.IBlobBaseFeeCalculator blobBaseFeeCalculator,
ISpecProvider? specProvider,
IWorldState? worldState,
IVirtualMachine? virtualMachine,
ICodeInfoRepository? codeInfoRepository,
ILogManager? logManager)
: EthereumTransactionProcessorBase(blobBaseFeeCalculator, specProvider, worldState, virtualMachine, codeInfoRepository, logManager);
public class BlobBaseFeeCalculator : ITransactionProcessor.IBlobBaseFeeCalculator
{
public static BlobBaseFeeCalculator Instance { get; } = new BlobBaseFeeCalculator();
public bool TryCalculateBlobBaseFee(BlockHeader header, Transaction transaction,
UInt256 blobGasPriceUpdateFraction, out UInt256 blobBaseFee) =>
BlobGasCalculator.TryCalculateBlobBaseFee(header, transaction, blobGasPriceUpdateFraction, out blobBaseFee);
}
public abstract class TransactionProcessorBase<TGasPolicy> : ITransactionProcessor
where TGasPolicy : struct, IGasPolicy<TGasPolicy>
{
protected EthereumEcdsa Ecdsa { get; }
protected ILogger Logger { get; }
protected ISpecProvider SpecProvider { get; }
protected IWorldState WorldState { get; }
protected IVirtualMachine<TGasPolicy> VirtualMachine { get; }
private readonly ICodeInfoRepository _codeInfoRepository;
private SystemTransactionProcessor<TGasPolicy>? _systemTransactionProcessor;
private readonly ITransactionProcessor.IBlobBaseFeeCalculator _blobBaseFeeCalculator;
private readonly ILogManager _logManager;
private readonly bool _parallel;
private long _blockCumulativeReceiptGas;
protected TransactionProcessorBase(
ITransactionProcessor.IBlobBaseFeeCalculator? blobBaseFeeCalculator,
ISpecProvider? specProvider,
IWorldState? worldState,
IVirtualMachine<TGasPolicy>? virtualMachine,
ICodeInfoRepository? codeInfoRepository,
ILogManager? logManager,
bool parallel = false)
{
ArgumentNullException.ThrowIfNull(logManager);
ArgumentNullException.ThrowIfNull(specProvider);
ArgumentNullException.ThrowIfNull(worldState);
ArgumentNullException.ThrowIfNull(virtualMachine);
ArgumentNullException.ThrowIfNull(codeInfoRepository);
ArgumentNullException.ThrowIfNull(blobBaseFeeCalculator);
Logger = logManager.GetClassLogger(typeof(TransactionProcessorBase<>));
SpecProvider = specProvider;
WorldState = worldState;
VirtualMachine = virtualMachine;
_codeInfoRepository = codeInfoRepository;
_blobBaseFeeCalculator = blobBaseFeeCalculator;
Ecdsa = new EthereumEcdsa(specProvider.ChainId);
_logManager = logManager;
_parallel = parallel;
}
public void SetBlockExecutionContext(in BlockExecutionContext blockExecutionContext)
{
_blockCumulativeReceiptGas = 0;
VirtualMachine.SetBlockExecutionContext(in blockExecutionContext);
}
public void SetBlockExecutionContext(BlockHeader header)
{
IReleaseSpec spec = SpecProvider.GetSpec(header);
BlockExecutionContext blockExecutionContext = new(header, spec);
SetBlockExecutionContext(in blockExecutionContext);
}
public TransactionResult Process(
Transaction transaction,
ITxTracer txTracer,
ExecutionOptions options)
{
if (options == ExecutionOptions.BuildUp)
{
WorldState.TakeSnapshot(true);
}
return ExecuteCore(transaction, txTracer, options);
}
private TransactionResult ExecuteCore(Transaction tx, ITxTracer tracer, ExecutionOptions opts)
{
if (Logger.IsTrace) Logger.Trace($"Executing tx {tx.Hash}");
if (tx.IsSystem() || (opts & ~ExecutionOptions.Warmup) == ExecutionOptions.SkipValidation)
{
if (_systemTransactionProcessor is null)
{
Interlocked.CompareExchange(ref _systemTransactionProcessor,
new SystemTransactionProcessor<TGasPolicy>(_blobBaseFeeCalculator, SpecProvider, WorldState, VirtualMachine, _codeInfoRepository, _logManager),
null);
}
return _systemTransactionProcessor.Execute(tx, tracer, opts);
}
TransactionResult result = Execute(tx, tracer, opts);
if (Logger.IsTrace) Logger.Trace($"Tx {tx.Hash} was executed, {result}");
return result;
}
protected TransactionResult ExecuteCore(Transaction tx, ITxTracer tracer, ExecutionOptions opts, in IntrinsicGas<TGasPolicy> intrinsicGas)
{
if (Logger.IsTrace) Logger.Trace($"Executing tx {tx.Hash}");
if (tx.IsSystem() || (opts & ~ExecutionOptions.Warmup) == ExecutionOptions.SkipValidation)
{
if (_systemTransactionProcessor is null)
{
Interlocked.CompareExchange(ref _systemTransactionProcessor,
new SystemTransactionProcessor<TGasPolicy>(_blobBaseFeeCalculator, SpecProvider, WorldState, VirtualMachine, _codeInfoRepository, _logManager),
null);
}
return _systemTransactionProcessor.Execute(tx, tracer, opts);
}
TransactionResult result = Execute(tx, tracer, opts, in intrinsicGas);
if (Logger.IsTrace) Logger.Trace($"Tx {tx.Hash} was executed, {result}");
return result;
}
protected virtual TransactionResult Execute(Transaction tx, ITxTracer tracer, ExecutionOptions opts)
{
BlockHeader header = VirtualMachine.BlockExecutionContext.Header;
IReleaseSpec spec = GetSpec(header);
IntrinsicGas<TGasPolicy> intrinsicGas = CalculateIntrinsicGas(tx, spec, header.GasLimit);
return Execute(tx, tracer, opts, header, spec, in intrinsicGas);
}
protected TransactionResult Execute(Transaction tx, ITxTracer tracer, ExecutionOptions opts, in IntrinsicGas<TGasPolicy> intrinsicGas)
{
BlockHeader header = VirtualMachine.BlockExecutionContext.Header;
IReleaseSpec spec = GetSpec(header);
return Execute(tx, tracer, opts, header, spec, in intrinsicGas);
}
private TransactionResult Execute(Transaction tx, ITxTracer tracer, ExecutionOptions opts, BlockHeader header, IReleaseSpec spec, in IntrinsicGas<TGasPolicy> intrinsicGas)
{
// restore is CallAndRestore - previous call, we will restore state after the execution
bool restore = opts.HasFlag(ExecutionOptions.Restore);
// commit - is for standard execute, we will commit the state after execution
// !commit - is for build up during block production, we won't commit state after each transaction to support rollbacks
// we commit only after all block is constructed
bool commit = opts.HasFlag(ExecutionOptions.Commit) || (!opts.HasFlag(ExecutionOptions.SkipValidation) && !spec.IsEip658Enabled);
TransactionResult result;
if (!(result = ValidateStatic(tx, header, spec, opts, in intrinsicGas))) return result;
UInt256 effectiveGasPrice = CalculateEffectiveGasPrice(tx, spec.IsEip1559Enabled, header.BaseFeePerGas, out UInt256 opcodeGasPrice);
VirtualMachine.SetTxExecutionContext(new(tx.SenderAddress!, _codeInfoRepository, tx.BlobVersionedHashes, in opcodeGasPrice));
UpdateMetrics(opts, effectiveGasPrice);
bool deleteCallerAccount = RecoverSenderIfNeeded(tx, spec, opts, effectiveGasPrice);
if (!(result = ValidateSender(tx, header, spec, tracer, opts)) ||
!(result = BuyGas(tx, spec, tracer, opts, effectiveGasPrice, out UInt256 premiumPerGas, out UInt256 senderReservedGasPayment, out UInt256 blobBaseFee)) ||
!(result = IncrementNonce(tx, header, spec, tracer, opts)))
{
if (restore)
{
WorldState.Reset(resetBlockChanges: false);
}
return result;
}
if (commit) WorldState.Commit(spec, tracer.IsTracingState ? tracer : NullTxTracer.Instance, commitRoots: false);
// substate.Logs contains a reference to accessTracker.Logs so we can't Dispose until end of the method
using StackAccessTracker accessTracker = new(tracer.IsTracingAccess);
int delegationRefunds = !spec.IsEip7702Enabled || !tx.HasAuthorizationList ? 0 : ProcessDelegations(tx, spec, accessTracker);
if (!(result = CalculateAvailableGas(tx, spec, in intrinsicGas, out TGasPolicy gasAvailable))) return result;
Apply8037DelegationRefunds(spec, in intrinsicGas, ref gasAvailable, ref delegationRefunds);
if (!(result = BuildExecutionEnvironment(tx, spec, _codeInfoRepository, accessTracker, out ExecutionEnvironment e))) return result;
using ExecutionEnvironment env = e;
int statusCode = !tracer.IsTracingInstructions ?
ExecuteEvmCall<OffFlag>(tx, header, spec, tracer, opts, delegationRefunds, intrinsicGas, accessTracker, gasAvailable, env, out TransactionSubstate substate, out GasConsumed spentGas) :
ExecuteEvmCall<OnFlag>(tx, header, spec, tracer, opts, delegationRefunds, intrinsicGas, accessTracker, gasAvailable, env, out substate, out spentGas);
PayFees(tx, header, spec, tracer, in substate, spentGas.SpentGas, premiumPerGas, blobBaseFee, statusCode);
// EIP-8037+EIP-7708: process destroy list after PayFees so burn logs include
// the priority fee in the destroyed account's balance.
if (spec.IsEip8037Enabled && spec.IsEip7708Enabled && statusCode == StatusCode.Success)
{
JournalSet<Address> destroyList = substate.DestroyList;
if (destroyList.Count > 1)
{
Address[] orderedDestroyList = [.. destroyList];
Array.Sort(orderedDestroyList, GenericComparer.GetOptimized<Address>());
for (int i = 0; i < orderedDestroyList.Length; i++)
{
FinalizeDestroyedAccount(WorldState, in substate, orderedDestroyList[i]);
}
}
else
{
foreach (Address toBeDestroyed in destroyList)
{
FinalizeDestroyedAccount(WorldState, in substate, toBeDestroyed);
}
}
static void FinalizeDestroyedAccount(IWorldState worldState, in TransactionSubstate substate, Address toBeDestroyed)
{
UInt256 balance = worldState.GetBalance(toBeDestroyed);
if (!balance.IsZero)
{
substate.Logs.Add(TransferLog.CreateBurn(toBeDestroyed, balance));
}
worldState.ClearStorage(toBeDestroyed);
worldState.DeleteAccount(toBeDestroyed);
}
}
if (!opts.HasFlag(ExecutionOptions.Warmup))
{
tx.BlockGasUsed = spentGas.EffectiveBlockGas;
}
if (!opts.HasFlag(ExecutionOptions.SkipValidation))
{
_blockCumulativeReceiptGas += spentGas.SpentGas;
}
//only main thread updates transaction
if (!opts.HasFlag(ExecutionOptions.Warmup))
tx.SpentGas = spentGas.SpentGas;
// Finalize
if (restore)
{
WorldState.Reset(resetBlockChanges: false);
if (deleteCallerAccount)
{
WorldState.DeleteAccount(tx.SenderAddress!);
}
else
{
if (!senderReservedGasPayment.IsZero)
{
WorldState.AddToBalance(tx.SenderAddress!, senderReservedGasPayment, spec);
}
DecrementNonce(tx);
WorldState.Commit(spec, commitRoots: false);
}
}
else if (commit)
{
WorldState.Commit(spec, tracer.IsTracingState ? tracer : NullStateTracer.Instance, commitRoots: !spec.IsEip658Enabled);
}
else
{
WorldState.ResetTransient();
}
if (tracer.IsTracingReceipt)
{
Hash256 stateRoot = null;
if (!spec.IsEip658Enabled)
{
WorldState.RecalculateStateRoot();
stateRoot = WorldState.StateRoot;
}
if (statusCode == StatusCode.Failure)
{
byte[] output = substate.ShouldRevert ? substate.Output.ToArray() : [];
tracer.MarkAsFailed(env.ExecutingAccount, spentGas, output, substate.Error, stateRoot);
}
else
{
LogEntry[] logs = substate.Logs.Count != 0 ? substate.Logs.ToArray() : [];
tracer.MarkAsSuccess(env.ExecutingAccount, spentGas, substate.Output.ToArray(), logs, stateRoot);
}
}
return substate.EvmExceptionType != EvmExceptionType.None
? TransactionResult.EvmException(substate.EvmExceptionType, substate.SubstateError)
: TransactionResult.Ok;
}
protected virtual TransactionResult CalculateAvailableGas(Transaction tx, IReleaseSpec spec, in IntrinsicGas<TGasPolicy> intrinsicGas, out TGasPolicy gasAvailable)
{
gasAvailable = TGasPolicy.CreateAvailableFromIntrinsic(tx.GasLimit, intrinsicGas.Standard, spec);
return TransactionResult.Ok;
}
private static void Apply8037DelegationRefunds(IReleaseSpec spec, in IntrinsicGas<TGasPolicy> intrinsicGas, ref TGasPolicy gasAvailable, ref int delegationRefunds)
{
if (spec.IsEip8037Enabled && delegationRefunds > 0)
{
TGasPolicy intrinsicGasStandard = intrinsicGas.Standard;
long stateGasFloor = TGasPolicy.GetStateReservoir(in intrinsicGasStandard);
TGasPolicy.ApplyCodeInsertRefunds(ref gasAvailable, delegationRefunds, spec, stateGasFloor);
delegationRefunds = 0;
}
}
[MethodImpl(MethodImplOptions.NoInlining)]
private int ProcessDelegations(Transaction tx, IReleaseSpec spec, in StackAccessTracker accessTracker)
{
Debug.Assert(spec.IsEip7702Enabled && tx.HasAuthorizationList);
int refunds = 0;
foreach (AuthorizationTuple authTuple in tx.AuthorizationList)
{
Address authority = (authTuple.Authority ??= Ecdsa.RecoverAddress(authTuple))!;
AuthorizationTupleResult authorizationResult = IsValidForExecution(authTuple, accessTracker, spec, out string? error);
if (authorizationResult != AuthorizationTupleResult.Valid)
{
if (Logger.IsDebug) Logger.Debug($"Delegation {authTuple} is invalid with error: {error}");
}
else
{
if (!WorldState.AccountExists(authority))
{
WorldState.CreateAccount(authority, 0, 1);
}
else
{
refunds++;
WorldState.IncrementNonce(authority);
}
_codeInfoRepository.SetDelegation(authTuple.CodeAddress, authority, spec);
}
}
return refunds;
}
private enum AuthorizationTupleResult
{
Valid,
IncorrectNonce,
InvalidNonce,
InvalidChainId,
InvalidSignature,
InvalidAsCodeDeployed
}
private AuthorizationTupleResult IsValidForExecution(
AuthorizationTuple authorizationTuple,
in StackAccessTracker accessTracker,
IReleaseSpec spec,
[NotNullWhen(false)] out string? error)
{
if (authorizationTuple.ChainId != 0 && SpecProvider.ChainId != authorizationTuple.ChainId)
{
error = $"Chain id ({authorizationTuple.ChainId}) does not match.";
return AuthorizationTupleResult.InvalidChainId;
}
if (authorizationTuple.Nonce == ulong.MaxValue)
{
error = $"Nonce ({authorizationTuple.Nonce}) must be less than 2**64 - 1.";
return AuthorizationTupleResult.InvalidNonce;
}
UInt256 s = new(authorizationTuple.AuthoritySignature.SAsSpan, isBigEndian: true);
if (authorizationTuple.Authority is null
|| s > SecP256k1Curve.HalfN
//V minus the offset can only be 1 or 0 since eip-155 does not apply to Setcode signatures
|| authorizationTuple.AuthoritySignature.V - Signature.VOffset > 1)
{
error = "Bad signature.";
return AuthorizationTupleResult.InvalidSignature;
}
accessTracker.WarmUp(authorizationTuple.Authority);
if (WorldState.HasCode(authorizationTuple.Authority) && !_codeInfoRepository.TryGetDelegation(authorizationTuple.Authority, spec, out _))
{
error = $"Authority ({authorizationTuple.Authority}) has code deployed.";
return AuthorizationTupleResult.InvalidAsCodeDeployed;
}
UInt256 authNonce = WorldState.GetNonce(authorizationTuple.Authority);
if (authNonce != authorizationTuple.Nonce)
{
error = $"Skipping tuple in authorization_list because nonce is set to {authorizationTuple.Nonce}, but authority ({authorizationTuple.Authority}) has {authNonce}.";
return AuthorizationTupleResult.IncorrectNonce;
}
error = null;
return AuthorizationTupleResult.Valid;
}
protected virtual IReleaseSpec GetSpec(BlockHeader header) => VirtualMachine.BlockExecutionContext.Spec;
private static void UpdateMetrics(ExecutionOptions opts, UInt256 effectiveGasPrice)
{
if (opts is ExecutionOptions.Commit or ExecutionOptions.None or ExecutionOptions.BuildUp && (effectiveGasPrice[2] | effectiveGasPrice[3]) == 0)
{
float gasPrice = (float)((double)effectiveGasPrice / 1_000_000_000.0);
Metrics.BlockMinGasPrice = Math.Min(gasPrice, Metrics.BlockMinGasPrice);
Metrics.BlockMaxGasPrice = Math.Max(gasPrice, Metrics.BlockMaxGasPrice);
Metrics.BlockAveGasPrice = (Metrics.BlockAveGasPrice * Metrics.BlockTransactions + gasPrice) / (Metrics.BlockTransactions + 1);
Metrics.BlockEstMedianGasPrice += Metrics.BlockAveGasPrice * 0.01f * float.Sign(gasPrice - Metrics.BlockEstMedianGasPrice);
Metrics.BlockTransactions++;
}
}
/// <summary>
/// Validates the transaction, in a static manner (i.e. without accessing state/storage).
/// It basically ensures the transaction is well formed (i.e. no null values where not allowed, no overflows, etc).
/// As a part of validating the transaction the premium per gas will be calculated, to save computation this
/// is returned in an out parameter.
/// </summary>
/// <param name="tx">The transaction to validate</param>
/// <param name="header">The block containing the transaction. Only BaseFee is being used from the block atm.</param>
/// <param name="spec">The release spec with which the transaction will be executed</param>
/// <param name="opts">Options (Flags) to use for execution</param>
/// <param name="intrinsicGas">Calculated intrinsic gas</param>
/// <returns></returns>
protected virtual TransactionResult ValidateStatic(
Transaction tx,
BlockHeader header,
IReleaseSpec spec,
ExecutionOptions opts,
in IntrinsicGas<TGasPolicy> intrinsicGas)
{
bool validate = !opts.HasFlag(ExecutionOptions.SkipValidation);
if (tx.SenderAddress is null)
{
TraceLogInvalidTx(tx, "SENDER_NOT_SPECIFIED");
return TransactionResult.SenderNotSpecified;
}
if (validate && tx.Nonce >= ulong.MaxValue - 1)
{
// we are here if nonce is at least (ulong.MaxValue - 1). If tx is contract creation,
// it is max possible value. Otherwise, (ulong.MaxValue - 1) is allowed, but ulong.MaxValue not.
if (tx.IsContractCreation || tx.Nonce == ulong.MaxValue)
{
TraceLogInvalidTx(tx, "NONCE_OVERFLOW");
return TransactionResult.NonceOverflow;
}
}
if (tx.IsAboveInitCode(spec))
{
TraceLogInvalidTx(tx, $"CREATE_TRANSACTION_SIZE_EXCEEDS_MAX_INIT_CODE_SIZE {tx.DataLength} > {spec.MaxInitCodeSize}");
return TransactionResult.TransactionSizeOverMaxInitCodeSize;
}
TGasPolicy standard = intrinsicGas.Standard;
TGasPolicy minimal = intrinsicGas.MinimalGas;
long minGasRequired = spec.IsEip8037Enabled
? Math.Max(TGasPolicy.GetRemainingGas(in standard) + TGasPolicy.GetStateReservoir(in standard), TGasPolicy.GetRemainingGas(in minimal))
: TGasPolicy.GetRemainingGas(in minimal);
return ValidateGas(tx, header, spec, in standard, minGasRequired, validate);
}
protected virtual TransactionResult ValidateGas(Transaction tx, BlockHeader header, IReleaseSpec spec, in TGasPolicy intrinsicGas, long minGasRequired, bool validate)
{
if (tx.GasLimit < minGasRequired)
{
TraceLogInvalidTx(tx, $"GAS_LIMIT_BELOW_INTRINSIC_GAS {tx.GasLimit} < {minGasRequired}");
return TransactionResult.ErrorType.GasLimitBelowIntrinsicGas.WithDetail(
$"intrinsic gas too low: have {tx.GasLimit}, want {minGasRequired}");
}
if (validate)
{
if (spec.IsEip8037Enabled)
{
if (tx.GasLimit > header.GasLimit)
{
TraceLogInvalidTx(tx, $"BLOCK_GAS_LIMIT_EXCEEDED {tx.GasLimit} > {header.GasLimit}");
return TransactionResult.BlockGasLimitExceeded;
}
// Per-block EIP-8037 inclusion depends on cumulative regular/state gas,
// so block validation performs the 2D check in BlockAccessListManager
// where those accumulators are available. Direct Execute/BuildUp/estimator
// callers can only validate the tx-local allowance here.
return TransactionResult.Ok;
}
long gasUsedForAllowance = _parallel ? 0 : spec switch
{
{ IsEip7778Enabled: true } => _blockCumulativeReceiptGas,
_ => header.GasUsed,
};
long maxTransactionGasLimit = header.GasLimit - gasUsedForAllowance;
if (tx.GasLimit > maxTransactionGasLimit)
{
string limitDescription = _parallel
? $"{header.GasLimit}"
: $"{header.GasLimit} - {gasUsedForAllowance}";
TraceLogInvalidTx(tx, $"BLOCK_GAS_LIMIT_EXCEEDED {tx.GasLimit} > {limitDescription}");
return TransactionResult.BlockGasLimitExceeded;
}
}
return TransactionResult.Ok;
}
protected virtual bool RecoverSenderIfNeeded(Transaction tx, IReleaseSpec spec, ExecutionOptions opts, in UInt256 effectiveGasPrice)
{
bool deleteCallerAccount = false;
Address? sender = tx.SenderAddress;
if (sender is null || !WorldState.AccountExists(sender))
{
bool commit = opts.HasFlag(ExecutionOptions.Commit) || !spec.IsEip658Enabled;
bool restore = opts.HasFlag(ExecutionOptions.Restore);
bool noValidation = opts.HasFlag(ExecutionOptions.SkipValidation);
if (Logger.IsDebug) Logger.Debug($"TX sender account does not exist {sender} - trying to recover it");
// hacky fix for the potential recovery issue
if (tx.Signature is not null)
tx.SenderAddress = Ecdsa.RecoverAddress(tx, !spec.ValidateChainId);
if (sender != tx.SenderAddress)
{
if (Logger.IsWarn) Logger.Warn($"TX recovery issue fixed - tx was coming with sender {sender} and the now it recovers to {tx.SenderAddress}");
sender = tx.SenderAddress;
}
else
{
TraceLogInvalidTx(tx, $"SENDER_ACCOUNT_DOES_NOT_EXIST {sender}");
if (!commit || noValidation || effectiveGasPrice.IsZero)
{
deleteCallerAccount = !commit || restore;
WorldState.CreateAccount(sender!, in UInt256.Zero);
}
}
if (sender is null)
{
ThrowInvalidDataException($"Failed to recover sender address on tx {tx.Hash} when previously recovered sender account did not exist.");
}
}
return deleteCallerAccount;
}
protected virtual IntrinsicGas<TGasPolicy> CalculateIntrinsicGas(Transaction tx, IReleaseSpec spec, long blockGasLimit)
=> TGasPolicy.CalculateIntrinsicGas(tx, spec, blockGasLimit);
protected virtual UInt256 CalculateEffectiveGasPrice(Transaction tx, bool eip1559Enabled, in UInt256 baseFee, out UInt256 opcodeGasPrice)
{
opcodeGasPrice = tx.CalculateEffectiveGasPrice(eip1559Enabled, in baseFee);
return opcodeGasPrice;
}
protected virtual bool TryCalculatePremiumPerGas(Transaction tx, in UInt256 baseFee, out UInt256 premiumPerGas) =>
tx.TryCalculatePremiumPerGas(baseFee, out premiumPerGas);
protected virtual TransactionResult ValidateSender(Transaction tx, BlockHeader header, IReleaseSpec spec, ITxTracer tracer, ExecutionOptions opts)
{
bool validate = !opts.HasFlag(ExecutionOptions.SkipValidation);
if (validate && WorldState.IsInvalidContractSender(spec, tx.SenderAddress!))
{
TraceLogInvalidTx(tx, "SENDER_IS_CONTRACT");
return TransactionResult.SenderHasDeployedCode;
}
return TransactionResult.Ok;
}
protected static bool ShouldValidateGas(Transaction tx, ExecutionOptions opts)
=> !opts.HasFlag(ExecutionOptions.SkipValidation) || !tx.MaxFeePerGas.IsZero || !tx.MaxPriorityFeePerGas.IsZero;
protected virtual TransactionResult BuyGas(Transaction tx, IReleaseSpec spec, ITxTracer tracer, ExecutionOptions opts,
in UInt256 effectiveGasPrice, out UInt256 premiumPerGas, out UInt256 senderReservedGasPayment, out UInt256 blobBaseFee)
{
premiumPerGas = UInt256.Zero;
senderReservedGasPayment = UInt256.Zero;
blobBaseFee = UInt256.Zero;
bool validate = ShouldValidateGas(tx, opts);
BlockHeader header = VirtualMachine.BlockExecutionContext.Header;
if (validate && !TryCalculatePremiumPerGas(tx, header.BaseFeePerGas, out premiumPerGas))
{
TraceLogInvalidTx(tx, "MINER_PREMIUM_IS_NEGATIVE");
string errorDetail = $"max fee per gas less than block base fee: address {tx.SenderAddress?.ToString(withEip55Checksum: true) ?? "unknown"}, maxFeePerGas: {tx.MaxFeePerGas}, baseFee: {header.BaseFeePerGas}";
return TransactionResult.ErrorType.MaxFeePerGasBelowBaseFee.WithDetail(errorDetail);
}
UInt256 senderBalance = WorldState.GetBalance(tx.SenderAddress!);
if (UInt256.SubtractUnderflow(in senderBalance, in tx.ValueRef, out UInt256 balanceLeft))
{
TraceLogInvalidTx(tx, $"INSUFFICIENT_SENDER_BALANCE: ({tx.SenderAddress})_BALANCE = {senderBalance}");
return InsufficientFundsForTransfer(tx, senderBalance);
}
bool overflows;
if (spec.IsEip1559Enabled && !tx.IsFree())
{
overflows = UInt256.MultiplyOverflow((UInt256)tx.GasLimit, tx.MaxFeePerGas, out UInt256 maxGasFee);
if (overflows || balanceLeft < maxGasFee)
{
TraceLogInvalidTx(tx, $"INSUFFICIENT_MAX_FEE_PER_GAS_FOR_SENDER_BALANCE: ({tx.SenderAddress})_BALANCE = {senderBalance}, MAX_FEE_PER_GAS: {tx.MaxFeePerGas}");
return InsufficientFundsForGas(tx, senderBalance, tx.MaxFeePerGas);
}
if (tx.SupportsBlobs)
{
overflows = UInt256.MultiplyOverflow(BlobGasCalculator.CalculateBlobGas(tx), (UInt256)tx.MaxFeePerBlobGas!, out UInt256 maxBlobGasFee);
if (overflows || UInt256.AddOverflow(maxGasFee, maxBlobGasFee, out UInt256 multidimGasFee) || multidimGasFee > balanceLeft)
{
TraceLogInvalidTx(tx, $"INSUFFICIENT_MAX_FEE_PER_BLOB_GAS_FOR_SENDER_BALANCE: ({tx.SenderAddress})_BALANCE = {senderBalance}");
return InsufficientFundsForGas(tx, senderBalance, effectiveGasPrice);
}
}
}
overflows = UInt256.MultiplyOverflow((UInt256)tx.GasLimit, effectiveGasPrice, out senderReservedGasPayment);
if (!overflows && tx.SupportsBlobs)
{
if (validate)
{
if (!BlobGasCalculator.TryCalculateFeePerBlobGas(header, spec.BlobBaseFeeUpdateFraction, out UInt256 feePerBlobGas))
{
overflows = true;
}
else if (tx.MaxFeePerBlobGas < feePerBlobGas)
{
TraceLogInvalidTx(tx, "INSUFFICIENT_MAX_FEE_PER_BLOB_GAS");
return TransactionResult.WithDetail(TransactionResult.ErrorType.InsufficientSenderBalance, BlockErrorMessages.InsufficientMaxFeePerBlobGas);
}
}
if (!overflows)
{
overflows = !_blobBaseFeeCalculator.TryCalculateBlobBaseFee(header, tx, spec.BlobBaseFeeUpdateFraction, out blobBaseFee);
if (!overflows)
{
overflows = UInt256.AddOverflow(senderReservedGasPayment, blobBaseFee, out senderReservedGasPayment);
}
}
}
if (overflows || senderReservedGasPayment > balanceLeft)
{
TraceLogInvalidTx(tx, $"INSUFFICIENT_SENDER_BALANCE: ({tx.SenderAddress})_BALANCE = {senderBalance}");
return InsufficientFundsForGas(tx, senderBalance, effectiveGasPrice);
}
if (!senderReservedGasPayment.IsZero) WorldState.SubtractFromBalance(tx.SenderAddress, senderReservedGasPayment, spec);
return TransactionResult.Ok;
}
private static TransactionResult InsufficientFundsForTransfer(Transaction tx, UInt256 senderBalance) =>
TransactionResult.ErrorType.InsufficientSenderBalance.WithDetail(
$"insufficient funds for transfer: address {tx.SenderAddress?.ToString(withEip55Checksum: true)} have {senderBalance} want {tx.Value}");
private static TransactionResult InsufficientFundsForGas(Transaction tx, UInt256 senderBalance, UInt256 gasPrice)
{
UInt256.MultiplyOverflow((UInt256)tx.GasLimit, gasPrice, out UInt256 gasCost);
UInt256.AddOverflow(gasCost, tx.Value, out UInt256 want);
return TransactionResult.ErrorType.InsufficientMaxFeePerGasForSenderBalance.WithDetail(
$"insufficient sender balance for gas * price + value: address {tx.SenderAddress?.ToString(withEip55Checksum: true)} have {senderBalance} want {want}");
}
protected virtual TransactionResult IncrementNonce(Transaction tx, BlockHeader header, IReleaseSpec spec, ITxTracer tracer, ExecutionOptions opts)
{
bool validate = !opts.HasFlag(ExecutionOptions.SkipValidation);
UInt256 nonce = WorldState.GetNonce(tx.SenderAddress!);
if (validate && tx.Nonce != nonce)
{
TraceLogInvalidTx(tx, $"WRONG_TRANSACTION_NONCE: {tx.Nonce} (expected {nonce})");
// Geth core/state_transition.go ErrNonceTooHigh / ErrNonceTooLow.
string sender = tx.SenderAddress?.ToString(withEip55Checksum: true) ?? "unknown";
return tx.Nonce > nonce
? TransactionResult.ErrorType.TransactionNonceTooHigh.WithDetail(
$"nonce too high: address {sender}, tx: {tx.Nonce} state: {nonce}")
: TransactionResult.ErrorType.TransactionNonceTooLow.WithDetail(
$"nonce too low: address {sender}, tx: {tx.Nonce} state: {nonce}");
}
UInt256 newNonce = validate || nonce < ulong.MaxValue ? nonce + 1 : 0;
WorldState.SetNonce(tx.SenderAddress, newNonce);
return TransactionResult.Ok;
}
protected virtual void DecrementNonce(Transaction tx) => WorldState.DecrementNonce(tx.SenderAddress!);
[SkipLocalsInit]
private TransactionResult BuildExecutionEnvironment(
Transaction tx,
IReleaseSpec spec,
ICodeInfoRepository codeInfoRepository,
in StackAccessTracker accessTracker,
out ExecutionEnvironment env)
{
Address recipient = tx.GetRecipient(tx.IsContractCreation ? WorldState.GetNonce(tx.SenderAddress!) : 0);
if (recipient is null) ThrowInvalidDataException("Recipient has not been resolved properly before tx execution");
CodeInfo? codeInfo;
ReadOnlyMemory<byte> inputData = tx.IsMessageCall ? tx.Data : default;
if (tx.IsContractCreation)
{
codeInfo = CodeInfoFactory.CreateCodeInfo(tx.Data);
}
else
{
codeInfo = codeInfoRepository.GetCachedCodeInfo(recipient, spec, out Address? delegationAddress);
//We assume eip-7702 must be active if it is a delegation
if (delegationAddress is not null)
accessTracker.WarmUp(delegationAddress);
}
if (spec.UseHotAndColdStorage)
{
if (spec.UseTxAccessLists)
accessTracker.WarmUp(tx.AccessList); // eip-2930
if (spec.AddCoinbaseToTxAccessList)
accessTracker.WarmUp(VirtualMachine.BlockExecutionContext.Header.GasBeneficiary!);
accessTracker.WarmUp(recipient);
accessTracker.WarmUp(tx.SenderAddress!);
}
env = ExecutionEnvironment.Rent(
codeInfo: codeInfo,
executingAccount: recipient,
caller: tx.SenderAddress!,
codeSource: recipient,
callDepth: 0,
transferValue: in tx.ValueRef,
value: in tx.ValueRef,
inputData: in inputData);
return TransactionResult.Ok;
}
protected virtual bool ShouldValidate(ExecutionOptions opts) => !opts.HasFlag(ExecutionOptions.SkipValidation);
private int ExecuteEvmCall<TTracingInst>(
Transaction tx,
BlockHeader header,
IReleaseSpec spec,
ITxTracer tracer,
ExecutionOptions opts,
int delegationRefunds,
IntrinsicGas<TGasPolicy> gas,
in StackAccessTracker accessedItems,
TGasPolicy gasAvailable,
ExecutionEnvironment env,
out TransactionSubstate substate,
out GasConsumed gasConsumed)
where TTracingInst : struct, IFlag
{
substate = default;
gasConsumed = tx.GasLimit;
byte statusCode = StatusCode.Failure;
long selfDestructStateRefund = 0;
// EIP-7702 + EIP-8037: capture the tx-start state reservoir (post-Apply8037DelegationRefunds).
// The halt path needs this to correctly initialize the reservoir in ResetForHalt; the
// intrinsicGasStandard-based formula misses the auth refund and would charge the sender
// for unconsumed reservoir gas (1x AccountCreationCost = 131,488 per valid auth on
// existing account).
long postIntrinsicStateReservoir = TGasPolicy.GetStateReservoir(in gasAvailable);
Snapshot snapshot = WorldState.TakeSnapshot();
long floorGasLong = TGasPolicy.GetRemainingGas(gas.FloorGas);
PayValue(tx, spec, opts);
if (env.CodeInfo is not null)
{
if (tx.IsContractCreation)
{
// if transaction is a contract creation then recipient address is the contract deployment address
if (!PrepareDeployment(env.ExecutingAccount))
{
if (Logger.IsTrace) Logger.Trace("Restoring state from before transaction");
WorldState.Restore(snapshot);
TGasPolicy collisionIntrinsicGasStandard = gas.Standard;
gasConsumed = RefundOnContractCollision(
tx,
spec,
opts,
in gasAvailable,
VirtualMachine.TxExecutionContext.GasPrice,
in collisionIntrinsicGasStandard,
floorGasLong);
goto Complete;
}
}
}
else
{
// Gas for initcode execution is not consumed, only intrinsic creation transaction costs are charged.
long minimalGasLong = TGasPolicy.GetRemainingGas(gas.MinimalGas);
gasConsumed = minimalGasLong;
// If noValidation we didn't charge for gas, so do not refund; otherwise return unspent gas
if (!opts.HasFlag(ExecutionOptions.SkipValidation))
WorldState.AddToBalance(tx.SenderAddress!, (ulong)(tx.GasLimit - minimalGasLong) * VirtualMachine.TxExecutionContext.GasPrice, spec);
goto Complete;
}
ExecutionType executionType = tx.IsContractCreation ? ExecutionType.CREATE : ExecutionType.TRANSACTION;
using (VmState<TGasPolicy> state = VmState<TGasPolicy>.RentTopLevel(gasAvailable, executionType, env, in accessedItems, in snapshot))
{
substate = !TTracingInst.IsActive
? VirtualMachine.ExecuteTransaction(state, WorldState, tracer) // no GVM trick for ZK
: VirtualMachine.ExecuteTransaction<OnFlag>(state, WorldState, tracer);
Metrics.IncrementOpCodes(VirtualMachine.OpCodeCount);
gasAvailable = state.Gas;
if (tracer.IsTracingAccess)
{
tracer.ReportAccess(accessedItems.AccessedAddresses, accessedItems.AccessedStorageCells);
}
if (substate.ShouldRevert || substate.IsError)
{
if (Logger.IsTrace) Logger.Trace("Restoring state from before transaction");
WorldState.Restore(snapshot);
}
else
{
if (tx.IsContractCreation)
{
if (!DeployContract(spec, env.ExecutingAccount, in substate, in accessedItems, ref gasAvailable))
{
goto FailContractCreate;
}
}
selfDestructStateRefund = CalculateSelfDestructStateRefund(spec, in substate, in accessedItems, in gasAvailable);
// EIP-8037: defer destroy list processing to after PayFees so that
// burn logs include the priority fee in the balance.
bool deferFinalization = spec.IsEip7708Enabled && spec.IsEip8037Enabled;
if (!deferFinalization)
{
bool eip7708Enabled = spec.IsEip7708Enabled;
bool tracingRefunds = tracer.IsTracingRefunds;
foreach (Address toBeDestroyed in substate.DestroyList)
{
if (Logger.IsTrace) Logger.Trace($"Destroying account {toBeDestroyed}");
if (eip7708Enabled)
{
UInt256 balance = WorldState.GetBalance(toBeDestroyed);
if (!balance.IsZero)
{
substate.Logs.Add(TransferLog.CreateSelfDestruct(toBeDestroyed, balance));
}
}
WorldState.ClearStorage(toBeDestroyed);
WorldState.DeleteAccount(toBeDestroyed);
if (tracingRefunds)
{
tracer.ReportRefund(spec.GasCosts.DestroyRefund);
}
}
}
statusCode = StatusCode.Success;
}
}
gasConsumed = Refund(tx, header, spec, opts, in substate, gasAvailable, VirtualMachine.TxExecutionContext.GasPrice, delegationRefunds, selfDestructStateRefund, gas.FloorGas, gas.Standard, postIntrinsicStateReservoir);
goto Complete;
FailContractCreate:
if (Logger.IsTrace) Logger.Trace("Restoring state from before transaction");
if (spec.ChargeForTopLevelCreate)
{
TGasPolicy.SetOutOfGas(ref gasAvailable);
}
WorldState.Restore(snapshot);
TGasPolicy intrinsicGasStandard = gas.Standard;
if (spec.IsEip8037Enabled)
{
// Use postIntrinsicStateReservoir captured before EVM execution so any
// EIP-7702 auth refund applied via Apply8037DelegationRefunds is preserved
// (otherwise the sender pays AccountCreationCost per refunded auth even
// though no account was created).
gasConsumed = CompleteEip8037Halt(tx, spec, opts, ref gasAvailable, VirtualMachine.TxExecutionContext.GasPrice, in intrinsicGasStandard, floorGasLong, postIntrinsicStateReservoir);
}
else
{
gasConsumed = RefundOnFail(tx, spec, opts, in gasAvailable, VirtualMachine.TxExecutionContext.GasPrice, in intrinsicGasStandard, floorGasLong);
}
Complete:
if (!opts.HasFlag(ExecutionOptions.SkipValidation) && !_parallel)
{
header.GasUsed += gasConsumed.EffectiveBlockGas;
}
return statusCode;
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
static void RefundRevertedExecutionStateGas(IReleaseSpec spec, in TGasPolicy intrinsicGas, ref TGasPolicy gas)
{
if (!spec.IsEip8037Enabled)
{
return;
}
long stateGasFloor = TGasPolicy.GetStateReservoir(in intrinsicGas);
long revertedStateGas = TGasPolicy.GetStateGasUsed(in gas);
if (revertedStateGas > stateGasFloor)
{
TGasPolicy.RefundStateGas(ref gas, revertedStateGas, stateGasFloor);
}
}
// Common EIP-8037 halt-prepare-then-restore sequence shared by FailContractCreate
// and the substate.IsError branch of Refund. AggressiveInlining keeps codegen
// identical to the prior inline form on both hot paths.
[MethodImpl(MethodImplOptions.AggressiveInlining)]
private GasConsumed CompleteEip8037Halt(
Transaction tx,
IReleaseSpec spec,
ExecutionOptions opts,
ref TGasPolicy gas,
in UInt256 gasPrice,
in TGasPolicy intrinsicGasStandard,
long floorGas,
long postIntrinsicStateReservoir)
{
RefundRevertedExecutionStateGas(spec, in intrinsicGasStandard, ref gas);
long refundedCreateStateSpillForHalt = CalculateRefundedCreateStateSpillForHalt(in gas);
long intrinsicStateGas = TGasPolicy.GetStateReservoir(in intrinsicGasStandard);
TGasPolicy.ResetForHalt(ref gas, postIntrinsicStateReservoir, intrinsicStateGas);
return RefundOnTopLevelHalt(tx, spec, opts, in gas, in gasPrice, in intrinsicGasStandard, floorGas, refundedCreateStateSpillForHalt);
}