-
Notifications
You must be signed in to change notification settings - Fork 380
/
VirtualMachine.cs
3017 lines (2654 loc) · 140 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
// Copyright (c) 2021 Demerzel Solutions Limited
// This file is part of the Nethermind library.
//
// The Nethermind library is free software: you can redistribute it and/or modify
// it under the terms of the GNU Lesser General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// The Nethermind library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public License
// along with the Nethermind. If not, see <http://www.gnu.org/licenses/>.
using System;
using System.Collections.Generic;
using System.Numerics;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using Nethermind.Core;
using Nethermind.Core.Caching;
using Nethermind.Core.Crypto;
using Nethermind.Core.Extensions;
using Nethermind.Core.Specs;
using Nethermind.Evm.CodeAnalysis;
using Nethermind.Int256;
using Nethermind.Evm.Precompiles;
using Nethermind.Evm.Precompiles.Bls.Shamatar;
using Nethermind.Evm.Precompiles.Snarks.Shamatar;
using Nethermind.Evm.Tracing;
using Nethermind.Logging;
using Nethermind.State;
using ILDelegate = System.Func<long, Nethermind.Evm.EvmExceptionType>;
[assembly: InternalsVisibleTo("Nethermind.Evm.Test")]
namespace Nethermind.Evm
{
public class VirtualMachine : IVirtualMachine
{
public const int MaxCallDepth = 1024;
private bool _simdOperationsEnabled = Vector<byte>.Count == 32;
private UInt256 P255Int = (UInt256)BigInteger.Pow(2, 255);
private UInt256 P255 => P255Int;
private UInt256 BigInt256 = 256;
public UInt256 BigInt32 = 32;
internal byte[] BytesZero = { 0 };
internal 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 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
};
private readonly byte[] _chainId;
private readonly IBlockhashProvider _blockhashProvider;
private readonly ISpecProvider _specProvider;
private static readonly ICache<Keccak, CodeInfo> _codeCache =
new LruCache<Keccak, CodeInfo>(MemoryAllowance.CodeCacheSize, MemoryAllowance.CodeCacheSize,
"VM bytecodes");
private readonly ILogger _logger;
private IWorldState _worldState;
private IStateProvider _state;
private readonly Stack<EvmState> _stateStack = new();
private IStorageProvider _storage;
private (Address Address, bool ShouldDelete) _parityTouchBugAccount = (Address.FromNumber(3), false);
private Dictionary<Address, CodeInfo>? _precompiles;
private byte[] _returnDataBuffer = Array.Empty<byte>();
private ITxTracer _txTracer = NullTxTracer.Instance;
public VirtualMachine(
IBlockhashProvider? blockhashProvider,
ISpecProvider? specProvider,
ILogManager? logManager)
{
_logger = logManager?.GetClassLogger() ?? throw new ArgumentNullException(nameof(logManager));
_blockhashProvider = blockhashProvider ?? throw new ArgumentNullException(nameof(blockhashProvider));
_specProvider = specProvider ?? throw new ArgumentNullException(nameof(specProvider));
_chainId = ((UInt256)specProvider.ChainId).ToBigEndian();
InitializePrecompiledContracts();
}
public TransactionSubstate Run(EvmState state, IWorldState worldState, ITxTracer txTracer)
{
_txTracer = txTracer;
_state = worldState.StateProvider;
_storage = worldState.StorageProvider;
_worldState = worldState;
IReleaseSpec spec = _specProvider.GetSpec(state.Env.TxExecutionContext.Header.Number);
EvmState currentState = state;
byte[] previousCallResult = null;
ZeroPaddedSpan previousCallOutput = ZeroPaddedSpan.Empty;
UInt256 previousCallOutputDestination = UInt256.Zero;
while (true)
{
if (!currentState.IsContinuation)
{
_returnDataBuffer = Array.Empty<byte>();
}
try
{
CallResult callResult;
if (currentState.IsPrecompile)
{
if (_txTracer.IsTracingActions)
{
_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 (currentState.IsPrecompile && currentState.IsTopLevel)
{
Metrics.EvmExceptions++;
// TODO: when direct / calls are treated same we should not need such differentiation
throw new PrecompileExecutionFailureException();
}
// TODO: testing it as it seems the way to pass zkSNARKs tests
currentState.GasAvailable = 0;
}
}
else
{
if (_txTracer.IsTracingActions && !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 = ExecuteCall(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 (_txTracer.IsTracingActions) _txTracer.ReportActionError(callResult.ExceptionType);
_worldState.Restore(currentState.Snapshot);
if (_parityTouchBugAccount.ShouldDelete)
{
_state.AddToBalance(_parityTouchBugAccount.Address, UInt256.Zero, spec);
_parityTouchBugAccount.ShouldDelete = false;
}
if (currentState.IsTopLevel)
{
return new TransactionSubstate(callResult.ExceptionType,
_txTracer != NullTxTracer.Instance);
}
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 (_txTracer.IsTracingActions)
{
long codeDepositGasCost = CodeDepositHandler.CalculateCost(callResult.Output.Length, spec);
if (callResult.IsException)
{
_txTracer.ReportActionError(callResult.ExceptionType);
}
else if (callResult.ShouldRevert)
{
if (currentState.ExecutionType.IsAnyCreate())
{
_txTracer.ReportActionError(EvmExceptionType.Revert,
currentState.GasAvailable - codeDepositGasCost);
}
else
{
_txTracer.ReportActionError(EvmExceptionType.Revert, currentState.GasAvailable);
}
}
else
{
if (currentState.ExecutionType.IsAnyCreate() &&
currentState.GasAvailable < codeDepositGasCost)
{
_txTracer.ReportActionError(EvmExceptionType.OutOfGas);
}
// 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,
(IReadOnlyCollection<Address>)currentState.DestroyList,
(IReadOnlyCollection<LogEntry>)currentState.Logs,
callResult.ShouldRevert,
_txTracer != NullTxTracer.Instance);
}
Address callCodeOwner = currentState.Env.ExecutingAccount;
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)
{
Keccak codeHash = _state.UpdateCode(callResult.Output);
_state.UpdateCodeHash(callCodeOwner, codeHash, spec);
currentState.GasAvailable -= codeDepositGasCost;
if (_txTracer.IsTracingActions)
{
_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 (_txTracer.IsTracingActions)
{
if (invalidCode)
_txTracer.ReportActionError(EvmExceptionType.InvalidCode);
else
_txTracer.ReportActionError(EvmExceptionType.OutOfGas);
}
}
}
}
else
{
_returnDataBuffer = callResult.Output;
previousCallResult = callResult.PrecompileSuccess.HasValue
? (callResult.PrecompileSuccess.Value
? StatusCode.SuccessBytes
: StatusCode.FailureBytes)
: StatusCode.SuccessBytes;
previousCallOutput = callResult.Output.AsSpan().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((long)previousCallOutputDestination,
previousCallOutput);
}
}
if (_txTracer.IsTracingActions)
{
_txTracer.ReportActionEnd(previousState.GasAvailable, _returnDataBuffer);
}
}
if (previousStateSucceeded)
{
previousState.CommitToParent(currentState);
}
}
else
{
worldState.Restore(previousState.Snapshot);
_returnDataBuffer = callResult.Output;
previousCallResult = StatusCode.FailureBytes;
previousCallOutput = callResult.Output.AsSpan().SliceWithZeroPadding(0,
Math.Min(callResult.Output.Length, (int)previousState.OutputLength));
previousCallOutputDestination = (ulong)previousState.OutputDestination;
if (_txTracer.IsTracingActions)
{
_txTracer.ReportActionError(EvmExceptionType.Revert, previousState.GasAvailable);
}
}
previousState.Dispose();
}
catch (Exception ex) when (ex is EvmException || ex is OverflowException)
{
if (_logger.IsTrace)
_logger.Trace(
$"exception ({ex.GetType().Name}) in {currentState.ExecutionType} at depth {currentState.Env.CallDepth} - restoring snapshot");
_worldState.Restore(currentState.Snapshot);
if (_parityTouchBugAccount.ShouldDelete)
{
_state.AddToBalance(_parityTouchBugAccount.Address, UInt256.Zero, spec);
_parityTouchBugAccount.ShouldDelete = false;
}
if (txTracer.IsTracingInstructions)
{
txTracer.ReportOperationError(ex is EvmException evmException
? evmException.ExceptionType
: EvmExceptionType.Other);
txTracer.ReportOperationRemainingGas(0);
}
if (_txTracer.IsTracingActions)
{
EvmException evmException = ex as EvmException;
_txTracer.ReportActionError(evmException?.ExceptionType ?? EvmExceptionType.Other);
}
if (currentState.IsTopLevel)
{
return new TransactionSubstate(
ex is OverflowException ? EvmExceptionType.Other : (ex as EvmException).ExceptionType,
_txTracer != NullTxTracer.Instance);
}
previousCallResult = StatusCode.FailureBytes;
previousCallOutputDestination = UInt256.Zero;
_returnDataBuffer = Array.Empty<byte>();
previousCallOutput = ZeroPaddedSpan.Empty;
currentState.Dispose();
currentState = _stateStack.Pop();
currentState.IsContinuation = true;
}
}
}
public void BuildILForNext() => _buildILForNext = true;
private bool _buildILForNext;
public CodeInfo GetCachedCodeInfo(IWorldState worldState, Address codeSource, IReleaseSpec vmSpec)
{
IStateProvider state = worldState.StateProvider;
if (codeSource.IsPrecompile(vmSpec))
{
if (_precompiles is null)
{
throw new InvalidOperationException("EVM precompile have not been initialized properly.");
}
return _precompiles[codeSource];
}
Keccak codeHash = state.GetCodeHash(codeSource);
CodeInfo cachedCodeInfo = _codeCache.Get(codeHash);
if (cachedCodeInfo == null)
{
byte[] code = state.GetCode(codeHash);
if (code == null)
{
throw new NullReferenceException($"Code {codeHash} missing in the state for address {codeSource}");
}
object? data = null;
// TODO: poor man's algo to select to build
if (_buildILForNext)
{
_buildILForNext = false; // consume
_logger.Info("Emitting a new IL VM");
ILDelegate build = IL.ILVirtualMachineBuilder.Build(code);
data = build;
}
cachedCodeInfo = new CodeInfo(code, data);
_codeCache.Set(codeHash, cachedCodeInfo);
}
else
{
// need to touch code so that any collectors that track database access are informed
state.TouchCode(codeHash);
}
return cachedCodeInfo;
}
public void DisableSimdInstructions()
{
_simdOperationsEnabled = false;
}
private void InitializePrecompiledContracts()
{
_precompiles = new Dictionary<Address, CodeInfo>
{
[EcRecoverPrecompile.Instance.Address] = new(EcRecoverPrecompile.Instance),
[Sha256Precompile.Instance.Address] = new(Sha256Precompile.Instance),
[Ripemd160Precompile.Instance.Address] = new(Ripemd160Precompile.Instance),
[IdentityPrecompile.Instance.Address] = new(IdentityPrecompile.Instance),
[Bn256AddPrecompile.Instance.Address] = new(Bn256AddPrecompile.Instance),
[Bn256MulPrecompile.Instance.Address] = new(Bn256MulPrecompile.Instance),
[Bn256PairingPrecompile.Instance.Address] = new(Bn256PairingPrecompile.Instance),
[ModExpPrecompile.Instance.Address] = new(ModExpPrecompile.Instance),
[Blake2FPrecompile.Instance.Address] = new(Blake2FPrecompile.Instance),
[G1AddPrecompile.Instance.Address] = new(G1AddPrecompile.Instance),
[G1MulPrecompile.Instance.Address] = new(G1MulPrecompile.Instance),
[G1MultiExpPrecompile.Instance.Address] = new(G1MultiExpPrecompile.Instance),
[G2AddPrecompile.Instance.Address] = new(G2AddPrecompile.Instance),
[G2MulPrecompile.Instance.Address] = new(G2MulPrecompile.Instance),
[G2MultiExpPrecompile.Instance.Address] = new(G2MultiExpPrecompile.Instance),
[PairingPrecompile.Instance.Address] = new(PairingPrecompile.Instance),
[MapToG1Precompile.Instance.Address] = new(MapToG1Precompile.Instance),
[MapToG2Precompile.Instance.Address] = new(MapToG2Precompile.Instance),
};
}
private static bool UpdateGas(long gasCost, ref long gasAvailable)
{
// Console.WriteLine($"{gasCost}");
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, IReleaseSpec spec, bool chargeForWarm = true)
{
// Console.WriteLine($"Accessing {address}");
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.WarmUp(address);
}
if (vmState.IsCold(address) && !address.IsPrecompile(spec))
{
result = UpdateGas(GasCostOf.ColdAccountAccess, ref gasAvailable);
vmState.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,
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.WarmUp(storageCell);
}
if (vmState.IsCold(storageCell))
{
result = UpdateGas(GasCostOf.ColdSLoad, ref gasAvailable);
vmState.WarmUp(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 dataGasCost = precompile.DataGasCost(callData, spec);
bool wasCreated = false;
if (!_state.AccountExists(state.Env.ExecutingAccount))
{
wasCreated = true;
_state.CreateAccount(state.Env.ExecutingAccount, transferValue);
}
else
{
_state.AddToBalance(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(dataGasCost, ref gasAvailable)) return CallResult.Exception;
if (!UpdateGas(baseGasCost, ref gasAvailable))
{
Metrics.EvmExceptions++;
throw new OutOfGasException();
}
if (!UpdateGas(dataGasCost, ref gasAvailable))
{
Metrics.EvmExceptions++;
throw new OutOfGasException();
}
state.GasAvailable = gasAvailable;
try
{
(ReadOnlyMemory<byte> output, bool success) = precompile.Run(callData, spec);
CallResult callResult = new(output.ToArray(), success, !success);
return callResult;
}
catch (Exception)
{
CallResult callResult = new(Array.Empty<byte>(), false, true);
return callResult;
}
}
private CallResult ExecuteCall(EvmState vmState, byte[]? previousCallResult, ZeroPaddedSpan previousCallOutput, in UInt256 previousCallOutputDestination, IReleaseSpec spec)
{
if (!vmState.IsContinuation)
{
ExecutionEnvironment env = vmState.Env;
if (!_state.AccountExists(env.ExecutingAccount))
{
_state.CreateAccount(env.ExecutingAccount, env.TransferValue);
}
else
{
_state.AddToBalance(env.ExecutingAccount, env.TransferValue, spec);
}
if (vmState.ExecutionType.IsAnyCreate() && spec.ClearEmptyAccountWhenTouched)
{
_state.IncrementNonce(env.ExecutingAccount);
}
}
if (vmState.Env.CodeInfo.MachineCode.Length == 0)
{
return CallResult.Empty;
}
if (vmState.Env.CodeInfo.Data is ILDelegate @delegate)
{
_logger.Info("Executing as an IL delegate!");
EvmExceptionType evmExceptionType = @delegate(vmState.GasAvailable);
return new CallResult(Array.Empty<byte>(), null, false, evmExceptionType);
}
// fallback to regular evm, if no IL based
return ExecuteMachine(vmState, previousCallResult, previousCallOutput, previousCallOutputDestination, spec);
}
private CallResult ExecuteMachine(EvmState vmState, byte[]? previousCallResult, ZeroPaddedSpan previousCallOutput, UInt256 previousCallOutputDestination, IReleaseSpec spec)
{
bool isTrace = _logger.IsTrace;
bool traceOpcodes = _txTracer.IsTracingInstructions;
ExecutionEnvironment env = vmState.Env;
TxExecutionContext txCtx = env.TxExecutionContext;
vmState.InitStacks();
EvmStack stack = new(vmState.DataStack.AsSpan(), vmState.DataStackHead, _txTracer);
long gasAvailable = vmState.GasAvailable;
int programCounter = vmState.ProgramCounter;
Span<byte> code = env.CodeInfo.MachineCode.AsSpan();
static void UpdateCurrentState(EvmState state, in int pc, in long gas, in int stackHead)
{
state.ProgramCounter = pc;
state.GasAvailable = gas;
state.DataStackHead = stackHead;
}
void StartInstructionTrace(Instruction instruction, EvmStack stackValue)
{
_txTracer.StartOperation(env.CallDepth + 1, gasAvailable, instruction, programCounter);
if (_txTracer.IsTracingMemory)
{
_txTracer.SetOperationMemory(vmState.Memory?.GetTrace() ?? new List<string>());
}
if (_txTracer.IsTracingStack)
{
_txTracer.SetOperationStack(stackValue.GetStackTrace());
}
}
void EndInstructionTrace()
{
if (traceOpcodes)
{
if (_txTracer.IsTracingMemory)
{
_txTracer.SetOperationMemorySize(vmState.Memory?.Size ?? 0);
}
_txTracer.ReportOperationRemainingGas(gasAvailable);
}
}
void EndInstructionTraceError(EvmExceptionType evmExceptionType)
{
if (traceOpcodes)
{
_txTracer.ReportOperationError(evmExceptionType);
_txTracer.ReportOperationRemainingGas(gasAvailable);
}
}
void Jump(in UInt256 jumpDest, bool isSubroutine = false)
{
if (jumpDest > int.MaxValue)
{
Metrics.EvmExceptions++;
EndInstructionTraceError(EvmExceptionType.InvalidJumpDestination);
// https://github.com/NethermindEth/nethermind/issues/140
throw new InvalidJumpDestinationException();
// return CallResult.InvalidJumpDestination; // TODO: add a test, validating inside the condition was not covered by existing tests and fails on 0xf435a354924097686ea88dab3aac1dd464e6a3b387c77aeee94145b0fa5a63d2 mainnet
}
int jumpDestInt = (int)jumpDest;
if (!env.CodeInfo.ValidateJump(jumpDestInt, isSubroutine))
{
EndInstructionTraceError(EvmExceptionType.InvalidJumpDestination);
// https://github.com/NethermindEth/nethermind/issues/140
throw new InvalidJumpDestinationException();
// return CallResult.InvalidJumpDestination; // TODO: add a test, validating inside the condition was not covered by existing tests and fails on 61363 Ropsten
}
programCounter = jumpDestInt;
}
void UpdateMemoryCost(in UInt256 position, in UInt256 length)
{
if (vmState.Memory is null)
{
throw new InvalidOperationException("EVM memory has not been initialized properly.");
}
long memoryCost = vmState.Memory.CalculateMemoryCost(in position, length);
if (memoryCost != 0L)
{
if (!UpdateGas(memoryCost, ref gasAvailable))
{
Metrics.EvmExceptions++;
EndInstructionTraceError(EvmExceptionType.OutOfGas);
throw new OutOfGasException();
}
}
}
if (previousCallResult != null)
{
stack.PushBytes(previousCallResult);
if (_txTracer.IsTracingInstructions) _txTracer.ReportOperationRemainingGas(vmState.GasAvailable);
}
if (previousCallOutput.Length > 0)
{
UInt256 localPreviousDest = previousCallOutputDestination;
UpdateMemoryCost(in localPreviousDest, (ulong)previousCallOutput.Length);
if (vmState.Memory is null)
{
throw new InvalidOperationException("EVM memory has not been initialized properly.");
}
vmState.Memory.Save(in localPreviousDest, previousCallOutput);
// if(_txTracer.IsTracingInstructions) _txTracer.ReportMemoryChange((long)localPreviousDest, previousCallOutput);
}
while (programCounter < code.Length)
{
Instruction instruction = (Instruction)code[programCounter];
// Console.WriteLine(instruction);
if (traceOpcodes)
{
StartInstructionTrace(instruction, stack);
}
programCounter++;
switch (instruction)
{
case Instruction.STOP:
{
UpdateCurrentState(vmState, programCounter, gasAvailable, stack.Head);
EndInstructionTrace();
return CallResult.Empty;
}
case Instruction.ADD:
{
if (!UpdateGas(GasCostOf.VeryLow, ref gasAvailable))
{
EndInstructionTraceError(EvmExceptionType.OutOfGas);
return CallResult.OutOfGasException;
}
stack.PopUInt256(out UInt256 b);
stack.PopUInt256(out UInt256 a);
UInt256.Add(in a, in b, out UInt256 c);
stack.PushUInt256(c);
break;
}
case Instruction.MUL:
{
if (!UpdateGas(GasCostOf.Low, ref gasAvailable))
{
EndInstructionTraceError(EvmExceptionType.OutOfGas);
return CallResult.OutOfGasException;
}
stack.PopUInt256(out UInt256 a);
stack.PopUInt256(out UInt256 b);
UInt256.Multiply(in a, in b, out UInt256 res);
stack.PushUInt256(in res);
break;
}
case Instruction.SUB:
{
if (!UpdateGas(GasCostOf.VeryLow, ref gasAvailable))
{
EndInstructionTraceError(EvmExceptionType.OutOfGas);
return CallResult.OutOfGasException;
}
stack.PopUInt256(out UInt256 a);
stack.PopUInt256(out UInt256 b);
UInt256.Subtract(in a, in b, out UInt256 result);
stack.PushUInt256(in result);
break;
}
case Instruction.DIV:
{
if (!UpdateGas(GasCostOf.Low, ref gasAvailable))
{
EndInstructionTraceError(EvmExceptionType.OutOfGas);
return CallResult.OutOfGasException;
}
stack.PopUInt256(out UInt256 a);
stack.PopUInt256(out UInt256 b);
if (b.IsZero)
{
stack.PushZero();
}
else
{
UInt256.Divide(in a, in b, out UInt256 res);
stack.PushUInt256(in res);
}
break;
}
case Instruction.SDIV:
{
if (!UpdateGas(GasCostOf.Low, ref gasAvailable))
{
EndInstructionTraceError(EvmExceptionType.OutOfGas);
return CallResult.OutOfGasException;
}
stack.PopUInt256(out UInt256 a);
stack.PopSignedInt256(out Int256.Int256 b);
if (b.IsZero)
{
stack.PushZero();
}
else if (b == Int256.Int256.MinusOne && a == P255)
{
UInt256 res = P255;
stack.PushUInt256(in res);
}
else
{
Int256.Int256 signedA = new(a);
Int256.Int256.Divide(in signedA, in b, out Int256.Int256 res);
stack.PushSignedInt256(in res);
}
break;
}
case Instruction.MOD:
{
if (!UpdateGas(GasCostOf.Low, ref gasAvailable))
{
EndInstructionTraceError(EvmExceptionType.OutOfGas);
return CallResult.OutOfGasException;
}
stack.PopUInt256(out UInt256 a);
stack.PopUInt256(out UInt256 b);
UInt256.Mod(in a, in b, out UInt256 result);
stack.PushUInt256(in result);
break;
}
case Instruction.SMOD:
{
if (!UpdateGas(GasCostOf.Low, ref gasAvailable))
{
EndInstructionTraceError(EvmExceptionType.OutOfGas);
return CallResult.OutOfGasException;
}
stack.PopSignedInt256(out Int256.Int256 a);
stack.PopSignedInt256(out Int256.Int256 b);
if (b.IsZero || b.IsOne)
{
stack.PushZero();
}
else
{
a.Abs(out Int256.Int256 absA);
b.Abs(out Int256.Int256 absB);
absA.Mod(in absB, out Int256.Int256 mod);
int sign = a.Sign;
if (sign < 0)
{
mod.Neg(out Int256.Int256 res);
stack.PushSignedInt256(in res);
}
else
{
stack.PushSignedInt256(in mod);
}
}
break;
}
case Instruction.ADDMOD:
{
if (!UpdateGas(GasCostOf.Mid, ref gasAvailable))
{
EndInstructionTraceError(EvmExceptionType.OutOfGas);
return CallResult.OutOfGasException;
}
stack.PopUInt256(out UInt256 a);
stack.PopUInt256(out UInt256 b);
stack.PopUInt256(out UInt256 mod);
if (mod.IsZero)
{
stack.PushZero();
}
else
{
UInt256.AddMod(a, b, mod, out UInt256 res);
stack.PushUInt256(in res);
}
break;
}
case Instruction.MULMOD:
{
if (!UpdateGas(GasCostOf.Mid, ref gasAvailable))
{
EndInstructionTraceError(EvmExceptionType.OutOfGas);
return CallResult.OutOfGasException;
}
stack.PopUInt256(out UInt256 a);
stack.PopUInt256(out UInt256 b);
stack.PopUInt256(out UInt256 mod);
if (mod.IsZero)
{
stack.PushZero();
}
else
{
UInt256.MultiplyMod(in a, in b, in mod, out UInt256 res);
stack.PushUInt256(in res);
}