-
Notifications
You must be signed in to change notification settings - Fork 132
/
vm.go
1763 lines (1558 loc) · 60.7 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/json"
"errors"
"fmt"
"io"
"math/big"
"os"
"path/filepath"
"strings"
"sync"
"time"
avalanchegoMetrics "github.com/ava-labs/avalanchego/api/metrics"
"github.com/ava-labs/coreth/consensus/dummy"
corethConstants "github.com/ava-labs/coreth/constants"
"github.com/ava-labs/coreth/core"
"github.com/ava-labs/coreth/core/rawdb"
"github.com/ava-labs/coreth/core/state"
"github.com/ava-labs/coreth/core/types"
"github.com/ava-labs/coreth/eth"
"github.com/ava-labs/coreth/eth/ethconfig"
"github.com/ava-labs/coreth/ethdb"
corethPrometheus "github.com/ava-labs/coreth/metrics/prometheus"
"github.com/ava-labs/coreth/miner"
"github.com/ava-labs/coreth/node"
"github.com/ava-labs/coreth/params"
"github.com/ava-labs/coreth/peer"
"github.com/ava-labs/coreth/plugin/evm/message"
"github.com/ava-labs/coreth/rpc"
statesyncclient "github.com/ava-labs/coreth/sync/client"
"github.com/ava-labs/coreth/sync/client/stats"
"github.com/ava-labs/coreth/sync/handlers"
handlerstats "github.com/ava-labs/coreth/sync/handlers/stats"
"github.com/ava-labs/coreth/trie"
"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/ava-labs/coreth/eth/tracers/js"
_ "github.com/ava-labs/coreth/eth/tracers/native"
"github.com/ethereum/go-ethereum/common"
"github.com/ethereum/go-ethereum/log"
"github.com/ethereum/go-ethereum/rlp"
"github.com/ava-labs/coreth/metrics"
avalancheRPC "github.com/gorilla/rpc/v2"
"github.com/ava-labs/avalanchego/cache"
"github.com/ava-labs/avalanchego/codec"
"github.com/ava-labs/avalanchego/codec/linearcodec"
"github.com/ava-labs/avalanchego/database"
"github.com/ava-labs/avalanchego/database/manager"
"github.com/ava-labs/avalanchego/database/prefixdb"
"github.com/ava-labs/avalanchego/database/versiondb"
"github.com/ava-labs/avalanchego/ids"
"github.com/ava-labs/avalanchego/snow"
"github.com/ava-labs/avalanchego/snow/choices"
"github.com/ava-labs/avalanchego/snow/consensus/snowman"
"github.com/ava-labs/avalanchego/snow/engine/snowman/block"
"github.com/ava-labs/avalanchego/utils/constants"
"github.com/ava-labs/avalanchego/utils/crypto/secp256k1"
"github.com/ava-labs/avalanchego/utils/formatting/address"
"github.com/ava-labs/avalanchego/utils/logging"
"github.com/ava-labs/avalanchego/utils/math"
"github.com/ava-labs/avalanchego/utils/perms"
"github.com/ava-labs/avalanchego/utils/profiler"
"github.com/ava-labs/avalanchego/utils/set"
"github.com/ava-labs/avalanchego/utils/timer/mockable"
"github.com/ava-labs/avalanchego/utils/units"
"github.com/ava-labs/avalanchego/vms/components/avax"
"github.com/ava-labs/avalanchego/vms/components/chain"
"github.com/ava-labs/avalanchego/vms/secp256k1fx"
commonEng "github.com/ava-labs/avalanchego/snow/engine/common"
avalancheJSON "github.com/ava-labs/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.StateSyncableVM = &VM{}
_ block.HeightIndexedChainVM = &VM{}
_ statesyncclient.EthBlockParser = &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
targetAtomicTxsSize = 40 * units.KiB
)
// 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")
metadataPrefix = []byte("metadata")
ethDBPrefix = []byte("ethdb")
// Prefixes for atomic trie
atomicTrieDBPrefix = []byte("atomicTrieDB")
atomicTrieMetaDBPrefix = []byte("atomicTrieMetaDB")
)
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")
errRejectedParent = errors.New("rejected parent")
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
// legacyApiNames maps pre geth v1.10.20 api names to their updated counterparts.
// used in attachEthService for backward configuration compatibility.
var legacyApiNames = map[string]string{
"internal-public-eth": "internal-eth",
"internal-public-blockchain": "internal-blockchain",
"internal-public-transaction-pool": "internal-transaction",
"internal-public-tx-pool": "internal-tx-pool",
"internal-public-debug": "internal-debug",
"internal-private-debug": "internal-debug",
"internal-public-account": "internal-account",
"internal-private-personal": "internal-personal",
"public-eth": "eth",
"public-eth-filter": "eth-filter",
"private-admin": "admin",
"public-debug": "debug",
"private-debug": "debug",
}
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
}
// 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
chainConfig *params.ChainConfig
ethConfig ethconfig.Config
// pointers to eth constructs
eth *eth.Ethereum
txPool *core.TxPool
blockChain *core.BlockChain
miner *miner.Miner
// [db] is the VM's current database managed by ChainState
db *versiondb.Database
// metadataDB is used to store one off keys.
metadataDB database.Database
// [chaindb] is the database supplied to the Ethereum backend
chaindb ethdb.Database
// [acceptedBlockDB] is the database to store the last accepted
// block.
acceptedBlockDB database.Database
toEngine chan<- commonEng.Message
syntacticBlockValidator BlockValidator
// [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].
atomicTrie AtomicTrie
// [atomicBackend] abstracts verification and processing of atomic transactions
atomicBackend AtomicBackend
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 secp256k1.Factory
// Continuous Profiler
profiler profiler.ContinuousProfiler
peer.Network
client peer.NetworkClient
networkCodec codec.Manager
// Metrics
multiGatherer avalanchegoMetrics.MultiGatherer
bootstrapped bool
IsPlugin bool
logger CorethLogger
// State sync server and client
StateSyncServer
StateSyncClient
}
// 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 }
/*
******************************************************************************
********************************* 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(
_ context.Context,
chainCtx *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
}
vm.ctx = chainCtx
// Create logger
alias, err := vm.ctx.BCLookup.PrimaryAlias(vm.ctx.ChainID)
if err != nil {
alias = vm.ctx.ChainID.String()
}
var writer io.Writer = vm.ctx.Log
if vm.IsPlugin {
writer = originalStderr
}
corethLogger, err := InitLogger(alias, vm.config.LogLevel, vm.config.LogJSONFormat, writer)
if err != nil {
return fmt.Errorf("failed to initialize logger due to: %w ", err)
}
vm.logger = corethLogger
log.Info("Initializing Coreth VM", "Version", Version, "Config", vm.config)
if len(fxs) > 0 {
return errUnsupportedFXs
}
// Enable debug-level metrics that might impact runtime performance
metrics.EnabledExpensive = vm.config.MetricsExpensiveEnabled
vm.toEngine = toEngine
vm.shutdownChan = make(chan struct{}, 1)
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)
vm.metadataDB = prefixdb.New(metadataPrefix, vm.db)
if vm.config.InspectDatabase {
start := time.Now()
log.Info("Starting database inspection")
if err := rawdb.InspectDatabase(vm.chaindb, nil, nil); err != nil {
return err
}
log.Info("Completed database inspection", "elapsed", time.Since(start))
}
g := new(core.Genesis)
if err := json.Unmarshal(genesisBytes, g); err != nil {
return err
}
var extDataHashes map[common.Hash]common.Hash
// Set the chain config for mainnet/fuji chain IDs
switch {
case g.Config.ChainID.Cmp(params.AvalancheMainnetChainID) == 0:
g.Config = params.AvalancheMainnetChainConfig
extDataHashes = mainnetExtDataHashes
case g.Config.ChainID.Cmp(params.AvalancheFujiChainID) == 0:
g.Config = params.AvalancheFujiChainConfig
extDataHashes = fujiExtDataHashes
case g.Config.ChainID.Cmp(params.AvalancheLocalChainID) == 0:
g.Config = params.AvalancheLocalChainConfig
}
// Set the Avalanche Context on the ChainConfig
g.Config.AvalancheContext = params.AvalancheContext{
BlockchainID: common.Hash(chainCtx.ChainID),
}
vm.syntacticBlockValidator = NewBlockValidator(extDataHashes)
// Ensure that non-standard commit interval is only allowed for the local network
if g.Config.ChainID.Cmp(params.AvalancheLocalChainID) != 0 {
if vm.config.CommitInterval != defaultCommitInterval {
return fmt.Errorf("cannot start non-local network with commit interval %d", vm.config.CommitInterval)
}
if vm.config.StateSyncCommitInterval != defaultSyncableCommitInterval {
return fmt.Errorf("cannot start non-local network with syncable interval %d", vm.config.StateSyncCommitInterval)
}
}
// 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
vm.ethConfig = ethconfig.NewDefaultConfig()
vm.ethConfig.Genesis = g
vm.ethConfig.NetworkId = vm.chainID.Uint64()
vm.genesisHash = vm.ethConfig.Genesis.ToBlock(nil).Hash() // must create genesis hash before [vm.readLastAccepted]
lastAcceptedHash, lastAcceptedHeight, err := vm.readLastAccepted()
if err != nil {
return err
}
log.Info(fmt.Sprintf("lastAccepted = %s", lastAcceptedHash))
// 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
vm.ethConfig.RPCGasCap = vm.config.RPCGasCap
vm.ethConfig.RPCEVMTimeout = vm.config.APIMaxDuration.Duration
vm.ethConfig.RPCTxFeeCap = vm.config.RPCTxFeeCap
vm.ethConfig.TxPool.NoLocals = !vm.config.LocalTxsEnabled
vm.ethConfig.TxPool.Journal = vm.config.TxPoolJournal
vm.ethConfig.TxPool.Rejournal = vm.config.TxPoolRejournal.Duration
vm.ethConfig.TxPool.PriceLimit = vm.config.TxPoolPriceLimit
vm.ethConfig.TxPool.PriceBump = vm.config.TxPoolPriceBump
vm.ethConfig.TxPool.AccountSlots = vm.config.TxPoolAccountSlots
vm.ethConfig.TxPool.GlobalSlots = vm.config.TxPoolGlobalSlots
vm.ethConfig.TxPool.AccountQueue = vm.config.TxPoolAccountQueue
vm.ethConfig.TxPool.GlobalQueue = vm.config.TxPoolGlobalQueue
vm.ethConfig.AllowUnfinalizedQueries = vm.config.AllowUnfinalizedQueries
vm.ethConfig.AllowUnprotectedTxs = vm.config.AllowUnprotectedTxs
vm.ethConfig.AllowUnprotectedTxHashes = vm.config.AllowUnprotectedTxHashes
vm.ethConfig.Preimages = vm.config.Preimages
vm.ethConfig.TrieCleanCache = vm.config.TrieCleanCache
vm.ethConfig.TrieCleanJournal = vm.config.TrieCleanJournal
vm.ethConfig.TrieCleanRejournal = vm.config.TrieCleanRejournal.Duration
vm.ethConfig.TrieDirtyCache = vm.config.TrieDirtyCache
vm.ethConfig.TrieDirtyCommitTarget = vm.config.TrieDirtyCommitTarget
vm.ethConfig.SnapshotCache = vm.config.SnapshotCache
vm.ethConfig.Pruning = vm.config.Pruning
vm.ethConfig.AcceptorQueueLimit = vm.config.AcceptorQueueLimit
vm.ethConfig.PopulateMissingTries = vm.config.PopulateMissingTries
vm.ethConfig.PopulateMissingTriesParallelism = vm.config.PopulateMissingTriesParallelism
vm.ethConfig.AllowMissingTries = vm.config.AllowMissingTries
vm.ethConfig.SnapshotDelayInit = vm.stateSyncEnabled(lastAcceptedHeight)
vm.ethConfig.SnapshotAsync = vm.config.SnapshotAsync
vm.ethConfig.SnapshotVerify = vm.config.SnapshotVerify
vm.ethConfig.OfflinePruning = vm.config.OfflinePruning
vm.ethConfig.OfflinePruningBloomFilterSize = vm.config.OfflinePruningBloomFilterSize
vm.ethConfig.OfflinePruningDataDirectory = vm.config.OfflinePruningDataDirectory
vm.ethConfig.CommitInterval = vm.config.CommitInterval
vm.ethConfig.SkipUpgradeCheck = vm.config.SkipUpgradeCheck
vm.ethConfig.AcceptedCacheSize = vm.config.AcceptedCacheSize
vm.ethConfig.TxLookupLimit = vm.config.TxLookupLimit
// Create directory for offline pruning
if len(vm.ethConfig.OfflinePruningDataDirectory) != 0 {
if err := os.MkdirAll(vm.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 = vm.ethConfig.NetworkId
vm.secpFactory = secp256k1.Factory{
Cache: cache.LRU[ids.ID, *secp256k1.PublicKey]{
Size: secpFactoryCacheSize,
},
}
vm.codec = Codec
// TODO: read size from settings
vm.mempool = NewMempool(chainCtx.AVAXAssetID, defaultMempoolSize)
if err := vm.initializeMetrics(); err != nil {
return err
}
// initialize peer network
vm.networkCodec = message.Codec
vm.Network = peer.NewNetwork(appSender, vm.networkCodec, message.CrossChainCodec, chainCtx.NodeID, vm.config.MaxOutboundActiveRequests, vm.config.MaxOutboundActiveCrossChainRequests)
vm.client = peer.NewNetworkClient(vm.Network)
if err := vm.initializeChain(lastAcceptedHash); err != nil {
return err
}
// initialize bonus blocks on mainnet
var (
bonusBlockHeights map[uint64]ids.ID
canonicalBlockHeights []uint64
)
if vm.chainID.Cmp(params.AvalancheMainnetChainID) == 0 {
bonusBlockHeights = bonusBlockMainnetHeights
canonicalBlockHeights = canonicalBlockMainnetHeights
}
// initialize atomic repository
vm.atomicTxRepository, err = NewAtomicTxRepository(
vm.db, vm.codec, lastAcceptedHeight,
bonusBlockHeights, canonicalBlockHeights,
vm.getAtomicTxFromPreApricot5BlockByHeight,
)
if err != nil {
return fmt.Errorf("failed to create atomic repository: %w", err)
}
vm.atomicBackend, err = NewAtomicBackend(
vm.db, vm.ctx.SharedMemory, bonusBlockHeights, vm.atomicTxRepository, lastAcceptedHeight, lastAcceptedHash, vm.config.CommitInterval,
)
if err != nil {
return fmt.Errorf("failed to create atomic backend: %w", err)
}
vm.atomicTrie = vm.atomicBackend.AtomicTrie()
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()
if err := vm.fx.Initialize(vm); err != nil {
return err
}
vm.initializeStateSyncServer()
return vm.initializeStateSyncClient(lastAcceptedHeight)
}
func (vm *VM) initializeMetrics() error {
vm.multiGatherer = avalanchegoMetrics.NewMultiGatherer()
// 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 := vm.ctx.Metrics.Register(vm.multiGatherer); err != nil {
return err
}
}
return nil
}
func (vm *VM) initializeChain(lastAcceptedHash common.Hash) error {
nodecfg := &node.Config{
CorethVersion: Version,
KeyStoreDir: vm.config.KeystoreDirectory,
ExternalSigner: vm.config.KeystoreExternalSigner,
InsecureUnlockAllowed: vm.config.KeystoreInsecureUnlockAllowed,
}
node, err := node.New(nodecfg)
if err != nil {
return err
}
vm.eth, err = eth.New(
node,
&vm.ethConfig,
vm.createConsensusCallbacks(),
vm.chaindb,
vm.config.EthBackendSettings(),
lastAcceptedHash,
&vm.clock,
)
if err != nil {
return err
}
vm.eth.SetEtherbase(corethConstants.BlackholeAddr)
vm.txPool = vm.eth.TxPool()
vm.blockChain = vm.eth.BlockChain()
vm.miner = vm.eth.Miner()
// start goroutines to update the tx pool gas minimum gas price when upgrades go into effect
vm.handleGasPriceUpdates()
vm.eth.Start()
return vm.initChainState(vm.blockChain.LastAcceptedBlock())
}
// initializeStateSyncClient initializes the client for performing state sync.
// If state sync is disabled, this function will wipe any ongoing summary from
// disk to ensure that we do not continue syncing from an invalid snapshot.
func (vm *VM) initializeStateSyncClient(lastAcceptedHeight uint64) error {
stateSyncEnabled := vm.stateSyncEnabled(lastAcceptedHeight)
// parse nodeIDs from state sync IDs in vm config
var stateSyncIDs []ids.NodeID
if stateSyncEnabled && len(vm.config.StateSyncIDs) > 0 {
nodeIDs := strings.Split(vm.config.StateSyncIDs, ",")
stateSyncIDs = make([]ids.NodeID, len(nodeIDs))
for i, nodeIDString := range nodeIDs {
nodeID, err := ids.NodeIDFromString(nodeIDString)
if err != nil {
return fmt.Errorf("failed to parse %s as NodeID: %w", nodeIDString, err)
}
stateSyncIDs[i] = nodeID
}
}
vm.StateSyncClient = NewStateSyncClient(&stateSyncClientConfig{
chain: vm.eth,
state: vm.State,
client: statesyncclient.NewClient(
&statesyncclient.ClientConfig{
NetworkClient: vm.client,
Codec: vm.networkCodec,
Stats: stats.NewClientSyncerStats(),
StateSyncNodeIDs: stateSyncIDs,
BlockParser: vm,
},
),
enabled: stateSyncEnabled,
skipResume: vm.config.StateSyncSkipResume,
stateSyncMinBlocks: vm.config.StateSyncMinBlocks,
stateSyncRequestSize: vm.config.StateSyncRequestSize,
lastAcceptedHeight: lastAcceptedHeight, // TODO clean up how this is passed around
chaindb: vm.chaindb,
metadataDB: vm.metadataDB,
acceptedBlockDB: vm.acceptedBlockDB,
db: vm.db,
atomicBackend: vm.atomicBackend,
toEngine: vm.toEngine,
})
// If StateSync is disabled, clear any ongoing summary so that we will not attempt to resume
// sync using a snapshot that has been modified by the node running normal operations.
if !stateSyncEnabled {
return vm.StateSyncClient.StateSyncClearOngoingSummary()
}
return nil
}
// initializeStateSyncServer should be called after [vm.chain] is initialized.
func (vm *VM) initializeStateSyncServer() {
vm.StateSyncServer = NewStateSyncServer(&stateSyncServerConfig{
Chain: vm.blockChain,
AtomicTrie: vm.atomicTrie,
SyncableInterval: vm.config.StateSyncCommitInterval,
})
vm.setAppRequestHandlers()
vm.setCrossChainAppRequestHandler()
}
func (vm *VM) initChainState(lastAcceptedBlock *types.Block) error {
block, err := vm.newBlock(lastAcceptedBlock)
if err != nil {
return fmt.Errorf("failed to create block wrapper for the last accepted block: %w", err)
}
block.status = choices.Accepted
config := &chain.Config{
DecidedCacheSize: decidedCacheSize,
MissingCacheSize: missingCacheSize,
UnverifiedCacheSize: unverifiedCacheSize,
GetBlockIDAtHeight: vm.GetBlockIDAtHeight,
GetBlock: vm.getBlock,
UnmarshalBlock: vm.parseBlock,
BuildBlock: vm.buildBlock,
LastAcceptedBlock: block,
}
// Register chain state metrics
chainStateRegisterer := prometheus.NewRegistry()
state, err := chain.NewMeteredState(chainStateRegisterer, config)
if err != nil {
return fmt.Errorf("could not create metered state: %w", err)
}
vm.State = state
return vm.multiGatherer.Register(chainStateMetricsPrefix, chainStateRegisterer)
}
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 set.Set[ids.ID]
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))
size int
)
for {
tx, exists := vm.mempool.NextTx()
if !exists {
break
}
// Ensure that adding [tx] to the block will not exceed the block size soft limit.
txSize := len(tx.SignedBytes())
if size+txSize > targetAtomicTxsSize {
vm.mempool.CancelCurrentTx(tx.ID())
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)
size += txSize
}
// 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)
header = block.Header()
rules = vm.chainConfig.AvalancheRules(header.Number, new(big.Int).SetUint64(header.Time))
)
txs, err := ExtractAtomicTxs(block.ExtData(), rules.IsApricotPhase5, vm.codec)
if err != nil {
return nil, nil, err
}
// If [atomicBackend] is nil, the VM is still initializing and is reprocessing accepted blocks.
if vm.atomicBackend != nil {
if vm.atomicBackend.IsBonus(block.NumberU64(), block.Hash()) {
log.Info("skipping atomic tx verification on bonus block", "block", block.Hash())
} else {
// Verify [txs] do not conflict with themselves or ancestor blocks.
if err := vm.verifyTxs(txs, block.ParentHash(), block.BaseFee(), block.NumberU64(), rules); err != nil {
return nil, nil, err
}
}
// Update the atomic backend with [txs] from this block.
_, err := vm.atomicBackend.InsertTxs(block.Hash(), block.NumberU64(), block.ParentHash(), txs)
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 rules.IsApricotPhase4 {
contribution, gasUsed, err := tx.BlockFeeContribution(rules.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 rules.IsApricotPhase5 {
// 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) SetState(_ context.Context, state snow.State) error {
switch state {
case snow.StateSyncing:
vm.bootstrapped = false
return nil
case snow.Bootstrapping:
vm.bootstrapped = false
if err := vm.StateSyncClient.Error(); err != nil {
return err
}
return vm.fx.Bootstrapping()
case snow.NormalOp:
// Initialize goroutines related to block building once we enter normal operation as there is no need to handle mempool gossip before this point.
vm.initBlockBuilding()
vm.bootstrapped = true
return vm.fx.Bootstrapped()
default:
return snow.ErrUnknownState
}
}
// initBlockBuilding starts goroutines to manage block building
func (vm *VM) initBlockBuilding() {
// NOTE: gossip network must be initialized first otherwise ETH tx gossip will not work.
gossipStats := NewGossipStats()
vm.gossiper = vm.createGossiper(gossipStats)
vm.builder = vm.NewBlockBuilder(vm.toEngine)
vm.builder.awaitSubmittedTxs()
vm.Network.SetGossipHandler(NewGossipHandler(vm, gossipStats))
}
// setAppRequestHandlers sets the request handlers for the VM to serve state sync
// requests.
func (vm *VM) setAppRequestHandlers() {
// Create separate EVM TrieDB (read only) for serving leafs requests.
// We create a separate TrieDB here, so that it has a separate cache from the one
// used by the node when processing blocks.
evmTrieDB := trie.NewDatabaseWithConfig(
vm.chaindb,
&trie.Config{
Cache: vm.config.StateSyncServerTrieCache,
},
)
syncRequestHandler := handlers.NewSyncHandler(
vm.blockChain,
vm.chaindb,
evmTrieDB,
vm.atomicTrie.TrieDB(),
vm.networkCodec,
handlerstats.NewHandlerStats(metrics.Enabled),
)
vm.Network.SetRequestHandler(syncRequestHandler)
}
// setCrossChainAppRequestHandler sets the request handlers for the VM to serve cross chain
// requests.
func (vm *VM) setCrossChainAppRequestHandler() {
crossChainRequestHandler := message.NewCrossChainHandler(vm.eth.APIBackend, message.CrossChainCodec)
vm.Network.SetCrossChainRequestHandler(crossChainRequestHandler)
}
// Shutdown implements the snowman.ChainVM interface
func (vm *VM) Shutdown(context.Context) error {
if vm.ctx == nil {
return nil
}
vm.Network.Shutdown()
if err := vm.StateSyncClient.Shutdown(); err != nil {
log.Error("error stopping state syncer", "err", err)
}
close(vm.shutdownChan)
vm.eth.Stop()
vm.shutdownWg.Wait()
return nil
}
// buildBlock builds a block to be wrapped by ChainState
func (vm *VM) buildBlock(_ context.Context) (snowman.Block, error) {
block, err := vm.miner.GenerateBlock()
vm.builder.handleGenerateBlock()
if err != nil {
vm.mempool.CancelCurrentTxs()
return nil, err
}
// Note: the status of block is set by ChainState
blk, err := vm.newBlock(block)
if err != nil {
vm.mempool.DiscardCurrentTxs()