forked from ava-labs/coreth
-
Notifications
You must be signed in to change notification settings - Fork 0
/
vm.go
1551 lines (1375 loc) · 52.6 KB
/
vm.go
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
// (c) 2019-2020, Ava Labs, Inc. All rights reserved.
// See the file LICENSE for licensing terms.
package evm
import (
"context"
"encoding/binary"
"encoding/json"
"errors"
"fmt"
"math/big"
"os"
"path/filepath"
"sort"
"strings"
"sync"
"time"
"github.com/haowang0402/coreth/plugin/evm/message"
avalanchegoMetrics "github.com/haowang0402/avalanchego/api/metrics"
coreth "github.com/haowang0402/coreth/chain"
"github.com/haowang0402/coreth/consensus/dummy"
"github.com/haowang0402/coreth/core"
"github.com/haowang0402/coreth/core/state"
"github.com/haowang0402/coreth/core/types"
"github.com/haowang0402/coreth/eth/ethconfig"
corethPrometheus "github.com/haowang0402/coreth/metrics/prometheus"
"github.com/haowang0402/coreth/node"
"github.com/haowang0402/coreth/params"
"github.com/haowang0402/coreth/peer"
"github.com/haowang0402/coreth/rpc"
"github.com/prometheus/client_golang/prometheus"
// Force-load tracer engine to trigger registration
//
// We must import this package (not referenced elsewhere) so that the native "callTracer"
// is added to a map of client-accessible tracers. In geth, this is done
// inside of cmd/geth.
_ "github.com/haowang0402/coreth/eth/tracers/js"
_ "github.com/haowang0402/coreth/eth/tracers/native"
"github.com/ethereum/go-ethereum/common"
"github.com/ethereum/go-ethereum/log"
"github.com/ethereum/go-ethereum/metrics"
"github.com/ethereum/go-ethereum/rlp"
avalancheRPC "github.com/gorilla/rpc/v2"
"github.com/haowang0402/avalanchego/cache"
"github.com/haowang0402/avalanchego/codec"
"github.com/haowang0402/avalanchego/codec/linearcodec"
"github.com/haowang0402/avalanchego/database"
"github.com/haowang0402/avalanchego/database/manager"
"github.com/haowang0402/avalanchego/database/prefixdb"
"github.com/haowang0402/avalanchego/database/versiondb"
"github.com/haowang0402/avalanchego/ids"
"github.com/haowang0402/avalanchego/snow"
"github.com/haowang0402/avalanchego/snow/choices"
"github.com/haowang0402/avalanchego/snow/consensus/snowman"
"github.com/haowang0402/avalanchego/snow/engine/snowman/block"
"github.com/haowang0402/avalanchego/utils/constants"
"github.com/haowang0402/avalanchego/utils/crypto"
"github.com/haowang0402/avalanchego/utils/formatting"
"github.com/haowang0402/avalanchego/utils/logging"
"github.com/haowang0402/avalanchego/utils/math"
"github.com/haowang0402/avalanchego/utils/perms"
"github.com/haowang0402/avalanchego/utils/profiler"
"github.com/haowang0402/avalanchego/utils/timer/mockable"
"github.com/haowang0402/avalanchego/vms/components/avax"
"github.com/haowang0402/avalanchego/vms/components/chain"
"github.com/haowang0402/avalanchego/vms/secp256k1fx"
commonEng "github.com/haowang0402/avalanchego/snow/engine/common"
avalancheJSON "github.com/haowang0402/avalanchego/utils/json"
)
const (
x2cRateInt64 int64 = 1_000_000_000
x2cRateMinus1Int64 int64 = x2cRateInt64 - 1
// Prefixes for metrics gatherers
ethMetricsPrefix = "eth"
chainStateMetricsPrefix = "chain_state"
)
var (
// x2cRate is the conversion rate between the smallest denomination on the X-Chain
// 1 nAVAX and the smallest denomination on the C-Chain 1 wei. Where 1 nAVAX = 1 gWei.
// This is only required for AVAX because the denomination of 1 AVAX is 9 decimal
// places on the X and P chains, but is 18 decimal places within the EVM.
x2cRate = big.NewInt(x2cRateInt64)
x2cRateMinus1 = big.NewInt(x2cRateMinus1Int64)
_ block.ChainVM = &VM{}
_ block.HeightIndexedChainVM = &VM{}
)
const (
// Max time from current time allowed for blocks, before they're considered future blocks
// and fail verification
maxFutureBlockTime = 10 * time.Second
maxUTXOsToFetch = 1024
defaultMempoolSize = 4096
codecVersion = uint16(0)
secpFactoryCacheSize = 1024
decidedCacheSize = 100
missingCacheSize = 50
unverifiedCacheSize = 50
)
// Define the API endpoints for the VM
const (
avaxEndpoint = "/avax"
adminEndpoint = "/admin"
ethRPCEndpoint = "/rpc"
ethWSEndpoint = "/ws"
)
var (
// Set last accepted key to be longer than the keys used to store accepted block IDs.
lastAcceptedKey = []byte("last_accepted_key")
acceptedPrefix = []byte("snowman_accepted")
ethDBPrefix = []byte("ethdb")
// Prefixes for atomic trie
atomicTrieDBPrefix = []byte("atomicTrieDB")
atomicTrieMetaDBPrefix = []byte("atomicTrieMetaDB")
// Prefixes for pruning
pruneRejectedBlocksKey = []byte("pruned_rejected_blocks")
)
var (
errEmptyBlock = errors.New("empty block")
errUnsupportedFXs = errors.New("unsupported feature extensions")
errInvalidBlock = errors.New("invalid block")
errInvalidAddr = errors.New("invalid hex address")
errInsufficientAtomicTxFee = errors.New("atomic tx fee too low for atomic mempool")
errAssetIDMismatch = errors.New("asset IDs in the input don't match the utxo")
errNoImportInputs = errors.New("tx has no imported inputs")
errInputsNotSortedUnique = errors.New("inputs not sorted and unique")
errPublicKeySignatureMismatch = errors.New("signature doesn't match public key")
errWrongChainID = errors.New("tx has wrong chain ID")
errInsufficientFunds = errors.New("insufficient funds")
errNoExportOutputs = errors.New("tx has no export outputs")
errOutputsNotSorted = errors.New("tx outputs not sorted")
errOutputsNotSortedUnique = errors.New("outputs not sorted and unique")
errOverflowExport = errors.New("overflow when computing export amount + txFee")
errInvalidNonce = errors.New("invalid nonce")
errConflictingAtomicInputs = errors.New("invalid block due to conflicting atomic inputs")
errUnclesUnsupported = errors.New("uncles unsupported")
errTxHashMismatch = errors.New("txs hash does not match header")
errUncleHashMismatch = errors.New("uncle hash mismatch")
errRejectedParent = errors.New("rejected parent")
errInvalidDifficulty = errors.New("invalid difficulty")
errInvalidBlockVersion = errors.New("invalid block version")
errInvalidMixDigest = errors.New("invalid mix digest")
errInvalidExtDataHash = errors.New("invalid extra data hash")
errHeaderExtraDataTooBig = errors.New("header extra data too big")
errInsufficientFundsForFee = errors.New("insufficient AVAX funds to pay transaction fee")
errNoEVMOutputs = errors.New("tx has no EVM outputs")
errNilBaseFeeApricotPhase3 = errors.New("nil base fee is invalid after apricotPhase3")
errNilExtDataGasUsedApricotPhase4 = errors.New("nil extDataGasUsed is invalid after apricotPhase4")
errNilBlockGasCostApricotPhase4 = errors.New("nil blockGasCost is invalid after apricotPhase4")
errConflictingAtomicTx = errors.New("conflicting atomic tx present")
errTooManyAtomicTx = errors.New("too many atomic tx")
errMissingAtomicTxs = errors.New("cannot build a block with non-empty extra data and zero atomic transactions")
)
var originalStderr *os.File
func init() {
// Preserve [os.Stderr] prior to the call in plugin/main.go to plugin.Serve(...).
// Preserving the log level allows us to update the root handler while writing to the original
// [os.Stderr] that is being piped through to the logger via the rpcchainvm.
originalStderr = os.Stderr
log.Root().SetHandler(log.LvlFilterHandler(log.LvlDebug, log.StreamHandler(originalStderr, log.TerminalFormat(false))))
}
// VM implements the snowman.ChainVM interface
type VM struct {
ctx *snow.Context
// *chain.State helps to implement the VM interface by wrapping blocks
// with an efficient caching layer.
*chain.State
config Config
chainID *big.Int
networkID uint64
genesisHash common.Hash
chain *coreth.ETHChain
chainConfig *params.ChainConfig
// [db] is the VM's current database managed by ChainState
db *versiondb.Database
// [chaindb] is the database supplied to the Ethereum backend
chaindb Database
// [acceptedBlockDB] is the database to store the last accepted
// block.
acceptedBlockDB database.Database
// [atomicTxRepository] maintains two indexes on accepted atomic txs.
// - txID to accepted atomic tx
// - block height to list of atomic txs accepted on block at that height
atomicTxRepository AtomicTxRepository
// [atomicTrie] maintains a merkle forest of [height]=>[atomic txs].
// Used to state sync clients.
atomicTrie AtomicTrie
builder *blockBuilder
gossiper Gossiper
baseCodec codec.Registry
codec codec.Manager
clock mockable.Clock
mempool *Mempool
shutdownChan chan struct{}
shutdownWg sync.WaitGroup
fx secp256k1fx.Fx
secpFactory crypto.FactorySECP256K1R
// Continuous Profiler
profiler profiler.ContinuousProfiler
peer.Network
client peer.Client
networkCodec codec.Manager
// Metrics
multiGatherer avalanchegoMetrics.MultiGatherer
bootstrapped bool
}
// Codec implements the secp256k1fx interface
func (vm *VM) Codec() codec.Manager { return vm.codec }
// CodecRegistry implements the secp256k1fx interface
func (vm *VM) CodecRegistry() codec.Registry { return vm.baseCodec }
// Clock implements the secp256k1fx interface
func (vm *VM) Clock() *mockable.Clock { return &vm.clock }
// Logger implements the secp256k1fx interface
func (vm *VM) Logger() logging.Logger { return vm.ctx.Log }
// setLogLevel sets the log level with the original [os.StdErr] interface along
// with the context logger.
func (vm *VM) setLogLevel(logLevel log.Lvl) {
format := log.TerminalFormat(false)
log.Root().SetHandler(log.LvlFilterHandler(logLevel, log.MultiHandler(
log.StreamHandler(originalStderr, format),
log.StreamHandler(vm.ctx.Log, format),
)))
}
/*
******************************************************************************
********************************* Snowman API ********************************
******************************************************************************
*/
// implements SnowmanPlusPlusVM interface
func (vm *VM) GetActivationTime() time.Time {
return time.Unix(vm.chainConfig.ApricotPhase4BlockTimestamp.Int64(), 0)
}
// Initialize implements the snowman.ChainVM interface
func (vm *VM) Initialize(
ctx *snow.Context,
dbManager manager.Manager,
genesisBytes []byte,
upgradeBytes []byte,
configBytes []byte,
toEngine chan<- commonEng.Message,
fxs []*commonEng.Fx,
appSender commonEng.AppSender,
) error {
vm.config.SetDefaults()
if len(configBytes) > 0 {
if err := json.Unmarshal(configBytes, &vm.config); err != nil {
return fmt.Errorf("failed to unmarshal config %s: %w", string(configBytes), err)
}
}
if err := vm.config.Validate(); err != nil {
return err
}
if b, err := json.Marshal(vm.config); err == nil {
log.Info("Initializing Coreth VM", "Version", Version, "Config", string(b))
} else {
// Log a warning message since we have already successfully unmarshalled into the struct
log.Warn("Problem initializing Coreth VM", "Version", Version, "Config", string(b), "err", err)
}
if len(fxs) > 0 {
return errUnsupportedFXs
}
metrics.Enabled = vm.config.MetricsEnabled
metrics.EnabledExpensive = vm.config.MetricsExpensiveEnabled
vm.shutdownChan = make(chan struct{}, 1)
vm.ctx = ctx
baseDB := dbManager.Current().Database
// Use NewNested rather than New so that the structure of the database
// remains the same regardless of the provided baseDB type.
vm.chaindb = Database{prefixdb.NewNested(ethDBPrefix, baseDB)}
vm.db = versiondb.New(baseDB)
vm.acceptedBlockDB = prefixdb.New(acceptedPrefix, vm.db)
g := new(core.Genesis)
if err := json.Unmarshal(genesisBytes, g); err != nil {
return err
}
// Set the chain config for mainnet/fuji chain IDs
switch {
case g.Config.ChainID.Cmp(params.AvalancheMainnetChainID) == 0:
g.Config = params.AvalancheMainnetChainConfig
phase0BlockValidator.extDataHashes = mainnetExtDataHashes
case g.Config.ChainID.Cmp(params.AvalancheFujiChainID) == 0:
g.Config = params.AvalancheFujiChainConfig
phase0BlockValidator.extDataHashes = fujiExtDataHashes
case g.Config.ChainID.Cmp(params.AvalancheLocalChainID) == 0:
g.Config = params.AvalancheLocalChainConfig
}
// Free the memory of the extDataHash map that is not used (i.e. if mainnet
// config, free fuji)
fujiExtDataHashes = nil
mainnetExtDataHashes = nil
vm.chainID = g.Config.ChainID
ethConfig := ethconfig.NewDefaultConfig()
ethConfig.Genesis = g
ethConfig.NetworkId = vm.chainID.Uint64()
// Set log level
logLevel, err := log.LvlFromString(vm.config.LogLevel)
if err != nil {
return fmt.Errorf("failed to initialize logger due to: %w ", err)
}
vm.setLogLevel(logLevel)
// Set minimum price for mining and default gas price oracle value to the min
// gas price to prevent so transactions and blocks all use the correct fees
ethConfig.RPCGasCap = vm.config.RPCGasCap
ethConfig.RPCEVMTimeout = vm.config.APIMaxDuration.Duration
ethConfig.RPCTxFeeCap = vm.config.RPCTxFeeCap
ethConfig.TxPool.NoLocals = !vm.config.LocalTxsEnabled
ethConfig.AllowUnfinalizedQueries = vm.config.AllowUnfinalizedQueries
ethConfig.AllowUnprotectedTxs = vm.config.AllowUnprotectedTxs
ethConfig.Preimages = vm.config.Preimages
ethConfig.Pruning = vm.config.Pruning
ethConfig.PopulateMissingTries = vm.config.PopulateMissingTries
ethConfig.PopulateMissingTriesParallelism = vm.config.PopulateMissingTriesParallelism
ethConfig.AllowMissingTries = vm.config.AllowMissingTries
ethConfig.SnapshotAsync = vm.config.SnapshotAsync
ethConfig.SnapshotVerify = vm.config.SnapshotVerify
ethConfig.OfflinePruning = vm.config.OfflinePruning
ethConfig.OfflinePruningBloomFilterSize = vm.config.OfflinePruningBloomFilterSize
ethConfig.OfflinePruningDataDirectory = vm.config.OfflinePruningDataDirectory
// Create directory for offline pruning
if len(ethConfig.OfflinePruningDataDirectory) != 0 {
if err := os.MkdirAll(ethConfig.OfflinePruningDataDirectory, perms.ReadWriteExecute); err != nil {
log.Error("failed to create offline pruning data directory", "error", err)
return err
}
}
vm.chainConfig = g.Config
vm.networkID = ethConfig.NetworkId
vm.secpFactory = crypto.FactorySECP256K1R{Cache: cache.LRU{Size: secpFactoryCacheSize}}
nodecfg := node.Config{
CorethVersion: Version,
KeyStoreDir: vm.config.KeystoreDirectory,
ExternalSigner: vm.config.KeystoreExternalSigner,
InsecureUnlockAllowed: vm.config.KeystoreInsecureUnlockAllowed,
}
vm.codec = Codec
// TODO: read size from settings
vm.mempool = NewMempool(ctx.AVAXAssetID, defaultMempoolSize)
// Attempt to load last accepted block to determine if it is necessary to
// initialize state with the genesis block.
lastAcceptedBytes, lastAcceptedErr := vm.acceptedBlockDB.Get(lastAcceptedKey)
var lastAcceptedHash common.Hash
switch {
case lastAcceptedErr == database.ErrNotFound:
// Set [lastAcceptedHash] to the genesis block hash.
lastAcceptedHash = ethConfig.Genesis.ToBlock(nil).Hash()
case lastAcceptedErr != nil:
return fmt.Errorf("failed to get last accepted block ID due to: %w", lastAcceptedErr)
case len(lastAcceptedBytes) != common.HashLength:
return fmt.Errorf("last accepted bytes should have been length %d, but found %d", common.HashLength, len(lastAcceptedBytes))
default:
lastAcceptedHash = common.BytesToHash(lastAcceptedBytes)
}
ethChain, err := coreth.NewETHChain(ðConfig, &nodecfg, vm.chaindb, vm.config.EthBackendSettings(), vm.createConsensusCallbacks(), lastAcceptedHash, &vm.clock)
if err != nil {
return err
}
vm.chain = ethChain
lastAccepted := vm.chain.LastAcceptedBlock()
vm.atomicTxRepository, err = NewAtomicTxRepository(vm.db, vm.codec, lastAccepted.NumberU64())
if err != nil {
return fmt.Errorf("failed to create atomic repository: %w", err)
}
bonusBlockHeights := make(map[uint64]ids.ID)
if vm.chainID.Cmp(params.AvalancheMainnetChainID) == 0 {
bonusBlockHeights = bonusBlockMainnetHeights
}
if err := repairAtomicRepositoryForBonusBlockTxs(
vm.atomicTxRepository,
vm.db,
getAtomicRepositoryRepairHeights(vm.chainID),
vm.getAtomicTxFromPreApricot5BlockByHeight,
); err != nil {
return fmt.Errorf("failed to repair atomic repository: %w", err)
}
vm.atomicTrie, err = NewAtomicTrie(vm.db, vm.ctx.SharedMemory, bonusBlockHeights, vm.atomicTxRepository, vm.codec, lastAccepted.NumberU64())
if err != nil {
return fmt.Errorf("failed to create atomic trie: %w", err)
}
// start goroutines to update the tx pool gas minimum gas price when upgrades go into effect
vm.handleGasPriceUpdates()
vm.networkCodec, err = message.BuildCodec()
if err != nil {
return err
}
// initialize peer network
vm.Network = peer.NewNetwork(appSender, vm.networkCodec, ctx.NodeID, vm.config.MaxOutboundActiveRequests)
vm.client = peer.NewClient(vm.Network)
vm.initGossipHandling()
// start goroutines to manage block building
//
// NOTE: gossip network must be initialized first otherwie ETH tx gossip will
// not work.
vm.builder = vm.NewBlockBuilder(toEngine)
vm.chain.Start()
vm.genesisHash = vm.chain.GetGenesisBlock().Hash()
log.Info(fmt.Sprintf("lastAccepted = %s", lastAccepted.Hash().Hex()))
isApricotPhase5 := vm.chainConfig.IsApricotPhase5(new(big.Int).SetUint64(lastAccepted.Time()))
atomicTxs, err := ExtractAtomicTxs(lastAccepted.ExtData(), isApricotPhase5, vm.codec)
if err != nil {
return err
}
vm.multiGatherer = avalanchegoMetrics.NewMultiGatherer()
// Initialize [vm.State]
if err := vm.initChainState(&Block{
id: ids.ID(lastAccepted.Hash()),
ethBlock: lastAccepted,
vm: vm,
status: choices.Accepted,
atomicTxs: atomicTxs,
}, metrics.Enabled); err != nil {
return err
}
vm.builder.awaitSubmittedTxs()
go vm.ctx.Log.RecoverAndPanic(vm.startContinuousProfiler)
// The Codec explicitly registers the types it requires from the secp256k1fx
// so [vm.baseCodec] is a dummy codec use to fulfill the secp256k1fx VM
// interface. The fx will register all of its types, which can be safely
// ignored by the VM's codec.
vm.baseCodec = linearcodec.NewDefault()
// pruneChain removes all rejected blocks stored in the database.
//
// TODO: This function can take over 60 minutes to run on mainnet and
// should be converted to run asynchronously.
// if err := vm.pruneChain(); err != nil {
// return err
// }
// If metrics are enabled, register the default metrics regitry
if metrics.Enabled {
gatherer := corethPrometheus.Gatherer(metrics.DefaultRegistry)
if err := vm.multiGatherer.Register(ethMetricsPrefix, gatherer); err != nil {
return err
}
}
// Register [multiGatherer] after registerers have been registered to it
if err := ctx.Metrics.Register(vm.multiGatherer); err != nil {
return err
}
return vm.fx.Initialize(vm)
}
func (vm *VM) initChainState(lastAcceptedBlock *Block, metricsEnabled bool) error {
config := &chain.Config{
DecidedCacheSize: decidedCacheSize,
MissingCacheSize: missingCacheSize,
UnverifiedCacheSize: unverifiedCacheSize,
LastAcceptedBlock: lastAcceptedBlock,
GetBlockIDAtHeight: vm.GetBlockIDAtHeight,
GetBlock: vm.getBlock,
UnmarshalBlock: vm.parseBlock,
BuildBlock: vm.buildBlock,
}
if !metricsEnabled {
vm.State = chain.NewState(config)
return nil
}
// Register chain state metrics
chainStateRegisterer := prometheus.NewRegistry()
state, err := chain.NewMeteredState(chainStateRegisterer, config)
if err != nil {
return err
}
vm.State = state
return vm.multiGatherer.Register(chainStateMetricsPrefix, chainStateRegisterer)
}
func (vm *VM) initGossipHandling() {
if vm.chainConfig.ApricotPhase4BlockTimestamp != nil {
vm.gossiper = vm.newPushGossiper()
vm.Network.SetGossipHandler(NewGossipHandler(vm))
} else {
vm.gossiper = &noopGossiper{}
vm.Network.SetGossipHandler(message.NoopMempoolGossipHandler{})
}
}
func (vm *VM) createConsensusCallbacks() *dummy.ConsensusCallbacks {
return &dummy.ConsensusCallbacks{
OnFinalizeAndAssemble: vm.onFinalizeAndAssemble,
OnExtraStateChange: vm.onExtraStateChange,
}
}
func (vm *VM) preBatchOnFinalizeAndAssemble(header *types.Header, state *state.StateDB, txs []*types.Transaction) ([]byte, *big.Int, *big.Int, error) {
for {
tx, exists := vm.mempool.NextTx()
if !exists {
break
}
// Take a snapshot of [state] before calling verifyTx so that if the transaction fails verification
// we can revert to [snapshot].
// Note: snapshot is taken inside the loop because you cannot revert to the same snapshot more than
// once.
snapshot := state.Snapshot()
rules := vm.chainConfig.AvalancheRules(header.Number, new(big.Int).SetUint64(header.Time))
if err := vm.verifyTx(tx, header.ParentHash, header.BaseFee, state, rules); err != nil {
// Discard the transaction from the mempool on failed verification.
vm.mempool.DiscardCurrentTx(tx.ID())
state.RevertToSnapshot(snapshot)
continue
}
atomicTxBytes, err := vm.codec.Marshal(codecVersion, tx)
if err != nil {
// Discard the transaction from the mempool and error if the transaction
// cannot be marshalled. This should never happen.
vm.mempool.DiscardCurrentTx(tx.ID())
return nil, nil, nil, fmt.Errorf("failed to marshal atomic transaction %s due to %w", tx.ID(), err)
}
var contribution, gasUsed *big.Int
if rules.IsApricotPhase4 {
contribution, gasUsed, err = tx.BlockFeeContribution(rules.IsApricotPhase5, vm.ctx.AVAXAssetID, header.BaseFee)
if err != nil {
return nil, nil, nil, err
}
}
return atomicTxBytes, contribution, gasUsed, nil
}
if len(txs) == 0 {
// this could happen due to the async logic of geth tx pool
return nil, nil, nil, errEmptyBlock
}
return nil, nil, nil, nil
}
// assumes that we are in at least Apricot Phase 5.
func (vm *VM) postBatchOnFinalizeAndAssemble(header *types.Header, state *state.StateDB, txs []*types.Transaction) ([]byte, *big.Int, *big.Int, error) {
var (
batchAtomicTxs []*Tx
batchAtomicUTXOs ids.Set
batchContribution *big.Int = new(big.Int).Set(common.Big0)
batchGasUsed *big.Int = new(big.Int).Set(common.Big0)
rules = vm.chainConfig.AvalancheRules(header.Number, new(big.Int).SetUint64(header.Time))
)
for {
tx, exists := vm.mempool.NextTx()
if !exists {
break
}
var (
txGasUsed, txContribution *big.Int
err error
)
// Note: we do not need to check if we are in at least ApricotPhase4 here because
// we assume that this function will only be called when the block is in at least
// ApricotPhase5.
txContribution, txGasUsed, err = tx.BlockFeeContribution(true, vm.ctx.AVAXAssetID, header.BaseFee)
if err != nil {
return nil, nil, nil, err
}
// ensure [gasUsed] + [batchGasUsed] doesnt exceed the [atomicGasLimit]
if totalGasUsed := new(big.Int).Add(batchGasUsed, txGasUsed); totalGasUsed.Cmp(params.AtomicGasLimit) > 0 {
// Send [tx] back to the mempool's tx heap.
vm.mempool.CancelCurrentTx(tx.ID())
break
}
if batchAtomicUTXOs.Overlaps(tx.InputUTXOs()) {
// Discard the transaction from the mempool since it will fail verification
// after this block has been accepted.
// Note: if the proposed block is not accepted, the transaction may still be
// valid, but we discard it early here based on the assumption that the proposed
// block will most likely be accepted.
// Discard the transaction from the mempool on failed verification.
vm.mempool.DiscardCurrentTx(tx.ID())
continue
}
snapshot := state.Snapshot()
if err := vm.verifyTx(tx, header.ParentHash, header.BaseFee, state, rules); err != nil {
// Discard the transaction from the mempool and reset the state to [snapshot]
// if it fails verification here.
// Note: prior to this point, we have not modified [state] so there is no need to
// revert to a snapshot if we discard the transaction prior to this point.
vm.mempool.DiscardCurrentTx(tx.ID())
state.RevertToSnapshot(snapshot)
continue
}
batchAtomicTxs = append(batchAtomicTxs, tx)
batchAtomicUTXOs.Union(tx.InputUTXOs())
// Add the [txGasUsed] to the [batchGasUsed] when the [tx] has passed verification
batchGasUsed.Add(batchGasUsed, txGasUsed)
batchContribution.Add(batchContribution, txContribution)
}
// If there is a non-zero number of transactions, marshal them and return the byte slice
// for the block's extra data along with the contribution and gas used.
if len(batchAtomicTxs) > 0 {
atomicTxBytes, err := vm.codec.Marshal(codecVersion, batchAtomicTxs)
if err != nil {
// If we fail to marshal the batch of atomic transactions for any reason,
// discard the entire set of current transactions.
vm.mempool.DiscardCurrentTxs()
return nil, nil, nil, fmt.Errorf("failed to marshal batch of atomic transactions due to %w", err)
}
return atomicTxBytes, batchContribution, batchGasUsed, nil
}
// If there are no regular transactions and there were also no atomic transactions to be included,
// then the block is empty and should be considered invalid.
if len(txs) == 0 {
// this could happen due to the async logic of geth tx pool
return nil, nil, nil, errEmptyBlock
}
// If there are no atomic transactions, but there is a non-zero number of regular transactions, then
// we return a nil slice with no contribution from the atomic transactions and a nil error.
return nil, nil, nil, nil
}
func (vm *VM) onFinalizeAndAssemble(header *types.Header, state *state.StateDB, txs []*types.Transaction) ([]byte, *big.Int, *big.Int, error) {
if !vm.chainConfig.IsApricotPhase5(new(big.Int).SetUint64(header.Time)) {
return vm.preBatchOnFinalizeAndAssemble(header, state, txs)
}
return vm.postBatchOnFinalizeAndAssemble(header, state, txs)
}
func (vm *VM) onExtraStateChange(block *types.Block, state *state.StateDB) (*big.Int, *big.Int, error) {
var (
batchContribution *big.Int = big.NewInt(0)
batchGasUsed *big.Int = big.NewInt(0)
timestamp = new(big.Int).SetUint64(block.Time())
isApricotPhase4 = vm.chainConfig.IsApricotPhase4(timestamp)
isApricotPhase5 = vm.chainConfig.IsApricotPhase5(timestamp)
)
txs, err := ExtractAtomicTxs(block.ExtData(), isApricotPhase5, vm.codec)
if err != nil {
return nil, nil, err
}
// If there are no transactions, we can return early
if len(txs) == 0 {
return nil, nil, nil
}
for _, tx := range txs {
if err := tx.UnsignedAtomicTx.EVMStateTransfer(vm.ctx, state); err != nil {
return nil, nil, err
}
// If ApricotPhase4 is enabled, calculate the block fee contribution
if isApricotPhase4 {
contribution, gasUsed, err := tx.BlockFeeContribution(isApricotPhase5, vm.ctx.AVAXAssetID, block.BaseFee())
if err != nil {
return nil, nil, err
}
batchContribution.Add(batchContribution, contribution)
batchGasUsed.Add(batchGasUsed, gasUsed)
}
// If ApricotPhase5 is enabled, enforce that the atomic gas used does not exceed the
// atomic gas limit.
if vm.chainConfig.IsApricotPhase5(timestamp) {
// Ensure that [tx] does not push [block] above the atomic gas limit.
if batchGasUsed.Cmp(params.AtomicGasLimit) == 1 {
return nil, nil, fmt.Errorf("atomic gas used (%d) by block (%s), exceeds atomic gas limit (%d)", batchGasUsed, block.Hash().Hex(), params.AtomicGasLimit)
}
}
}
return batchContribution, batchGasUsed, nil
}
func (vm *VM) pruneChain() error {
if !vm.config.Pruning {
return nil
}
pruned, err := vm.db.Has(pruneRejectedBlocksKey)
if err != nil {
return fmt.Errorf("failed to check if the VM has pruned rejected blocks: %w", err)
}
if pruned {
return nil
}
lastAcceptedHeight := vm.LastAcceptedBlock().Height()
if err := vm.chain.RemoveRejectedBlocks(0, lastAcceptedHeight); err != nil {
return err
}
heightBytes := make([]byte, 8)
binary.PutUvarint(heightBytes, lastAcceptedHeight)
if err := vm.db.Put(pruneRejectedBlocksKey, heightBytes); err != nil {
return err
}
return vm.db.Commit()
}
func (vm *VM) SetState(state snow.State) error {
switch state {
case snow.Bootstrapping:
vm.bootstrapped = false
return vm.fx.Bootstrapping()
case snow.NormalOp:
vm.bootstrapped = true
return vm.fx.Bootstrapped()
default:
return snow.ErrUnknownState
}
}
// Shutdown implements the snowman.ChainVM interface
func (vm *VM) Shutdown() error {
if vm.ctx == nil {
return nil
}
close(vm.shutdownChan)
vm.chain.Stop()
vm.shutdownWg.Wait()
return nil
}
// buildBlock builds a block to be wrapped by ChainState
func (vm *VM) buildBlock() (snowman.Block, error) {
block, err := vm.chain.GenerateBlock()
vm.builder.handleGenerateBlock()
if err != nil {
vm.mempool.CancelCurrentTxs()
return nil, err
}
isApricotPhase5 := vm.chainConfig.IsApricotPhase5(new(big.Int).SetUint64(block.Time()))
atomicTxs, err := ExtractAtomicTxs(block.ExtData(), isApricotPhase5, vm.codec)
if err != nil {
vm.mempool.DiscardCurrentTxs()
return nil, err
}
// Note: the status of block is set by ChainState
blk := &Block{
id: ids.ID(block.Hash()),
ethBlock: block,
vm: vm,
atomicTxs: atomicTxs,
}
// Verify is called on a non-wrapped block here, such that this
// does not add [blk] to the processing blocks map in ChainState.
//
// TODO cache verification since Verify() will be called by the
// consensus engine as well.
//
// Note: this is only called when building a new block, so caching
// verification will only be a significant optimization for nodes
// that produce a large number of blocks.
// We call verify without writes here to avoid generating a reference
// to the blk state root in the triedb when we are going to call verify
// again from the consensus engine with writes enabled.
if err := blk.verify(false /*=writes*/); err != nil {
vm.mempool.CancelCurrentTxs()
return nil, fmt.Errorf("block failed verification due to: %w", err)
}
log.Debug(fmt.Sprintf("Built block %s", blk.ID()))
// Marks the current transactions from the mempool as being successfully issued
// into a block.
vm.mempool.IssueCurrentTxs()
return blk, nil
}
// parseBlock parses [b] into a block to be wrapped by ChainState.
func (vm *VM) parseBlock(b []byte) (snowman.Block, error) {
ethBlock := new(types.Block)
if err := rlp.DecodeBytes(b, ethBlock); err != nil {
return nil, err
}
isApricotPhase5 := vm.chainConfig.IsApricotPhase5(new(big.Int).SetUint64(ethBlock.Time()))
atomicTxs, err := ExtractAtomicTxs(ethBlock.ExtData(), isApricotPhase5, vm.codec)
if err != nil {
return nil, err
}
// Note: the status of block is set by ChainState
block := &Block{
id: ids.ID(ethBlock.Hash()),
ethBlock: ethBlock,
vm: vm,
atomicTxs: atomicTxs,
}
// Performing syntactic verification in ParseBlock allows for
// short-circuiting bad blocks before they are processed by the VM.
if _, err := block.syntacticVerify(); err != nil {
return nil, fmt.Errorf("syntactic block verification failed: %w", err)
}
return block, nil
}
// getBlock attempts to retrieve block [id] from the VM to be wrapped
// by ChainState.
func (vm *VM) getBlock(id ids.ID) (snowman.Block, error) {
ethBlock := vm.chain.GetBlockByHash(common.Hash(id))
// If [ethBlock] is nil, return [database.ErrNotFound] here
// so that the miss is considered cacheable.
if ethBlock == nil {
return nil, database.ErrNotFound
}
isApricotPhase5 := vm.chainConfig.IsApricotPhase5(new(big.Int).SetUint64(ethBlock.Time()))
atomicTxs, err := ExtractAtomicTxs(ethBlock.ExtData(), isApricotPhase5, vm.codec)
if err != nil {
return nil, err
}
// Note: the status of block is set by ChainState
blk := &Block{
id: ids.ID(ethBlock.Hash()),
ethBlock: ethBlock,
vm: vm,
atomicTxs: atomicTxs,
}
return blk, nil
}
// SetPreference sets what the current tail of the chain is
func (vm *VM) SetPreference(blkID ids.ID) error {
// Since each internal handler used by [vm.State] always returns a block
// with non-nil ethBlock value, GetBlockInternal should never return a
// (*Block) with a nil ethBlock value.
block, err := vm.GetBlockInternal(blkID)
if err != nil {
return fmt.Errorf("failed to set preference to %s: %w", blkID, err)
}
return vm.chain.SetPreference(block.(*Block).ethBlock)
}
func (vm *VM) VerifyHeightIndex() error {
// our index is vm.chain.GetBlockByNumber
return nil
}
// GetBlockIDAtHeight retrieves the blkID of the canonical block at [blkHeight]
// if [blkHeight] is less than the height of the last accepted block, this will return
// a canonical block. Otherwise, it may return a blkID that has not yet been accepted.
func (vm *VM) GetBlockIDAtHeight(blkHeight uint64) (ids.ID, error) {
ethBlock := vm.chain.GetBlockByNumber(blkHeight)
if ethBlock == nil {
return ids.ID{}, fmt.Errorf("could not find block at height: %d", blkHeight)
}
return ids.ID(ethBlock.Hash()), nil
}
func (vm *VM) Version() (string, error) {
return Version, nil
}
// NewHandler returns a new Handler for a service where:
// * The handler's functionality is defined by [service]
// [service] should be a gorilla RPC service (see https://www.gorillatoolkit.org/pkg/rpc/v2)
// * The name of the service is [name]
// * The LockOption is the first element of [lockOption]
// By default the LockOption is WriteLock
// [lockOption] should have either 0 or 1 elements. Elements beside the first are ignored.
func newHandler(name string, service interface{}, lockOption ...commonEng.LockOption) (*commonEng.HTTPHandler, error) {
server := avalancheRPC.NewServer()
server.RegisterCodec(avalancheJSON.NewCodec(), "application/json")
server.RegisterCodec(avalancheJSON.NewCodec(), "application/json;charset=UTF-8")
if err := server.RegisterService(service, name); err != nil {
return nil, err
}
var lock commonEng.LockOption = commonEng.WriteLock
if len(lockOption) != 0 {
lock = lockOption[0]
}
return &commonEng.HTTPHandler{LockOptions: lock, Handler: server}, nil
}
// CreateHandlers makes new http handlers that can handle API calls
func (vm *VM) CreateHandlers() (map[string]*commonEng.HTTPHandler, error) {
handler := vm.chain.NewRPCHandler(vm.config.APIMaxDuration.Duration)
enabledAPIs := vm.config.EthAPIs()
if err := vm.chain.AttachEthService(handler, enabledAPIs); err != nil {
return nil, err
}
primaryAlias, err := vm.ctx.BCLookup.PrimaryAlias(vm.ctx.ChainID)
if err != nil {
return nil, fmt.Errorf("failed to get primary alias for chain due to %w", err)
}
apis := make(map[string]*commonEng.HTTPHandler)
avaxAPI, err := newHandler("avax", &AvaxAPI{vm})
if err != nil {
return nil, fmt.Errorf("failed to register service for AVAX API due to %w", err)
}
enabledAPIs = append(enabledAPIs, "avax")
apis[avaxEndpoint] = avaxAPI
if vm.config.CorethAdminAPIEnabled {
adminAPI, err := newHandler("admin", NewAdminService(vm, os.ExpandEnv(fmt.Sprintf("%s_coreth_performance_%s", vm.config.CorethAdminAPIDir, primaryAlias))))
if err != nil {
return nil, fmt.Errorf("failed to register service for admin API due to %w", err)
}
apis[adminEndpoint] = adminAPI
enabledAPIs = append(enabledAPIs, "coreth-admin")
}
if vm.config.SnowmanAPIEnabled {
if err := handler.RegisterName("snowman", &SnowmanAPI{vm}); err != nil {
return nil, err
}
enabledAPIs = append(enabledAPIs, "snowman")
}
log.Info(fmt.Sprintf("Enabled APIs: %s", strings.Join(enabledAPIs, ", ")))
apis[ethRPCEndpoint] = &commonEng.HTTPHandler{
LockOptions: commonEng.NoLock,
Handler: handler,
}
apis[ethWSEndpoint] = &commonEng.HTTPHandler{
LockOptions: commonEng.NoLock,
Handler: handler.WebsocketHandlerWithDuration(
[]string{"*"},
vm.config.APIMaxDuration.Duration,
vm.config.WSCPURefillRate.Duration,
vm.config.WSCPUMaxStored.Duration,
),
}
return apis, nil
}