forked from iotexproject/iotex-core
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathevm.go
More file actions
981 lines (925 loc) · 33.2 KB
/
evm.go
File metadata and controls
981 lines (925 loc) · 33.2 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
// Copyright (c) 2024 IoTeX Foundation
// This source code is provided 'as is' and no warranties are given as to title or non-infringement, merchantability
// or fitness for purpose and, to the extent permitted by law, all liability for your use of the code is disclaimed.
// This source code is governed by Apache License 2.0 that can be found in the LICENSE file.
package evm
import (
"bytes"
"context"
"encoding/hex"
"math"
"math/big"
"time"
erigonstate "github.com/erigontech/erigon/core/state"
"github.com/ethereum/go-ethereum/common"
"github.com/ethereum/go-ethereum/core/tracing"
"github.com/ethereum/go-ethereum/core/types"
"github.com/ethereum/go-ethereum/core/vm"
"github.com/ethereum/go-ethereum/crypto"
"github.com/ethereum/go-ethereum/params"
"github.com/holiman/uint256"
"github.com/pkg/errors"
"go.uber.org/zap"
"google.golang.org/protobuf/proto"
"github.com/iotexproject/go-pkgs/hash"
"github.com/iotexproject/iotex-address/address"
"github.com/iotexproject/iotex-proto/golang/iotextypes"
"github.com/iotexproject/iotex-core/v2/action"
"github.com/iotexproject/iotex-core/v2/action/protocol"
"github.com/iotexproject/iotex-core/v2/blockchain/genesis"
"github.com/iotexproject/iotex-core/v2/pkg/log"
"github.com/iotexproject/iotex-core/v2/pkg/tracer"
"github.com/iotexproject/iotex-core/v2/pkg/util/byteutil"
)
var (
// TODO: whenever ActionGasLimit is removed from genesis, we need to hard code it to 5M to make it compatible with
// the mainnet.
_preAleutianActionGasLimit = genesis.Default.ActionGasLimit
_inContractTransfer = hash.BytesToHash256([]byte{byte(iotextypes.TransactionLogType_IN_CONTRACT_TRANSFER)})
// _revertSelector is a special function selector for revert reason unpacking.
_revertSelector = crypto.Keccak256([]byte("Error(string)"))[:4]
// ErrInconsistentNonce is the error that the nonce is different from executor's nonce
ErrInconsistentNonce = errors.New("Nonce is not identical to executor nonce")
)
type (
// GetBlockHash gets block hash by height
GetBlockHash func(uint64) (hash.Hash256, error)
// GetBlockTime gets block time by height
GetBlockTime func(uint64) (time.Time, error)
)
// CanTransfer checks whether the from account has enough balance
func CanTransfer(db vm.StateDB, fromHash common.Address, balance *uint256.Int) bool {
return db.GetBalance(fromHash).Cmp(balance) >= 0
}
// MakeTransfer transfers account
func MakeTransfer(db vm.StateDB, fromHash, toHash common.Address, amount *uint256.Int) {
db.SubBalance(fromHash, amount, tracing.BalanceChangeUnspecified)
db.AddBalance(toHash, amount, tracing.BalanceChangeUnspecified)
db.AddLog(&types.Log{
Topics: []common.Hash{
common.BytesToHash(_inContractTransfer[:]),
common.BytesToHash(fromHash[:]),
common.BytesToHash(toHash[:]),
},
Data: amount.Bytes(),
})
}
type (
// Params is the context and parameters
Params struct {
context vm.BlockContext
txCtx vm.TxContext
nonce uint64
amount *big.Int
contract *common.Address
gas uint64
data []byte
accessList types.AccessList
authList []types.SetCodeAuthorization
evmConfig vm.Config
chainConfig *params.ChainConfig
genesis genesis.Blockchain
blkCtx protocol.BlockCtx
featureCtx protocol.FeatureCtx
actionCtx protocol.ActionCtx
helperCtx HelperContext
}
stateDB interface {
vm.StateDB
CommitContracts() error
Logs() []*action.Log
TransactionLogs() []*action.TransactionLog
clear()
Error() error
}
)
// newParams creates a new context for use in the EVM.
func newParams(
ctx context.Context,
execution action.TxData,
) (*Params, error) {
var (
actionCtx = protocol.MustGetActionCtx(ctx)
blkCtx = protocol.MustGetBlockCtx(ctx)
featureCtx = protocol.MustGetFeatureCtx(ctx)
g = genesis.MustExtractGenesisContext(ctx)
helperCtx = mustGetHelperCtx(ctx)
evmNetworkID = protocol.MustGetBlockchainCtx(ctx).EvmNetworkID
executorAddr = common.BytesToAddress(actionCtx.Caller.Bytes())
getBlockHash = helperCtx.GetBlockHash
vmConfig vm.Config
getHashFn vm.GetHashFunc
)
gasLimit := execution.Gas()
// Reset gas limit to the system wide action gas limit cap if it's greater than it
if blkCtx.BlockHeight > 0 && featureCtx.SystemWideActionGasLimit && gasLimit > _preAleutianActionGasLimit {
gasLimit = _preAleutianActionGasLimit
}
switch {
case featureCtx.CorrectGetHashFn:
getHashFn = func(n uint64) common.Hash {
hash, err := getBlockHash(n)
if err == nil {
return common.BytesToHash(hash[:])
}
return common.Hash{}
}
case featureCtx.FixGetHashFnHeight:
getHashFn = func(n uint64) common.Hash {
hash, err := getBlockHash(blkCtx.BlockHeight - (n + 1))
if err == nil {
return common.BytesToHash(hash[:])
}
return common.Hash{}
}
default:
getHashFn = func(n uint64) common.Hash {
hash, err := getBlockHash(blkCtx.BlockHeight - n)
if err != nil {
// initial implementation did wrong, should return common.Hash{} in case of error
return common.BytesToHash(hash[:])
}
return common.Hash{}
}
}
context := vm.BlockContext{
CanTransfer: CanTransfer,
Transfer: MakeTransfer,
GetHash: getHashFn,
Coinbase: common.BytesToAddress(blkCtx.Producer.Bytes()),
GasLimit: gasLimit,
BlockNumber: new(big.Int).SetUint64(blkCtx.BlockHeight),
Time: new(big.Int).SetInt64(blkCtx.BlockTimeStamp.Unix()).Uint64(),
Difficulty: new(big.Int).SetUint64(uint64(50)),
BaseFee: new(big.Int),
}
if g.IsSumatra(blkCtx.BlockHeight) {
// Random opcode (EIP-4399) is not supported
context.Random = &common.Hash{}
}
if g.IsVanuatu(blkCtx.BlockHeight) {
// enable BLOBBASEFEE opcode
context.BlobBaseFee = protocol.CalcBlobFee(blkCtx.ExcessBlobGas)
// enable BASEFEE opcode
if blkCtx.BaseFee != nil {
context.BaseFee = new(big.Int).Set(blkCtx.BaseFee)
}
}
if vmCfg, ok := protocol.GetVMConfigCtx(ctx); ok {
vmConfig = vmCfg
}
chainConfig, err := getChainConfig(g.Blockchain, blkCtx.BlockHeight, evmNetworkID, func(height uint64) (*time.Time, error) {
return blockHeightToTime(ctx, height)
})
if err != nil {
return nil, err
}
vmTxCtx := vm.TxContext{
Origin: executorAddr,
GasPrice: execution.GasPrice(),
}
if g.IsVanuatu(blkCtx.BlockHeight) {
// enable BLOBHASH opcode
vmTxCtx.BlobHashes = execution.BlobHashes()
vmTxCtx.BlobFeeCap = execution.BlobGasFeeCap()
}
return &Params{
context,
vmTxCtx,
execution.Nonce(),
execution.Value(),
execution.To(),
gasLimit,
execution.Data(),
execution.AccessList(),
execution.SetCodeAuthorizations(),
vmConfig,
chainConfig,
g.Blockchain,
blkCtx,
featureCtx,
actionCtx,
helperCtx,
}, nil
}
func securityDeposit(ps *Params, stateDB vm.StateDB, gasLimit uint64) error {
executorNonce := stateDB.GetNonce(ps.txCtx.Origin)
if executorNonce > ps.nonce {
log.S().Errorf("Nonce on %v: %d vs %d", ps.txCtx.Origin, executorNonce, ps.nonce)
// TODO ignore inconsistent nonce problem until the actions are executed sequentially
// return ErrInconsistentNonce
}
if gasLimit < ps.gas {
return action.ErrGasLimit
}
gasConsumed := uint256.MustFromBig(new(big.Int).Mul(new(big.Int).SetUint64(ps.gas), ps.txCtx.GasPrice))
if stateDB.GetBalance(ps.txCtx.Origin).Cmp(gasConsumed) < 0 {
return action.ErrInsufficientFunds
}
stateDB.SubBalance(ps.txCtx.Origin, gasConsumed, tracing.BalanceChangeUnspecified)
return nil
}
// DeploySystemContracts deploys system contracts
func DeploySystemContracts(ctx context.Context, sm protocol.StateManager,
addrs []address.Address, codes [][]byte) error {
if len(addrs) != len(codes) {
return errors.Errorf("the length of addresses %d and codes %d are not equal", len(addrs), len(codes))
}
if len(addrs) == 0 {
return nil
}
var stateDB stateDB
stateDB, err := prepareStateDB(ctx, sm)
if err != nil {
return err
}
for i := range addrs {
addr := common.BytesToAddress(addrs[i].Bytes())
stateDB.CreateAccount(addr)
stateDB.CreateContract(addr)
stateDB.SetCode(addr, codes[i])
stateDB.SetNonce(addr, stateDB.GetNonce(addr)+1, tracing.NonceChangeContractCreator)
}
return stateDB.CommitContracts()
}
// HandleSystemContractCall handles system contract call
func HandleSystemContractCall(ctx context.Context, sm protocol.StateManager, execution action.TxData) ([]byte, error) {
var stateDB stateDB
stateDB, err := prepareStateDB(ctx, sm)
if err != nil {
return nil, err
}
params, err := newParams(ctx, execution)
if err != nil {
return nil, err
}
if params.contract == nil {
return nil, errors.New("contract address is nil")
}
evm := vm.NewEVM(params.context, stateDB, params.chainConfig, params.evmConfig)
evm.SetTxContext(params.txCtx)
stateDB.AddAddressToAccessList(*params.contract)
output, _, err := evm.Call(params.txCtx.Origin, *params.contract, params.data, params.gas, uint256.MustFromBig(params.amount))
if err != nil {
return nil, errors.Wrapf(err, "failed to call system contract %s", params.contract.String())
}
stateDB.Finalise(true)
if err := stateDB.CommitContracts(); err != nil {
return nil, errors.Wrap(err, "failed to commit contracts to underlying db")
}
return output, nil
}
// ExecuteContract processes a transfer which contains a contract
func ExecuteContract(
ctx context.Context,
sm protocol.StateManager,
execution action.TxData,
) ([]byte, *action.Receipt, error) {
ctx, span := tracer.NewSpan(ctx, "evm.ExecuteContract")
defer span.End()
var stateDB stateDB
stateDB, err := prepareStateDB(ctx, sm)
if err != nil {
return nil, nil, err
}
ps, err := newParams(ctx, execution)
if err != nil {
return nil, nil, err
}
retval, depositGas, remainingGas, contractAddress, statusCode, err := executeInEVM(ctx, ps, stateDB)
if err != nil {
return nil, nil, err
}
receipt := &action.Receipt{
GasConsumed: ps.gas - remainingGas,
BlockHeight: ps.blkCtx.BlockHeight,
ActionHash: ps.actionCtx.ActionHash,
ContractAddress: contractAddress,
Status: uint64(statusCode),
EffectiveGasPrice: protocol.EffectiveGasPrice(ctx, execution),
Output: retval,
}
var (
depositLog []*action.TransactionLog
burnLog *action.TransactionLog
consumedGas = depositGas - remainingGas
)
if ps.featureCtx.FixDoubleChargeGas {
// Refund all deposit and, actual gas fee will be subtracted when depositing gas fee to the rewarding protocol
stateDB.AddBalance(ps.txCtx.Origin, uint256.MustFromBig(big.NewInt(0).Mul(big.NewInt(0).SetUint64(depositGas), ps.txCtx.GasPrice)), tracing.BalanceChangeUnspecified)
} else {
if remainingGas > 0 {
remainingValue := new(big.Int).Mul(new(big.Int).SetUint64(remainingGas), ps.txCtx.GasPrice)
stateDB.AddBalance(ps.txCtx.Origin, uint256.MustFromBig(remainingValue), tracing.BalanceChangeUnspecified)
}
if consumedGas > 0 {
burnLog = &action.TransactionLog{
Type: iotextypes.TransactionLogType_GAS_FEE,
Sender: ps.actionCtx.Caller.String(),
Recipient: "", // burned
Amount: new(big.Int).Mul(new(big.Int).SetUint64(consumedGas), ps.txCtx.GasPrice),
}
}
}
if consumedGas > 0 {
priorityFee, baseFee, err := protocol.SplitGas(ctx, execution, consumedGas)
if err != nil {
return nil, nil, errors.Wrapf(err, "failed to split gas")
}
depositLog, err = ps.helperCtx.DepositGasFunc(ctx, sm, baseFee, protocol.PriorityFeeOption(priorityFee))
if err != nil {
return nil, nil, err
}
}
if err := stateDB.CommitContracts(); err != nil {
return nil, nil, errors.Wrap(err, "failed to commit contracts to underlying db")
}
receipt.AddLogs(stateDB.Logs()...).AddTransactionLogs(depositLog...)
receipt.AddTransactionLogs(burnLog)
if receipt.Status == uint64(iotextypes.ReceiptStatus_Success) ||
ps.featureCtx.AddOutOfGasToTransactionLog && receipt.Status == uint64(iotextypes.ReceiptStatus_ErrCodeStoreOutOfGas) {
receipt.AddTransactionLogs(stateDB.TransactionLogs()...)
}
stateDB.clear()
if ps.featureCtx.SetRevertMessageToReceipt && receipt.Status == uint64(iotextypes.ReceiptStatus_ErrExecutionReverted) && len(retval) >= 4 && bytes.Equal(retval[:4], _revertSelector) {
// in case of the execution revert error, parse the retVal and add to receipt
receipt.SetExecutionRevertMsg(ExtractRevertMessage(retval))
}
return retval, receipt, nil
}
// ReadContractStorage reads contract's storage
func ReadContractStorage(
ctx context.Context,
sm protocol.StateManager,
contract address.Address,
key []byte,
) ([]byte, error) {
bcCtx := protocol.MustGetBlockchainCtx(ctx)
ctx = protocol.WithFeatureCtx(protocol.WithBlockCtx(protocol.WithActionCtx(ctx,
protocol.ActionCtx{
ActionHash: hash.ZeroHash256,
}),
protocol.BlockCtx{
BlockHeight: bcCtx.Tip.Height + 1,
},
))
var stateDB stateDB
stateDB, err := prepareStateDBAdapter(ctx, sm)
if err != nil {
return nil, err
}
if erigonsm, ok := sm.(interface {
Erigon() (*erigonstate.IntraBlockState, bool)
}); ok {
if in, dryrun := erigonsm.Erigon(); in != nil {
if !dryrun {
log.S().Panic("should not happen, use dryrun instead")
}
stateDB = NewErigonStateDBAdapterDryrun(stateDB.(*StateDBAdapter), in)
}
}
res := stateDB.GetState(common.BytesToAddress(contract.Bytes()), common.BytesToHash(key))
return res[:], nil
}
// ReadContractCode reads contract's code
func ReadContractCode(
ctx context.Context,
sm protocol.StateManager,
contract address.Address,
) ([]byte, error) {
bcCtx := protocol.MustGetBlockchainCtx(ctx)
ctx = protocol.WithFeatureCtx(protocol.WithBlockCtx(protocol.WithActionCtx(ctx,
protocol.ActionCtx{
ActionHash: hash.ZeroHash256,
}),
protocol.BlockCtx{
BlockHeight: bcCtx.Tip.Height + 1,
},
))
var stateDB stateDB
stateDB, err := prepareSimulateStateDB(ctx, sm)
if err != nil {
return nil, err
}
code := stateDB.GetCode(common.BytesToAddress(contract.Bytes()))
return code, nil
}
func prepareSimulateStateDB(ctx context.Context, sm protocol.StateManager) (stateDB, error) {
var stateDB stateDB
stateDB, err := prepareStateDBAdapter(ctx, sm)
if err != nil {
return nil, err
}
if erigonsm, ok := sm.(interface {
Erigon() (*erigonstate.IntraBlockState, bool)
}); ok {
if in, dryrun := erigonsm.Erigon(); in != nil {
if !dryrun {
log.S().Panic("should not happen, use dryrun instead")
}
stateDB = NewErigonStateDBAdapterDryrun(stateDB.(*StateDBAdapter), in)
}
}
return stateDB, nil
}
func prepareStateDB(ctx context.Context, sm protocol.StateManager) (stateDB, error) {
var stateDB stateDB
stateDB, err := prepareStateDBAdapter(ctx, sm)
if err != nil {
return nil, err
}
if erigonsm, ok := sm.(interface {
Erigon() (*erigonstate.IntraBlockState, bool)
}); ok {
if in, dryrun := erigonsm.Erigon(); in != nil {
if dryrun {
stateDB = NewErigonStateDBAdapterDryrun(stateDB.(*StateDBAdapter), in)
} else {
stateDB = NewErigonStateDBAdapter(stateDB.(*StateDBAdapter), in)
}
}
}
return stateDB, nil
}
func prepareStateDBAdapter(ctx context.Context, sm protocol.StateManager) (*StateDBAdapter, error) {
var (
actionCtx = protocol.MustGetActionCtx(ctx)
blkCtx = protocol.MustGetBlockCtx(ctx)
featureCtx = protocol.MustGetFeatureCtx(ctx)
opts = []StateDBAdapterOption{}
)
if featureCtx.CreateLegacyNonceAccount {
opts = append(opts, LegacyNonceAccountOption())
}
if !featureCtx.FixSortCacheContractsAndUsePendingNonce {
opts = append(opts, DisableSortCachedContractsOption(), UseConfirmedNonceOption())
}
// Before featureCtx.RefactorFreshAccountConversion is activated,
// the type of a legacy fresh account is always 1
if featureCtx.RefactorFreshAccountConversion {
opts = append(opts, ZeroNonceForFreshAccountOption())
}
if featureCtx.NotFixTopicCopyBug {
opts = append(opts, NotFixTopicCopyBugOption())
}
if featureCtx.AsyncContractTrie {
opts = append(opts, AsyncContractTrieOption())
}
if featureCtx.FixSnapshotOrder {
opts = append(opts, FixSnapshotOrderOption())
}
if featureCtx.RevertLog {
opts = append(opts, RevertLogOption())
}
if !featureCtx.CorrectGasRefund {
opts = append(opts, ManualCorrectGasRefundOption())
}
if featureCtx.SuicideTxLogMismatchPanic {
opts = append(opts, SuicideTxLogMismatchPanicOption())
}
if featureCtx.PanicUnrecoverableError {
opts = append(opts, PanicUnrecoverableErrorOption())
}
if featureCtx.EnableCancunEVM {
opts = append(opts, EnableCancunEVMOption())
}
if featureCtx.FixRevertSnapshot || actionCtx.ReadOnly {
opts = append(opts, FixRevertSnapshotOption())
opts = append(opts, WithContext(ctx))
}
if featureCtx.PrePectraEVM {
opts = append(opts, IgnoreBalanceChangeTouchAccountOption())
}
return NewStateDBAdapter(
sm,
blkCtx.BlockHeight,
actionCtx.ActionHash,
opts...,
)
}
func getChainConfig(g genesis.Blockchain, height uint64, id uint32, getBlockTime func(uint64) (*time.Time, error)) (*params.ChainConfig, error) {
var chainConfig params.ChainConfig
chainConfig.ConstantinopleBlock = new(big.Int).SetUint64(0) // Constantinople switch block (nil = no fork, 0 = already activated)
chainConfig.BeringBlock = new(big.Int).SetUint64(g.BeringBlockHeight)
// enable earlier Ethereum forks at Greenland
chainConfig.GreenlandBlock = new(big.Int).SetUint64(g.GreenlandBlockHeight)
// support chainid and enable Istanbul + MuirGlacier at Iceland
chainConfig.IstanbulBlock = new(big.Int).SetUint64(g.IcelandBlockHeight)
chainConfig.MuirGlacierBlock = new(big.Int).SetUint64(g.IcelandBlockHeight)
if g.IsIceland(height) {
chainConfig.ChainID = new(big.Int).SetUint64(uint64(id))
}
// enable Berlin and London at Okhotsk
chainConfig.BerlinBlock = new(big.Int).SetUint64(g.OkhotskBlockHeight)
chainConfig.LondonBlock = new(big.Int).SetUint64(g.OkhotskBlockHeight)
// enable ArrowGlacier, GrayGlacier at Redsea
chainConfig.ArrowGlacierBlock = new(big.Int).SetUint64(g.RedseaBlockHeight)
chainConfig.GrayGlacierBlock = new(big.Int).SetUint64(g.RedseaBlockHeight)
// enable Merge, Shanghai at Sumatra
chainConfig.MergeNetsplitBlock = new(big.Int).SetUint64(g.SumatraBlockHeight)
// Starting Shanghai, fork scheduling on Ethereum was switched from blocks to timestamps
sumatraTime, err := getBlockTime(g.SumatraBlockHeight)
if err != nil {
return nil, err
} else if sumatraTime != nil {
sumatraTimestamp := (uint64)(sumatraTime.Unix())
chainConfig.ShanghaiTime = &sumatraTimestamp
}
// enable Cancun at Vanuatu
cancunTime, err := getBlockTime(g.VanuatuBlockHeight)
if err != nil {
return nil, err
} else if cancunTime != nil {
cancunTimestamp := (uint64)(cancunTime.Unix())
chainConfig.CancunTime = &cancunTimestamp
}
// enable Prague
pragueTime, err := getBlockTime(g.ToBeEnabledBlockHeight)
if err != nil {
return nil, err
} else if pragueTime != nil {
pragueTimestamp := (uint64)(pragueTime.Unix())
chainConfig.PragueTime = &pragueTimestamp
}
return &chainConfig, nil
}
// blockHeightToTime returns the block time by height
// if height is greater than current block height, return nil
// if height is equal to current block height, return current block time
// otherwise, return a fake time less than current block time
func blockHeightToTime(ctx context.Context, height uint64) (*time.Time, error) {
blkCtx := protocol.MustGetBlockCtx(ctx)
if height > blkCtx.BlockHeight {
return nil, nil
}
if height == blkCtx.BlockHeight {
return &blkCtx.BlockTimeStamp, nil
}
t := blkCtx.BlockTimeStamp.Add(time.Duration(height-blkCtx.BlockHeight) * time.Second)
return &t, nil
}
// Error in executeInEVM is a consensus issue
func executeInEVM(ctx context.Context, evmParams *Params, stateDB stateDB) ([]byte, uint64, uint64, string, iotextypes.ReceiptStatus, error) {
var (
gasLimit = evmParams.blkCtx.GasLimit
blockHeight = evmParams.blkCtx.BlockHeight
g = evmParams.genesis
remainingGas = evmParams.gas
chainConfig = evmParams.chainConfig
)
if err := securityDeposit(evmParams, stateDB, gasLimit); err != nil {
log.T(ctx).Warn("unexpected error: not enough security deposit", zap.Error(err))
return nil, 0, 0, action.EmptyAddress, iotextypes.ReceiptStatus_Failure, err
}
var (
accessList types.AccessList
floorDataGas uint64
)
evm := vm.NewEVM(evmParams.context, stateDB, chainConfig, evmParams.evmConfig)
evm.SetTxContext(evmParams.txCtx)
if g.IsOkhotsk(blockHeight) {
accessList = evmParams.accessList
}
traceGasChange := func(old, new uint64, reason tracing.GasChangeReason) {
if t := evm.Config.Tracer; t != nil && t.OnGasChange != nil {
t.OnGasChange(old, new, reason)
}
}
intriGas, err := intrinsicGas(uint64(len(evmParams.data)), accessList, evmParams.authList)
if err != nil {
return nil, evmParams.gas, remainingGas, action.EmptyAddress, iotextypes.ReceiptStatus_Failure, err
}
if remainingGas < intriGas {
return nil, evmParams.gas, remainingGas, action.EmptyAddress, iotextypes.ReceiptStatus_Failure, action.ErrInsufficientFunds
}
traceGasChange(remainingGas, remainingGas-intriGas, tracing.GasChangeTxIntrinsicGas)
remainingGas -= intriGas
// Set up the initial access list
rules := chainConfig.Rules(evm.Context.BlockNumber, g.IsSumatra(evmParams.blkCtx.BlockHeight), evmParams.context.Time)
if rules.IsBerlin {
stateDB.Prepare(rules, evmParams.txCtx.Origin, evmParams.context.Coinbase, evmParams.contract, vm.ActivePrecompiles(rules), evmParams.accessList)
}
if rules.IsPrague {
floorDataGas, err = action.FloorDataGas(evmParams.data)
if err != nil {
return nil, evmParams.gas, remainingGas, action.EmptyAddress, iotextypes.ReceiptStatus_Failure, err
}
if evmParams.gas < floorDataGas {
return nil, evmParams.gas, remainingGas, action.EmptyAddress, iotextypes.ReceiptStatus_Failure, errors.Wrapf(action.ErrFloorDataGas, "have %d, want %d", evmParams.gas, floorDataGas)
}
}
var (
contractRawAddress = action.EmptyAddress
executor = evmParams.txCtx.Origin
ret []byte
evmErr error
refund uint64
amount = uint256.MustFromBig(evmParams.amount)
)
if evmParams.contract == nil {
// create contract
var evmContractAddress common.Address
var createRet []byte
createRet, evmContractAddress, remainingGas, evmErr = evm.Create(executor, evmParams.data, remainingGas, amount)
log.T(ctx).Debug("evm Create.", log.Hex("addrHash", evmContractAddress[:]))
if evmErr == nil {
if contractAddress, err := address.FromBytes(evmContractAddress.Bytes()); err == nil {
contractRawAddress = contractAddress.String()
}
}
// ret updates may need hard fork
// so we change it only when readonly mode now
if evmParams.actionCtx.ReadOnly {
ret = createRet
}
} else {
stateDB.SetNonce(evmParams.txCtx.Origin, stateDB.GetNonce(evmParams.txCtx.Origin)+1, tracing.NonceChangeUnspecified)
// Apply EIP-7702 authorizations.
for _, auth := range evmParams.authList {
// Note errors are ignored, we simply skip invalid authorizations here.
if err := applyAuthorization(evm, stateDB, &auth); err != nil {
log.T(ctx).Debug("failed to apply authorization", zap.Error(err), zap.String("auth", auth.Address.String()))
}
}
// Perform convenience warming of sender's delegation target. Although the
// sender is already warmed in Prepare(..), it's possible a delegation to
// the account was deployed during this transaction. To handle correctly,
// simply wait until the final state of delegations is determined before
// performing the resolution and warming.
if addr, ok := types.ParseDelegation(stateDB.GetCode(*evmParams.contract)); ok {
stateDB.AddAddressToAccessList(addr)
}
// process contract
ret, remainingGas, evmErr = evm.Call(executor, *evmParams.contract, evmParams.data, remainingGas, amount)
}
if evmErr != nil {
log.T(ctx).Debug("evm error", zap.Error(evmErr))
// The only possible consensus-error would be if there wasn't
// sufficient balance to make the transfer happen.
// Should be a hard fork (Bering)
if evmErr == vm.ErrInsufficientBalance && g.IsBering(blockHeight) {
return nil, evmParams.gas, remainingGas, action.EmptyAddress, iotextypes.ReceiptStatus_Failure, evmErr
}
}
if stateDB.Error() != nil {
log.T(ctx).Debug("statedb error", zap.Error(stateDB.Error()))
}
if !rules.IsLondon {
// Before EIP-3529: refunds were capped to gasUsed / 2
refund = (evmParams.gas - remainingGas) / params.RefundQuotient
} else {
// After EIP-3529: refunds are capped to gasUsed / 5
refund = (evmParams.gas - remainingGas) / params.RefundQuotientEIP3529
}
// before London EVM activation (at Okhotsk height), in certain cases dynamicGas
// has caused gas refund to change, which needs to be manually adjusted after
// the tx is reverted. After Okhotsk height, it is fixed inside RevertToSnapshot()
var (
deltaRefundByDynamicGas = evm.DeltaRefundByDynamicGas
featureCtx = evmParams.featureCtx
)
if !featureCtx.CorrectGasRefund && deltaRefundByDynamicGas != 0 {
if deltaRefundByDynamicGas > 0 {
stateDB.SubRefund(uint64(deltaRefundByDynamicGas))
} else {
stateDB.AddRefund(uint64(-deltaRefundByDynamicGas))
}
}
if refund > stateDB.GetRefund() {
refund = stateDB.GetRefund()
}
remainingGas += refund
traceGasChange(remainingGas-refund, remainingGas, tracing.GasChangeTxRefunds)
if rules.IsPrague {
// After EIP-7623: Data-heavy transactions pay the floor gas.
gasUsed := evmParams.gas - remainingGas
if gasUsed < floorDataGas {
prev := remainingGas
remainingGas = evmParams.gas - floorDataGas
traceGasChange(prev, remainingGas, tracing.GasChangeTxDataFloor)
}
}
errCode := iotextypes.ReceiptStatus_Success
if evmErr != nil {
errCode = evmErrToErrStatusCode(evmErr, g, blockHeight)
if errCode == iotextypes.ReceiptStatus_ErrUnknown {
var addr string
if evmParams.contract != nil {
ioAddr, _ := address.FromBytes((*evmParams.contract)[:])
addr = ioAddr.String()
} else {
addr = "contract creation"
}
log.T(ctx).Warn("evm internal error", zap.Error(evmErr),
zap.String("address", addr),
log.Hex("calldata", evmParams.data))
}
}
return ret, evmParams.gas, remainingGas, contractRawAddress, errCode, nil
}
// evmErrToErrStatusCode returns ReceiptStatuscode which describes error type
func evmErrToErrStatusCode(evmErr error, g genesis.Blockchain, height uint64) iotextypes.ReceiptStatus {
// specific error starting London
if g.IsOkhotsk(height) {
if errors.Is(evmErr, vm.ErrInvalidCode) {
return iotextypes.ReceiptStatus_ErrInvalidCode
}
}
// specific error starting Jutland
if g.IsJutland(height) {
switch {
case errors.Is(evmErr, vm.ErrInsufficientBalance):
return iotextypes.ReceiptStatus_ErrInsufficientBalance
case errors.Is(evmErr, vm.ErrInvalidJump):
return iotextypes.ReceiptStatus_ErrInvalidJump
case errors.Is(evmErr, vm.ErrReturnDataOutOfBounds):
return iotextypes.ReceiptStatus_ErrReturnDataOutOfBounds
case errors.Is(evmErr, vm.ErrGasUintOverflow):
return iotextypes.ReceiptStatus_ErrGasUintOverflow
}
}
// specific error starting Bering
if g.IsBering(height) {
switch {
// the evm error may be wrapped by fmt.Errorf("%w: ..."), so we use errors.Is to check
case errors.Is(evmErr, vm.ErrOutOfGas):
return iotextypes.ReceiptStatus_ErrOutOfGas
case errors.Is(evmErr, vm.ErrCodeStoreOutOfGas):
return iotextypes.ReceiptStatus_ErrCodeStoreOutOfGas
case errors.Is(evmErr, vm.ErrDepth):
return iotextypes.ReceiptStatus_ErrDepth
case errors.Is(evmErr, vm.ErrContractAddressCollision):
return iotextypes.ReceiptStatus_ErrContractAddressCollision
case errors.Is(evmErr, vm.ErrExecutionReverted):
return iotextypes.ReceiptStatus_ErrExecutionReverted
case errors.Is(evmErr, vm.ErrMaxCodeSizeExceeded):
return iotextypes.ReceiptStatus_ErrMaxCodeSizeExceeded
case errors.Is(evmErr, vm.ErrWriteProtection):
return iotextypes.ReceiptStatus_ErrWriteProtection
default:
// internal errors from go-ethereum are not directly accessible
switch evmErr.Error() {
case "no compatible interpreter":
return iotextypes.ReceiptStatus_ErrNoCompatibleInterpreter
default:
return iotextypes.ReceiptStatus_ErrUnknown
}
}
}
// before Bering height, return one common failure
return iotextypes.ReceiptStatus_Failure
}
// intrinsicGas returns the intrinsic gas of an execution
func intrinsicGas(size uint64, list types.AccessList, authList []types.SetCodeAuthorization) (uint64, error) {
if action.ExecutionDataGas == 0 {
panic("payload gas price cannot be zero")
}
var accessListGas uint64
if len(list) > 0 {
accessListGas = uint64(len(list)) * action.TxAccessListAddressGas
accessListGas += uint64(list.StorageKeys()) * action.TxAccessListStorageKeyGas
}
if (math.MaxInt64-action.ExecutionBaseIntrinsicGas-accessListGas)/action.ExecutionDataGas < size {
return 0, action.ErrInsufficientFunds
}
var authListGas uint64
if len(authList) > 0 {
authListGas = uint64(len(authList)) * action.CallNewAccountGas
}
log.L().Debug("Intrinsic Gas Calculation", zap.Uint64("sizeGas", size*action.ExecutionDataGas),
zap.Uint64("baseGas", action.ExecutionBaseIntrinsicGas),
zap.Uint64("accessListGas", accessListGas),
zap.Uint64("authListGas", authListGas))
return size*action.ExecutionDataGas + action.ExecutionBaseIntrinsicGas + accessListGas + authListGas, nil
}
// SimulateExecution simulates the execution in evm
func SimulateExecution(
ctx context.Context,
sm protocol.StateManager,
caller address.Address,
ex action.TxDataForSimulation,
opts ...protocol.SimulateOption,
) ([]byte, *action.Receipt, error) {
ctx, span := tracer.NewSpan(ctx, "evm.SimulateExecution")
defer span.End()
if err := ex.SanityCheck(); err != nil {
return nil, nil, err
}
bcCtx := protocol.MustGetBlockchainCtx(ctx)
g := genesis.MustExtractGenesisContext(ctx)
ctx = protocol.WithActionCtx(
ctx,
protocol.ActionCtx{
Caller: caller,
ActionHash: hash.Hash256b(byteutil.Must(proto.Marshal(ex.Proto()))),
ReadOnly: true,
},
)
zeroAddr, err := address.FromString(address.ZeroAddress)
if err != nil {
return nil, nil, err
}
cfg := &protocol.SimulateOptionConfig{}
for _, opt := range opts {
opt(cfg)
}
if cfg.PreOpt != nil {
if err := cfg.PreOpt(sm); err != nil {
return nil, nil, err
}
}
ctx = protocol.WithFeatureCtx(protocol.WithBlockCtx(
ctx,
protocol.BlockCtx{
BlockHeight: bcCtx.Tip.Height + 1,
BlockTimeStamp: bcCtx.Tip.Timestamp.Add(g.BlockInterval),
GasLimit: g.BlockGasLimitByHeight(bcCtx.Tip.Height + 1),
Producer: zeroAddr,
BaseFee: protocol.CalcBaseFee(g.Blockchain, &bcCtx.Tip),
ExcessBlobGas: protocol.CalcExcessBlobGas(bcCtx.Tip.ExcessBlobGas, bcCtx.Tip.BlobGasUsed),
},
))
var (
retval []byte
receipt *action.Receipt
)
tErr := TraceStart(ctx, sm, ex)
if tErr != nil {
log.L().Warn("failed to start trace for simulation", zap.Error(tErr))
}
defer func() {
if tErr == nil {
TraceEnd(ctx, receipt)
}
if tCtx, ok := GetTracerCtx(ctx); ok && tCtx.CaptureTx != nil {
tCtx.CaptureTx(retval, receipt)
}
}()
retval, receipt, err = ExecuteContract(ctx, sm, ex)
return retval, receipt, err
}
// ExtractRevertMessage extracts the revert message from the return value
func ExtractRevertMessage(ret []byte) string {
if len(ret) < 4 {
return hex.EncodeToString(ret)
}
if !bytes.Equal(ret[:4], _revertSelector) {
return hex.EncodeToString(ret)
}
data := ret[4:]
msgLength := byteutil.BytesToUint64BigEndian(data[56:64])
revertMsg := string(data[64 : 64+msgLength])
return revertMsg
}
func validateAuthorization(evm *vm.EVM, sdb stateDB, auth *types.SetCodeAuthorization) (authority common.Address, err error) {
chainID := evm.ChainConfig().ChainID.Uint64()
// Verify chain ID is 0 or equal to current chain ID.
if !auth.ChainID.IsZero() && chainID != (auth.ChainID.Uint64()) {
return authority, errors.Errorf("authorization chain ID %v does not match current chain ID %v", auth.ChainID, chainID)
}
// Limit nonce to 2^64-1 per EIP-2681.
if auth.Nonce+1 < auth.Nonce {
return authority, errors.Errorf("authorization nonce %d exceeds maximum value", auth.Nonce)
}
// Validate signature values and recover authority.
authority, err = auth.Authority()
if err != nil {
return authority, errors.Wrap(err, "failed to recover authority from authorization")
}
// Check the authority account
// 1) doesn't have code or has exisiting delegation
// 2) matches the auth's nonce
//
// Note it is added to the access list even if the authorization is invalid.
sdb.AddAddressToAccessList(authority)
code := sdb.GetCode(authority)
if _, ok := types.ParseDelegation(code); len(code) != 0 && !ok {
return authority, errors.Errorf("authorization destination %s has code", authority.String())
}
if have := sdb.GetNonce(authority); have != auth.Nonce {
return authority, errors.Errorf("authorization nonce %d does not match account %s nonce %d", auth.Nonce, authority.String(), have)
}
return authority, nil
}
func applyAuthorization(evm *vm.EVM, sdb stateDB, auth *types.SetCodeAuthorization) error {
authority, err := validateAuthorization(evm, sdb, auth)
if err != nil {
return err
}
// If the account already exists in state, refund the new account cost
// charged in the intrinsic calculation.
if sdb.Exist(authority) {
log.L().Debug("EVM Authorization Refund", zap.Uint64("refund", action.CallNewAccountGas-action.TxAuthTupleGas))
sdb.AddRefund(action.CallNewAccountGas - action.TxAuthTupleGas)
}
// Update nonce and account code.
sdb.SetNonce(authority, auth.Nonce+1, tracing.NonceChangeAuthorization)
if auth.Address == (common.Address{}) {
// Delegation to zero address means clear.
sdb.SetCode(authority, nil)
return nil
}
// Otherwise install delegation to auth.Address.
sdb.SetCode(authority, types.AddressToDelegation(auth.Address))
return nil
}