-
Notifications
You must be signed in to change notification settings - Fork 473
/
Copy pathVirtualMachine.cs
2785 lines (2386 loc) · 117 KB
/
VirtualMachine.cs
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: 2022 Demerzel Solutions Limited
// SPDX-License-Identifier: LGPL-3.0-only
using System;
using System.Collections.Generic;
using System.Runtime.CompilerServices;
using Nethermind.Core;
using Nethermind.Core.Crypto;
using Nethermind.Core.Extensions;
using Nethermind.Core.Specs;
using Nethermind.Evm.CodeAnalysis;
using Nethermind.Evm.Precompiles;
using Nethermind.Evm.Tracing;
using Nethermind.Logging;
using Nethermind.State;
using System.Diagnostics.CodeAnalysis;
using System.Runtime.Intrinsics;
using static Nethermind.Evm.VirtualMachine;
using static System.Runtime.CompilerServices.Unsafe;
#if DEBUG
using Nethermind.Evm.Tracing.Debugger;
#endif
[assembly: InternalsVisibleTo("Nethermind.Evm.Test")]
namespace Nethermind.Evm;
using Int256;
public class VirtualMachine : IVirtualMachine
{
public const int MaxCallDepth = 1024;
private static readonly UInt256 P255Int = (UInt256)System.Numerics.BigInteger.Pow(2, 255);
internal static ref readonly UInt256 P255 => ref P255Int;
internal static readonly UInt256 BigInt256 = 256;
internal static readonly UInt256 BigInt32 = 32;
internal static readonly byte[] BytesZero = [0];
internal static readonly byte[] BytesZero32 =
{
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0
};
internal static readonly byte[] BytesMax32 =
{
255, 255, 255, 255, 255, 255, 255, 255,
255, 255, 255, 255, 255, 255, 255, 255,
255, 255, 255, 255, 255, 255, 255, 255,
255, 255, 255, 255, 255, 255, 255, 255
};
internal static readonly PrecompileExecutionFailureException PrecompileExecutionFailureException = new();
internal static readonly OutOfGasException PrecompileOutOfGasException = new();
private readonly IVirtualMachine _evm;
public VirtualMachine(
IBlockhashProvider? blockhashProvider,
ISpecProvider? specProvider,
ICodeInfoRepository codeInfoRepository,
ILogManager? logManager)
{
ILogger logger = logManager?.GetClassLogger() ?? throw new ArgumentNullException(nameof(logManager));
_evm = logger.IsTrace
? new VirtualMachine<IsTracing>(blockhashProvider, specProvider, logger)
: new VirtualMachine<NotTracing>(blockhashProvider, specProvider, logger);
}
public TransactionSubstate Run<TTracingActions>(EvmState state, IWorldState worldState, ITxTracer txTracer)
where TTracingActions : struct, VirtualMachine.IIsTracing
=> _evm.Run<TTracingActions>(state, worldState, txTracer);
internal readonly ref struct CallResult
{
public static CallResult InvalidSubroutineEntry => new(EvmExceptionType.InvalidSubroutineEntry);
public static CallResult InvalidSubroutineReturn => new(EvmExceptionType.InvalidSubroutineReturn);
public static CallResult OutOfGasException => new(EvmExceptionType.OutOfGas);
public static CallResult AccessViolationException => new(EvmExceptionType.AccessViolation);
public static CallResult InvalidJumpDestination => new(EvmExceptionType.InvalidJumpDestination);
public static CallResult InvalidInstructionException => new(EvmExceptionType.BadInstruction);
public static CallResult StaticCallViolationException => new(EvmExceptionType.StaticCallViolation);
public static CallResult StackOverflowException => new(EvmExceptionType.StackOverflow); // TODO: use these to avoid CALL POP attacks
public static CallResult StackUnderflowException => new(EvmExceptionType.StackUnderflow); // TODO: use these to avoid CALL POP attacks
public static CallResult InvalidCodeException => new(EvmExceptionType.InvalidCode);
public static CallResult Empty => new(default, null);
public static object BoxedEmpty { get; } = new object();
public CallResult(EvmState stateToExecute)
{
StateToExecute = stateToExecute;
Output = Array.Empty<byte>();
PrecompileSuccess = null;
ShouldRevert = false;
ExceptionType = EvmExceptionType.None;
}
private CallResult(EvmExceptionType exceptionType)
{
StateToExecute = null;
Output = StatusCode.FailureBytes;
PrecompileSuccess = null;
ShouldRevert = false;
ExceptionType = exceptionType;
}
public CallResult(ReadOnlyMemory<byte> output, bool? precompileSuccess, bool shouldRevert = false, EvmExceptionType exceptionType = EvmExceptionType.None)
{
StateToExecute = null;
Output = output;
PrecompileSuccess = precompileSuccess;
ShouldRevert = shouldRevert;
ExceptionType = exceptionType;
}
public EvmState? StateToExecute { get; }
public ReadOnlyMemory<byte> Output { get; }
public EvmExceptionType ExceptionType { get; }
public bool ShouldRevert { get; }
public bool? PrecompileSuccess { get; } // TODO: check this behaviour as it seems it is required and previously that was not the case
public bool IsReturn => StateToExecute is null;
public bool IsException => ExceptionType != EvmExceptionType.None;
}
public interface IIsTracing { }
public readonly struct NotTracing : IIsTracing { }
public readonly struct IsTracing : IIsTracing { }
}
internal sealed class VirtualMachine<TLogger> : IVirtualMachine where TLogger : struct, IIsTracing
{
private readonly byte[] _chainId;
private readonly IBlockhashProvider _blockhashProvider;
private readonly ISpecProvider _specProvider;
private readonly ILogger _logger;
private IWorldState _state = null!;
private readonly Stack<EvmState> _stateStack = new();
private (Address Address, bool ShouldDelete) _parityTouchBugAccount = (Address.FromNumber(3), false);
private ReadOnlyMemory<byte> _returnDataBuffer = Array.Empty<byte>();
private ITxTracer _txTracer = NullTxTracer.Instance;
public VirtualMachine(
IBlockhashProvider? blockhashProvider,
ISpecProvider? specProvider,
ILogger? logger)
{
_logger = logger ?? throw new ArgumentNullException(nameof(logger));
_blockhashProvider = blockhashProvider ?? throw new ArgumentNullException(nameof(blockhashProvider));
_specProvider = specProvider ?? throw new ArgumentNullException(nameof(specProvider));
_chainId = ((UInt256)specProvider.ChainId).ToBigEndian();
}
public TransactionSubstate Run<TTracingActions>(EvmState state, IWorldState worldState, ITxTracer txTracer)
where TTracingActions : struct, IIsTracing
{
_txTracer = txTracer;
_state = worldState;
ref readonly TxExecutionContext txExecutionContext = ref state.Env.TxExecutionContext;
ICodeInfoRepository codeInfoRepository = txExecutionContext.CodeInfoRepository;
IReleaseSpec spec = _specProvider.GetSpec(txExecutionContext.BlockExecutionContext.Header.Number, txExecutionContext.BlockExecutionContext.Header.Timestamp);
EvmState currentState = state;
ReadOnlyMemory<byte>? previousCallResult = null;
ZeroPaddedSpan previousCallOutput = ZeroPaddedSpan.Empty;
UInt256 previousCallOutputDestination = UInt256.Zero;
bool isTracing = _txTracer.IsTracing;
while (true)
{
Exception? failure = null;
if (!currentState.IsContinuation)
{
_returnDataBuffer = Array.Empty<byte>();
}
try
{
CallResult callResult;
if (currentState.IsPrecompile)
{
if (typeof(TTracingActions) == typeof(IsTracing))
{
_txTracer.ReportAction(currentState.GasAvailable, currentState.Env.Value, currentState.From, currentState.To, currentState.Env.InputData, currentState.ExecutionType, true);
}
callResult = ExecutePrecompile(currentState, spec);
if (!callResult.PrecompileSuccess.Value)
{
if (callResult.IsException)
{
failure = VirtualMachine.PrecompileOutOfGasException;
goto Failure;
}
if (currentState.IsPrecompile && currentState.IsTopLevel)
{
failure = VirtualMachine.PrecompileExecutionFailureException;
// TODO: when direct / calls are treated same we should not need such differentiation
goto Failure;
}
// TODO: testing it as it seems the way to pass zkSNARKs tests
currentState.GasAvailable = 0;
}
}
else
{
if (typeof(TTracingActions) == typeof(IsTracing) && !currentState.IsContinuation)
{
_txTracer.ReportAction(currentState.GasAvailable,
currentState.Env.Value,
currentState.From,
currentState.To,
currentState.ExecutionType.IsAnyCreate()
? currentState.Env.CodeInfo.MachineCode
: currentState.Env.InputData,
currentState.ExecutionType);
if (_txTracer.IsTracingCode) _txTracer.ReportByteCode(currentState.Env.CodeInfo.MachineCode);
}
callResult = !_txTracer.IsTracingInstructions
? ExecuteCall<NotTracing>(currentState, previousCallResult, previousCallOutput, previousCallOutputDestination, spec)
: ExecuteCall<IsTracing>(currentState, previousCallResult, previousCallOutput, previousCallOutputDestination, spec);
if (!callResult.IsReturn)
{
_stateStack.Push(currentState);
currentState = callResult.StateToExecute;
previousCallResult = null; // TODO: testing on ropsten sync, write VirtualMachineTest for this case as it was not covered by Ethereum tests (failing block 9411 on Ropsten https://ropsten.etherscan.io/vmtrace?txhash=0x666194d15c14c54fffafab1a04c08064af165870ef9a87f65711dcce7ed27fe1)
_returnDataBuffer = Array.Empty<byte>();
previousCallOutput = ZeroPaddedSpan.Empty;
continue;
}
if (callResult.IsException)
{
if (typeof(TTracingActions) == typeof(IsTracing)) _txTracer.ReportActionError(callResult.ExceptionType);
_state.Restore(currentState.Snapshot);
RevertParityTouchBugAccount(spec);
if (currentState.IsTopLevel)
{
return new TransactionSubstate(callResult.ExceptionType, isTracing);
}
previousCallResult = StatusCode.FailureBytes;
previousCallOutputDestination = UInt256.Zero;
_returnDataBuffer = Array.Empty<byte>();
previousCallOutput = ZeroPaddedSpan.Empty;
currentState.Dispose();
currentState = _stateStack.Pop();
currentState.IsContinuation = true;
continue;
}
}
if (currentState.IsTopLevel)
{
if (typeof(TTracingActions) == typeof(IsTracing))
{
long codeDepositGasCost = CodeDepositHandler.CalculateCost(callResult.Output.Length, spec);
if (callResult.IsException)
{
_txTracer.ReportActionError(callResult.ExceptionType);
}
else if (callResult.ShouldRevert)
{
_txTracer.ReportActionRevert(currentState.ExecutionType.IsAnyCreate()
? currentState.GasAvailable - codeDepositGasCost
: currentState.GasAvailable,
callResult.Output);
}
else
{
if (currentState.ExecutionType.IsAnyCreate() && currentState.GasAvailable < codeDepositGasCost)
{
if (spec.ChargeForTopLevelCreate)
{
_txTracer.ReportActionError(EvmExceptionType.OutOfGas);
}
else
{
_txTracer.ReportActionEnd(currentState.GasAvailable, currentState.To, callResult.Output);
}
}
// Reject code starting with 0xEF if EIP-3541 is enabled.
else if (currentState.ExecutionType.IsAnyCreate() && CodeDepositHandler.CodeIsInvalid(spec, callResult.Output))
{
_txTracer.ReportActionError(EvmExceptionType.InvalidCode);
}
else
{
if (currentState.ExecutionType.IsAnyCreate())
{
_txTracer.ReportActionEnd(currentState.GasAvailable - codeDepositGasCost, currentState.To, callResult.Output);
}
else
{
_txTracer.ReportActionEnd(currentState.GasAvailable, _returnDataBuffer);
}
}
}
}
return new TransactionSubstate(
callResult.Output,
currentState.Refund,
currentState.AccessTracker.DestroyList,
(IReadOnlyCollection<LogEntry>)currentState.AccessTracker.Logs,
callResult.ShouldRevert,
isTracerConnected: isTracing,
_logger);
}
Address callCodeOwner = currentState.Env.ExecutingAccount;
using (EvmState previousState = currentState)
{
currentState = _stateStack.Pop();
currentState.IsContinuation = true;
currentState.GasAvailable += previousState.GasAvailable;
bool previousStateSucceeded = true;
if (!callResult.ShouldRevert)
{
long gasAvailableForCodeDeposit = previousState.GasAvailable; // TODO: refactor, this is to fix 61363 Ropsten
if (previousState.ExecutionType.IsAnyCreate())
{
previousCallResult = callCodeOwner.Bytes;
previousCallOutputDestination = UInt256.Zero;
_returnDataBuffer = Array.Empty<byte>();
previousCallOutput = ZeroPaddedSpan.Empty;
long codeDepositGasCost = CodeDepositHandler.CalculateCost(callResult.Output.Length, spec);
bool invalidCode = CodeDepositHandler.CodeIsInvalid(spec, callResult.Output);
if (gasAvailableForCodeDeposit >= codeDepositGasCost && !invalidCode)
{
ReadOnlyMemory<byte> code = callResult.Output;
codeInfoRepository.InsertCode(_state, code, callCodeOwner, spec);
currentState.GasAvailable -= codeDepositGasCost;
if (typeof(TTracingActions) == typeof(IsTracing))
{
_txTracer.ReportActionEnd(previousState.GasAvailable - codeDepositGasCost, callCodeOwner, callResult.Output);
}
}
else if (spec.FailOnOutOfGasCodeDeposit || invalidCode)
{
currentState.GasAvailable -= gasAvailableForCodeDeposit;
worldState.Restore(previousState.Snapshot);
if (!previousState.IsCreateOnPreExistingAccount)
{
_state.DeleteAccount(callCodeOwner);
}
previousCallResult = BytesZero;
previousStateSucceeded = false;
if (typeof(TTracingActions) == typeof(IsTracing))
{
_txTracer.ReportActionError(invalidCode ? EvmExceptionType.InvalidCode : EvmExceptionType.OutOfGas);
}
}
else if (typeof(TTracingActions) == typeof(IsTracing))
{
_txTracer.ReportActionEnd(0L, callCodeOwner, callResult.Output);
}
}
else
{
_returnDataBuffer = callResult.Output;
previousCallResult = callResult.PrecompileSuccess.HasValue ? (callResult.PrecompileSuccess.Value ? StatusCode.SuccessBytes : StatusCode.FailureBytes) : StatusCode.SuccessBytes;
previousCallOutput = callResult.Output.Span.SliceWithZeroPadding(0, Math.Min(callResult.Output.Length, (int)previousState.OutputLength));
previousCallOutputDestination = (ulong)previousState.OutputDestination;
if (previousState.IsPrecompile)
{
// parity induced if else for vmtrace
if (_txTracer.IsTracingInstructions)
{
_txTracer.ReportMemoryChange(previousCallOutputDestination, previousCallOutput);
}
}
if (typeof(TTracingActions) == typeof(IsTracing))
{
_txTracer.ReportActionEnd(previousState.GasAvailable, _returnDataBuffer);
}
}
if (previousStateSucceeded)
{
previousState.CommitToParent(currentState);
}
}
else
{
worldState.Restore(previousState.Snapshot);
_returnDataBuffer = callResult.Output;
previousCallResult = StatusCode.FailureBytes;
previousCallOutput = callResult.Output.Span.SliceWithZeroPadding(0, Math.Min(callResult.Output.Length, (int)previousState.OutputLength));
previousCallOutputDestination = (ulong)previousState.OutputDestination;
if (typeof(TTracingActions) == typeof(IsTracing))
{
_txTracer.ReportActionRevert(previousState.GasAvailable, callResult.Output);
}
}
}
}
catch (Exception ex) when (ex is EvmException or OverflowException)
{
failure = ex;
goto Failure;
}
continue;
Failure:
{
if (typeof(TLogger) == typeof(IsTracing)) _logger.Trace($"exception ({failure.GetType().Name}) in {currentState.ExecutionType} at depth {currentState.Env.CallDepth} - restoring snapshot");
_state.Restore(currentState.Snapshot);
RevertParityTouchBugAccount(spec);
if (txTracer.IsTracingInstructions)
{
txTracer.ReportOperationRemainingGas(0);
txTracer.ReportOperationError(failure is EvmException evmException ? evmException.ExceptionType : EvmExceptionType.Other);
}
if (typeof(TTracingActions) == typeof(IsTracing))
{
EvmException evmException = failure as EvmException;
_txTracer.ReportActionError(evmException?.ExceptionType ?? EvmExceptionType.Other);
}
if (currentState.IsTopLevel)
{
return new TransactionSubstate(failure is OverflowException ? EvmExceptionType.Other : (failure as EvmException).ExceptionType, isTracing);
}
previousCallResult = StatusCode.FailureBytes;
previousCallOutputDestination = UInt256.Zero;
_returnDataBuffer = Array.Empty<byte>();
previousCallOutput = ZeroPaddedSpan.Empty;
currentState.Dispose();
currentState = _stateStack.Pop();
currentState.IsContinuation = true;
}
}
}
private void RevertParityTouchBugAccount(IReleaseSpec spec)
{
if (_parityTouchBugAccount.ShouldDelete)
{
if (_state.AccountExists(_parityTouchBugAccount.Address))
{
_state.AddToBalance(_parityTouchBugAccount.Address, UInt256.Zero, spec);
}
_parityTouchBugAccount.ShouldDelete = false;
}
}
private static bool UpdateGas(long gasCost, ref long gasAvailable)
{
if (gasAvailable < gasCost)
{
return false;
}
gasAvailable -= gasCost;
return true;
}
private static void UpdateGasUp(long refund, ref long gasAvailable)
{
gasAvailable += refund;
}
private bool ChargeAccountAccessGas(ref long gasAvailable, EvmState vmState, Address address, bool chargeForDelegation, IReleaseSpec spec, bool chargeForWarm = true)
{
if (!spec.UseHotAndColdStorage)
{
return true;
}
bool notOutOfGas = ChargeAccountGas(ref gasAvailable, vmState, address, spec);
return notOutOfGas
&& chargeForDelegation
&& vmState.Env.TxExecutionContext.CodeInfoRepository.TryGetDelegation(_state, address, out Address delegated)
? ChargeAccountGas(ref gasAvailable, vmState, delegated, spec)
: notOutOfGas;
bool ChargeAccountGas(ref long gasAvailable, EvmState vmState, Address address, IReleaseSpec spec)
{
bool result = true;
if (_txTracer.IsTracingAccess) // when tracing access we want cost as if it was warmed up from access list
{
vmState.AccessTracker.WarmUp(address);
}
if (vmState.AccessTracker.IsCold(address) && !address.IsPrecompile(spec))
{
result = UpdateGas(GasCostOf.ColdAccountAccess, ref gasAvailable);
vmState.AccessTracker.WarmUp(address);
}
else if (chargeForWarm)
{
result = UpdateGas(GasCostOf.WarmStateRead, ref gasAvailable);
}
return result;
}
}
private enum StorageAccessType
{
SLOAD,
SSTORE
}
private bool ChargeStorageAccessGas(
ref long gasAvailable,
EvmState vmState,
in StorageCell storageCell,
StorageAccessType storageAccessType,
IReleaseSpec spec)
{
// Console.WriteLine($"Accessing {storageCell} {storageAccessType}");
bool result = true;
if (spec.UseHotAndColdStorage)
{
if (_txTracer.IsTracingAccess) // when tracing access we want cost as if it was warmed up from access list
{
vmState.AccessTracker.WarmUp(in storageCell);
}
if (vmState.AccessTracker.IsCold(in storageCell))
{
result = UpdateGas(GasCostOf.ColdSLoad, ref gasAvailable);
vmState.AccessTracker.WarmUp(in storageCell);
}
else if (storageAccessType == StorageAccessType.SLOAD)
{
// we do not charge for WARM_STORAGE_READ_COST in SSTORE scenario
result = UpdateGas(GasCostOf.WarmStateRead, ref gasAvailable);
}
}
return result;
}
private CallResult ExecutePrecompile(EvmState state, IReleaseSpec spec)
{
ReadOnlyMemory<byte> callData = state.Env.InputData;
UInt256 transferValue = state.Env.TransferValue;
long gasAvailable = state.GasAvailable;
IPrecompile precompile = state.Env.CodeInfo.Precompile;
long baseGasCost = precompile.BaseGasCost(spec);
long blobGasCost = precompile.DataGasCost(callData, spec);
bool wasCreated = _state.AddToBalanceAndCreateIfNotExists(state.Env.ExecutingAccount, transferValue, spec);
// https://github.com/ethereum/EIPs/blob/master/EIPS/eip-161.md
// An additional issue was found in Parity,
// where the Parity client incorrectly failed
// to revert empty account deletions in a more limited set of contexts
// involving out-of-gas calls to precompiled contracts;
// the new Geth behavior matches Parity’s,
// and empty accounts will cease to be a source of concern in general
// in about one week once the state clearing process finishes.
if (state.Env.ExecutingAccount.Equals(_parityTouchBugAccount.Address)
&& !wasCreated
&& transferValue.IsZero
&& spec.ClearEmptyAccountWhenTouched)
{
_parityTouchBugAccount.ShouldDelete = true;
}
if (!UpdateGas(checked(baseGasCost + blobGasCost), ref gasAvailable))
{
return new(default, false, true, EvmExceptionType.OutOfGas);
}
state.GasAvailable = gasAvailable;
try
{
(ReadOnlyMemory<byte> output, bool success) = precompile.Run(callData, spec);
CallResult callResult = new(output, success, !success);
return callResult;
}
catch (DllNotFoundException exception)
{
if (_logger.IsError) _logger.Error($"Failed to load one of the dependencies of {precompile.GetType()} precompile", exception);
throw;
}
catch (Exception exception)
{
if (_logger.IsError) _logger.Error($"Precompiled contract ({precompile.GetType()}) execution exception", exception);
CallResult callResult = new(default, false, true);
return callResult;
}
}
/// <remarks>
/// Struct generic parameter is used to burn out all the if statements and inner code
/// by typeof(TTracingInstructions) == typeof(NotTracing) checks that are evaluated to constant
/// values at compile time.
/// </remarks>
[SkipLocalsInit]
private CallResult ExecuteCall<TTracingInstructions>(EvmState vmState, ReadOnlyMemory<byte>? previousCallResult, ZeroPaddedSpan previousCallOutput, scoped in UInt256 previousCallOutputDestination, IReleaseSpec spec)
where TTracingInstructions : struct, IIsTracing
{
ref readonly ExecutionEnvironment env = ref vmState.Env;
if (!vmState.IsContinuation)
{
_state.AddToBalanceAndCreateIfNotExists(env.ExecutingAccount, env.TransferValue, spec);
if (vmState.ExecutionType.IsAnyCreate() && spec.ClearEmptyAccountWhenTouched)
{
_state.IncrementNonce(env.ExecutingAccount);
}
}
if (env.CodeInfo.MachineCode.Length == 0)
{
if (!vmState.IsTopLevel)
{
Metrics.IncrementEmptyCalls();
}
goto Empty;
}
vmState.InitStacks();
EvmStack<TTracingInstructions> stack = new(vmState.DataStackHead, _txTracer, vmState.DataStack.AsSpan());
long gasAvailable = vmState.GasAvailable;
if (previousCallResult is not null)
{
stack.PushBytes(previousCallResult.Value.Span);
if (typeof(TTracingInstructions) == typeof(IsTracing)) _txTracer.ReportOperationRemainingGas(vmState.GasAvailable);
}
if (previousCallOutput.Length > 0)
{
UInt256 localPreviousDest = previousCallOutputDestination;
if (!UpdateMemoryCost(vmState, ref gasAvailable, in localPreviousDest, (ulong)previousCallOutput.Length))
{
goto OutOfGas;
}
vmState.Memory.Save(in localPreviousDest, previousCallOutput);
}
// Struct generic parameter is used to burn out all the if statements
// and inner code by typeof(TTracing) == typeof(NotTracing)
// checks that are evaluated to constant values at compile time.
// This only works for structs, not for classes or interface types
// which use shared generics.
if (!_txTracer.IsTracingRefunds)
{
return _txTracer.IsTracingOpLevelStorage ?
ExecuteCode<TTracingInstructions, NotTracing, IsTracing>(vmState, ref stack, gasAvailable, spec) :
ExecuteCode<TTracingInstructions, NotTracing, NotTracing>(vmState, ref stack, gasAvailable, spec);
}
else
{
return _txTracer.IsTracingOpLevelStorage ?
ExecuteCode<TTracingInstructions, IsTracing, IsTracing>(vmState, ref stack, gasAvailable, spec) :
ExecuteCode<TTracingInstructions, IsTracing, NotTracing>(vmState, ref stack, gasAvailable, spec);
}
Empty:
return CallResult.Empty;
OutOfGas:
return CallResult.OutOfGasException;
}
[SkipLocalsInit]
private CallResult ExecuteCode<TTracingInstructions, TTracingRefunds, TTracingStorage>(EvmState vmState, scoped ref EvmStack<TTracingInstructions> stack, long gasAvailable, IReleaseSpec spec)
where TTracingInstructions : struct, IIsTracing
where TTracingRefunds : struct, IIsTracing
where TTracingStorage : struct, IIsTracing
{
int programCounter = vmState.ProgramCounter;
ref readonly ExecutionEnvironment env = ref vmState.Env;
ref readonly TxExecutionContext txCtx = ref env.TxExecutionContext;
ref readonly BlockExecutionContext blkCtx = ref txCtx.BlockExecutionContext;
ReadOnlySpan<byte> code = env.CodeInfo.MachineCode.Span;
EvmExceptionType exceptionType = EvmExceptionType.None;
bool isRevert = false;
#if DEBUG
DebugTracer? debugger = _txTracer.GetTracer<DebugTracer>();
#endif
SkipInit(out UInt256 a);
SkipInit(out UInt256 b);
SkipInit(out UInt256 c);
SkipInit(out UInt256 result);
SkipInit(out StorageCell storageCell);
object returnData;
ZeroPaddedSpan slice;
bool isCancelable = _txTracer.IsCancelable;
uint codeLength = (uint)code.Length;
while ((uint)programCounter < codeLength)
{
#if DEBUG
debugger?.TryWait(ref vmState, ref programCounter, ref gasAvailable, ref stack.Head);
#endif
Instruction instruction = (Instruction)code[programCounter];
if (isCancelable && _txTracer.IsCancelled)
{
ThrowOperationCanceledException();
}
// Evaluated to constant at compile time and code elided if not tracing
if (typeof(TTracingInstructions) == typeof(IsTracing))
StartInstructionTrace(instruction, vmState, gasAvailable, programCounter, in stack);
programCounter++;
Span<byte> bytes;
switch (instruction)
{
case Instruction.STOP:
{
goto EmptyReturn;
}
case Instruction.ADD:
{
gasAvailable -= GasCostOf.VeryLow;
if (!stack.PopUInt256(out b)) goto StackUnderflow;
if (!stack.PopUInt256(out a)) goto StackUnderflow;
UInt256.Add(in a, in b, out result);
stack.PushUInt256(result);
break;
}
case Instruction.MUL:
{
gasAvailable -= GasCostOf.Low;
if (!stack.PopUInt256(out a)) goto StackUnderflow;
if (!stack.PopUInt256(out b)) goto StackUnderflow;
UInt256.Multiply(in a, in b, out result);
stack.PushUInt256(in result);
break;
}
case Instruction.SUB:
{
gasAvailable -= GasCostOf.VeryLow;
if (!stack.PopUInt256(out a)) goto StackUnderflow;
if (!stack.PopUInt256(out b)) goto StackUnderflow;
UInt256.Subtract(in a, in b, out result);
stack.PushUInt256(in result);
break;
}
case Instruction.DIV:
{
gasAvailable -= GasCostOf.Low;
if (!stack.PopUInt256(out a)) goto StackUnderflow;
if (!stack.PopUInt256(out b)) goto StackUnderflow;
if (b.IsZero)
{
stack.PushZero();
}
else
{
UInt256.Divide(in a, in b, out result);
stack.PushUInt256(in result);
}
break;
}
case Instruction.SDIV:
{
gasAvailable -= GasCostOf.Low;
if (!stack.PopUInt256(out a)) goto StackUnderflow;
if (!stack.PopUInt256(out b)) goto StackUnderflow;
if (b.IsZero)
{
stack.PushZero();
}
else if (As<UInt256, Int256>(ref b) == Int256.MinusOne && a == P255)
{
result = P255;
stack.PushUInt256(in result);
}
else
{
Int256.Divide(in As<UInt256, Int256>(ref a), in As<UInt256, Int256>(ref b), out As<UInt256, Int256>(ref result));
stack.PushUInt256(in result);
}
break;
}
case Instruction.MOD:
{
gasAvailable -= GasCostOf.Low;
if (!stack.PopUInt256(out a)) goto StackUnderflow;
if (!stack.PopUInt256(out b)) goto StackUnderflow;
UInt256.Mod(in a, in b, out result);
stack.PushUInt256(in result);
break;
}
case Instruction.SMOD:
{
gasAvailable -= GasCostOf.Low;
if (!stack.PopUInt256(out a)) goto StackUnderflow;
if (!stack.PopUInt256(out b)) goto StackUnderflow;
if (b.IsZeroOrOne)
{
stack.PushZero();
}
else
{
As<UInt256, Int256>(ref a)
.Mod(in As<UInt256, Int256>(ref b), out As<UInt256, Int256>(ref result));
stack.PushUInt256(in result);
}
break;
}
case Instruction.ADDMOD:
{
gasAvailable -= GasCostOf.Mid;
if (!stack.PopUInt256(out a)) goto StackUnderflow;
if (!stack.PopUInt256(out b)) goto StackUnderflow;
if (!stack.PopUInt256(out c)) goto StackUnderflow;
if (c.IsZero)
{
stack.PushZero();
}
else
{
UInt256.AddMod(a, b, c, out result);
stack.PushUInt256(in result);
}
break;
}
case Instruction.MULMOD:
{
gasAvailable -= GasCostOf.Mid;
if (!stack.PopUInt256(out a)) goto StackUnderflow;
if (!stack.PopUInt256(out b)) goto StackUnderflow;
if (!stack.PopUInt256(out c)) goto StackUnderflow;
if (c.IsZero)
{
stack.PushZero();
}
else
{
UInt256.MultiplyMod(in a, in b, in c, out result);
stack.PushUInt256(in result);
}
break;
}
case Instruction.EXP:
{
gasAvailable -= GasCostOf.Exp;
Metrics.ExpOpcode++;
if (!stack.PopUInt256(out a)) goto StackUnderflow;
bytes = stack.PopWord256();
int leadingZeros = bytes.LeadingZerosCount();
if (leadingZeros != 32)
{
int expSize = 32 - leadingZeros;
gasAvailable -= spec.GetExpByteCost() * expSize;
}
else
{
stack.PushOne();
break;
}
if (a.IsZero)
{
stack.PushZero();
}
else if (a.IsOne)
{
stack.PushOne();
}
else
{
UInt256.Exp(a, new UInt256(bytes, true), out result);
stack.PushUInt256(in result);
}
break;
}
case Instruction.SIGNEXTEND:
{
gasAvailable -= GasCostOf.Low;
if (!stack.PopUInt256(out a)) goto StackUnderflow;
if (a >= BigInt32)
{
if (!stack.EnsureDepth(1)) goto StackUnderflow;
break;
}
int position = 31 - (int)a;
bytes = stack.PeekWord256();
sbyte sign = (sbyte)bytes[position];
if (sign >= 0)
{
BytesZero32.AsSpan(0, position).CopyTo(bytes[..position]);
}
else
{
BytesMax32.AsSpan(0, position).CopyTo(bytes[..position]);
}
// Didn't remove from stack so don't need to push back
break;
}
case Instruction.LT:
{
gasAvailable -= GasCostOf.VeryLow;
if (!stack.PopUInt256(out a)) goto StackUnderflow;
if (!stack.PopUInt256(out b)) goto StackUnderflow;
if (a < b)
{
stack.PushOne();
}
else
{
stack.PushZero();
}
break;
}
case Instruction.GT:
{
gasAvailable -= GasCostOf.VeryLow;
if (!stack.PopUInt256(out a)) goto StackUnderflow;
if (!stack.PopUInt256(out b)) goto StackUnderflow;
if (a > b)
{
stack.PushOne();
}
else
{
stack.PushZero();
}
break;
}
case Instruction.SLT:
{
gasAvailable -= GasCostOf.VeryLow;
if (!stack.PopUInt256(out a)) goto StackUnderflow;
if (!stack.PopUInt256(out b)) goto StackUnderflow;
if (As<UInt256, Int256>(ref a).CompareTo(As<UInt256, Int256>(ref b)) < 0)
{
stack.PushOne();
}
else
{
stack.PushZero();
}
break;