forked from ava-labs/avalanchego
-
Notifications
You must be signed in to change notification settings - Fork 4
/
vm.go
702 lines (593 loc) · 18.5 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
// Copyright (C) 2019-2024, Ava Labs, Inc. All rights reserved.
// See the file LICENSE for licensing terms.
package avm
import (
"context"
"errors"
"fmt"
"net/http"
"reflect"
"sync"
"github.com/gorilla/rpc/v2"
"github.com/prometheus/client_golang/prometheus"
"go.uber.org/zap"
"github.com/MetalBlockchain/metalgo/cache"
"github.com/MetalBlockchain/metalgo/database"
"github.com/MetalBlockchain/metalgo/database/versiondb"
"github.com/MetalBlockchain/metalgo/ids"
"github.com/MetalBlockchain/metalgo/pubsub"
"github.com/MetalBlockchain/metalgo/snow"
"github.com/MetalBlockchain/metalgo/snow/consensus/snowman"
"github.com/MetalBlockchain/metalgo/snow/consensus/snowstorm"
"github.com/MetalBlockchain/metalgo/snow/engine/avalanche/vertex"
"github.com/MetalBlockchain/metalgo/snow/engine/common"
"github.com/MetalBlockchain/metalgo/utils"
"github.com/MetalBlockchain/metalgo/utils/json"
"github.com/MetalBlockchain/metalgo/utils/linkedhashmap"
"github.com/MetalBlockchain/metalgo/utils/set"
"github.com/MetalBlockchain/metalgo/utils/timer/mockable"
"github.com/MetalBlockchain/metalgo/version"
"github.com/MetalBlockchain/metalgo/vms/avm/block"
"github.com/MetalBlockchain/metalgo/vms/avm/config"
"github.com/MetalBlockchain/metalgo/vms/avm/metrics"
"github.com/MetalBlockchain/metalgo/vms/avm/network"
"github.com/MetalBlockchain/metalgo/vms/avm/state"
"github.com/MetalBlockchain/metalgo/vms/avm/txs"
"github.com/MetalBlockchain/metalgo/vms/avm/txs/mempool"
"github.com/MetalBlockchain/metalgo/vms/avm/utxo"
"github.com/MetalBlockchain/metalgo/vms/components/avax"
"github.com/MetalBlockchain/metalgo/vms/components/index"
"github.com/MetalBlockchain/metalgo/vms/components/keystore"
"github.com/MetalBlockchain/metalgo/vms/secp256k1fx"
blockbuilder "github.com/MetalBlockchain/metalgo/vms/avm/block/builder"
blockexecutor "github.com/MetalBlockchain/metalgo/vms/avm/block/executor"
extensions "github.com/MetalBlockchain/metalgo/vms/avm/fxs"
txexecutor "github.com/MetalBlockchain/metalgo/vms/avm/txs/executor"
)
const assetToFxCacheSize = 1024
var (
errIncompatibleFx = errors.New("incompatible feature extension")
errUnknownFx = errors.New("unknown feature extension")
errGenesisAssetMustHaveState = errors.New("genesis asset must have non-empty state")
_ vertex.LinearizableVMWithEngine = (*VM)(nil)
)
type VM struct {
network.Atomic
config.Config
metrics metrics.Metrics
avax.AddressManager
avax.AtomicUTXOManager
ids.Aliaser
utxo.Spender
// Contains information of where this VM is executing
ctx *snow.Context
// Used to check local time
clock mockable.Clock
registerer prometheus.Registerer
connectedPeers map[ids.NodeID]*version.Application
parser block.Parser
pubsub *pubsub.Server
appSender common.AppSender
// State management
state state.State
// Set to true once this VM is marked as `Bootstrapped` by the engine
bootstrapped bool
// asset id that will be used for fees
feeAssetID ids.ID
// Asset ID --> Bit set with fx IDs the asset supports
assetToFxCache *cache.LRU[ids.ID, set.Bits64]
baseDB database.Database
db *versiondb.Database
typeToFxIndex map[reflect.Type]int
fxs []*extensions.ParsedFx
walletService WalletService
addressTxsIndexer index.AddressTxsIndexer
txBackend *txexecutor.Backend
// Cancelled on shutdown
onShutdownCtx context.Context
// Call [onShutdownCtxCancel] to cancel [onShutdownCtx] during Shutdown()
onShutdownCtxCancel context.CancelFunc
awaitShutdown sync.WaitGroup
networkConfig network.Config
// These values are only initialized after the chain has been linearized.
blockbuilder.Builder
chainManager blockexecutor.Manager
network *network.Network
}
func (vm *VM) Connected(ctx context.Context, nodeID ids.NodeID, version *version.Application) error {
// If the chain isn't linearized yet, we must track the peers externally
// until the network is initialized.
if vm.network == nil {
vm.connectedPeers[nodeID] = version
return nil
}
return vm.network.Connected(ctx, nodeID, version)
}
func (vm *VM) Disconnected(ctx context.Context, nodeID ids.NodeID) error {
// If the chain isn't linearized yet, we must track the peers externally
// until the network is initialized.
if vm.network == nil {
delete(vm.connectedPeers, nodeID)
return nil
}
return vm.network.Disconnected(ctx, nodeID)
}
/*
******************************************************************************
********************************* Common VM **********************************
******************************************************************************
*/
func (vm *VM) Initialize(
_ context.Context,
ctx *snow.Context,
db database.Database,
genesisBytes []byte,
_ []byte,
configBytes []byte,
_ chan<- common.Message,
fxs []*common.Fx,
appSender common.AppSender,
) error {
noopMessageHandler := common.NewNoOpAppHandler(ctx.Log)
vm.Atomic = network.NewAtomic(noopMessageHandler)
avmConfig, err := ParseConfig(configBytes)
if err != nil {
return err
}
ctx.Log.Info("VM config initialized",
zap.Reflect("config", avmConfig),
)
registerer := prometheus.NewRegistry()
if err := ctx.Metrics.Register(registerer); err != nil {
return err
}
vm.registerer = registerer
vm.connectedPeers = make(map[ids.NodeID]*version.Application)
// Initialize metrics as soon as possible
vm.metrics, err = metrics.New("", registerer)
if err != nil {
return fmt.Errorf("failed to initialize metrics: %w", err)
}
vm.AddressManager = avax.NewAddressManager(ctx)
vm.Aliaser = ids.NewAliaser()
vm.ctx = ctx
vm.appSender = appSender
vm.baseDB = db
vm.db = versiondb.New(db)
vm.assetToFxCache = &cache.LRU[ids.ID, set.Bits64]{Size: assetToFxCacheSize}
vm.pubsub = pubsub.New(ctx.Log)
typedFxs := make([]extensions.Fx, len(fxs))
vm.fxs = make([]*extensions.ParsedFx, len(fxs))
for i, fxContainer := range fxs {
if fxContainer == nil {
return errIncompatibleFx
}
fx, ok := fxContainer.Fx.(extensions.Fx)
if !ok {
return errIncompatibleFx
}
typedFxs[i] = fx
vm.fxs[i] = &extensions.ParsedFx{
ID: fxContainer.ID,
Fx: fx,
}
}
vm.typeToFxIndex = map[reflect.Type]int{}
vm.parser, err = block.NewCustomParser(
vm.DurangoTime,
vm.typeToFxIndex,
&vm.clock,
ctx.Log,
typedFxs,
)
if err != nil {
return err
}
codec := vm.parser.Codec()
vm.AtomicUTXOManager = avax.NewAtomicUTXOManager(ctx.SharedMemory, codec)
vm.Spender = utxo.NewSpender(&vm.clock, codec)
state, err := state.New(
vm.db,
vm.parser,
vm.registerer,
avmConfig.ChecksumsEnabled,
)
if err != nil {
return err
}
vm.state = state
if err := vm.initGenesis(genesisBytes); err != nil {
return err
}
vm.walletService.vm = vm
vm.walletService.pendingTxs = linkedhashmap.New[ids.ID, *txs.Tx]()
// use no op impl when disabled in config
if avmConfig.IndexTransactions {
vm.ctx.Log.Warn("deprecated address transaction indexing is enabled")
vm.addressTxsIndexer, err = index.NewIndexer(vm.db, vm.ctx.Log, "", vm.registerer, avmConfig.IndexAllowIncomplete)
if err != nil {
return fmt.Errorf("failed to initialize address transaction indexer: %w", err)
}
} else {
vm.ctx.Log.Info("address transaction indexing is disabled")
vm.addressTxsIndexer, err = index.NewNoIndexer(vm.db, avmConfig.IndexAllowIncomplete)
if err != nil {
return fmt.Errorf("failed to initialize disabled indexer: %w", err)
}
}
vm.txBackend = &txexecutor.Backend{
Ctx: ctx,
Config: &vm.Config,
Fxs: vm.fxs,
TypeToFxIndex: vm.typeToFxIndex,
Codec: vm.parser.Codec(),
FeeAssetID: vm.feeAssetID,
Bootstrapped: false,
}
vm.onShutdownCtx, vm.onShutdownCtxCancel = context.WithCancel(context.Background())
vm.networkConfig = avmConfig.Network
return vm.state.Commit()
}
// onBootstrapStarted is called by the consensus engine when it starts bootstrapping this chain
func (vm *VM) onBootstrapStarted() error {
vm.txBackend.Bootstrapped = false
for _, fx := range vm.fxs {
if err := fx.Fx.Bootstrapping(); err != nil {
return err
}
}
return nil
}
func (vm *VM) onNormalOperationsStarted() error {
vm.txBackend.Bootstrapped = true
for _, fx := range vm.fxs {
if err := fx.Fx.Bootstrapped(); err != nil {
return err
}
}
vm.bootstrapped = true
return nil
}
func (vm *VM) SetState(_ context.Context, state snow.State) error {
switch state {
case snow.Bootstrapping:
return vm.onBootstrapStarted()
case snow.NormalOp:
return vm.onNormalOperationsStarted()
default:
return snow.ErrUnknownState
}
}
func (vm *VM) Shutdown(context.Context) error {
if vm.state == nil {
return nil
}
vm.onShutdownCtxCancel()
vm.awaitShutdown.Wait()
return utils.Err(
vm.state.Close(),
vm.baseDB.Close(),
)
}
func (*VM) Version(context.Context) (string, error) {
return version.Current.String(), nil
}
func (vm *VM) CreateHandlers(context.Context) (map[string]http.Handler, error) {
codec := json.NewCodec()
rpcServer := rpc.NewServer()
rpcServer.RegisterCodec(codec, "application/json")
rpcServer.RegisterCodec(codec, "application/json;charset=UTF-8")
rpcServer.RegisterInterceptFunc(vm.metrics.InterceptRequest)
rpcServer.RegisterAfterFunc(vm.metrics.AfterRequest)
// name this service "avm"
if err := rpcServer.RegisterService(&Service{vm: vm}, "avm"); err != nil {
return nil, err
}
walletServer := rpc.NewServer()
walletServer.RegisterCodec(codec, "application/json")
walletServer.RegisterCodec(codec, "application/json;charset=UTF-8")
walletServer.RegisterInterceptFunc(vm.metrics.InterceptRequest)
walletServer.RegisterAfterFunc(vm.metrics.AfterRequest)
// name this service "wallet"
err := walletServer.RegisterService(&vm.walletService, "wallet")
return map[string]http.Handler{
"": rpcServer,
"/wallet": walletServer,
"/events": vm.pubsub,
}, err
}
/*
******************************************************************************
********************************** Chain VM **********************************
******************************************************************************
*/
func (vm *VM) GetBlock(_ context.Context, blkID ids.ID) (snowman.Block, error) {
return vm.chainManager.GetBlock(blkID)
}
func (vm *VM) ParseBlock(_ context.Context, blkBytes []byte) (snowman.Block, error) {
blk, err := vm.parser.ParseBlock(blkBytes)
if err != nil {
return nil, err
}
return vm.chainManager.NewBlock(blk), nil
}
func (vm *VM) SetPreference(_ context.Context, blkID ids.ID) error {
vm.chainManager.SetPreference(blkID)
return nil
}
func (vm *VM) LastAccepted(context.Context) (ids.ID, error) {
return vm.chainManager.LastAccepted(), nil
}
func (vm *VM) GetBlockIDAtHeight(_ context.Context, height uint64) (ids.ID, error) {
return vm.state.GetBlockIDAtHeight(height)
}
func (*VM) VerifyHeightIndex(context.Context) error {
return nil
}
/*
******************************************************************************
*********************************** DAG VM ***********************************
******************************************************************************
*/
func (vm *VM) Linearize(ctx context.Context, stopVertexID ids.ID, toEngine chan<- common.Message) error {
time := version.GetCortinaTime(vm.ctx.NetworkID)
err := vm.state.InitializeChainState(stopVertexID, time)
if err != nil {
return err
}
mempool, err := mempool.New("mempool", vm.registerer, toEngine)
if err != nil {
return fmt.Errorf("failed to create mempool: %w", err)
}
vm.chainManager = blockexecutor.NewManager(
mempool,
vm.metrics,
vm.state,
vm.txBackend,
&vm.clock,
vm.onAccept,
)
vm.Builder = blockbuilder.New(
vm.txBackend,
vm.chainManager,
&vm.clock,
mempool,
)
// Invariant: The context lock is not held when calling network.IssueTx.
vm.network, err = network.New(
vm.ctx,
vm.parser,
network.NewLockedTxVerifier(
&vm.ctx.Lock,
vm.chainManager,
),
mempool,
vm.appSender,
vm.registerer,
vm.networkConfig,
)
if err != nil {
return fmt.Errorf("failed to initialize network: %w", err)
}
// Notify the network of our current peers
for nodeID, version := range vm.connectedPeers {
if err := vm.network.Connected(ctx, nodeID, version); err != nil {
return err
}
}
vm.connectedPeers = nil
// Note: It's important only to switch the networking stack after the full
// chainVM has been initialized. Traffic will immediately start being
// handled asynchronously.
vm.Atomic.Set(vm.network)
vm.awaitShutdown.Add(2)
go func() {
defer vm.awaitShutdown.Done()
// Invariant: PushGossip must never grab the context lock.
vm.network.PushGossip(vm.onShutdownCtx)
}()
go func() {
defer vm.awaitShutdown.Done()
// Invariant: PullGossip must never grab the context lock.
vm.network.PullGossip(vm.onShutdownCtx)
}()
go func() {
err := vm.state.Prune(&vm.ctx.Lock, vm.ctx.Log)
if err != nil {
vm.ctx.Log.Warn("state pruning failed",
zap.Error(err),
)
return
}
vm.ctx.Log.Info("state pruning finished")
}()
return nil
}
func (vm *VM) ParseTx(_ context.Context, bytes []byte) (snowstorm.Tx, error) {
tx, err := vm.parser.ParseTx(bytes)
if err != nil {
return nil, err
}
err = tx.Unsigned.Visit(&txexecutor.SyntacticVerifier{
Backend: vm.txBackend,
Tx: tx,
})
if err != nil {
return nil, err
}
return &Tx{
vm: vm,
tx: tx,
}, nil
}
/*
******************************************************************************
********************************** JSON API **********************************
******************************************************************************
*/
// issueTxFromRPC attempts to send a transaction to consensus.
//
// Invariant: The context lock is not held
// Invariant: This function is only called after Linearize has been called.
func (vm *VM) issueTxFromRPC(tx *txs.Tx) (ids.ID, error) {
txID := tx.ID()
err := vm.network.IssueTxFromRPC(tx)
if err != nil && !errors.Is(err, mempool.ErrDuplicateTx) {
vm.ctx.Log.Debug("failed to add tx to mempool",
zap.Stringer("txID", txID),
zap.Error(err),
)
return txID, err
}
return txID, nil
}
/*
******************************************************************************
********************************** Helpers ***********************************
******************************************************************************
*/
func (vm *VM) initGenesis(genesisBytes []byte) error {
genesisCodec := vm.parser.GenesisCodec()
genesis := Genesis{}
if _, err := genesisCodec.Unmarshal(genesisBytes, &genesis); err != nil {
return err
}
stateInitialized, err := vm.state.IsInitialized()
if err != nil {
return err
}
// secure this by defaulting to avaxAsset
vm.feeAssetID = vm.ctx.AVAXAssetID
for index, genesisTx := range genesis.Txs {
if len(genesisTx.Outs) != 0 {
return errGenesisAssetMustHaveState
}
tx := &txs.Tx{
Unsigned: &genesisTx.CreateAssetTx,
}
if err := tx.Initialize(genesisCodec); err != nil {
return err
}
txID := tx.ID()
if err := vm.Alias(txID, genesisTx.Alias); err != nil {
return err
}
if !stateInitialized {
vm.initState(tx)
}
if index == 0 {
vm.ctx.Log.Info("fee asset is established",
zap.String("alias", genesisTx.Alias),
zap.Stringer("assetID", txID),
)
vm.feeAssetID = txID
}
}
if !stateInitialized {
return vm.state.SetInitialized()
}
return nil
}
func (vm *VM) initState(tx *txs.Tx) {
txID := tx.ID()
vm.ctx.Log.Info("initializing genesis asset",
zap.Stringer("txID", txID),
)
vm.state.AddTx(tx)
for _, utxo := range tx.UTXOs() {
vm.state.AddUTXO(utxo)
}
}
// LoadUser returns:
// 1) The UTXOs that reference one or more addresses controlled by the given user
// 2) A keychain that contains this user's keys
// If [addrsToUse] has positive length, returns UTXOs that reference one or more
// addresses controlled by the given user that are also in [addrsToUse].
func (vm *VM) LoadUser(
username string,
password string,
addrsToUse set.Set[ids.ShortID],
) (
[]*avax.UTXO,
*secp256k1fx.Keychain,
error,
) {
user, err := keystore.NewUserFromKeystore(vm.ctx.Keystore, username, password)
if err != nil {
return nil, nil, err
}
// Drop any potential error closing the database to report the original
// error
defer user.Close()
kc, err := keystore.GetKeychain(user, addrsToUse)
if err != nil {
return nil, nil, err
}
utxos, err := avax.GetAllUTXOs(vm.state, kc.Addresses())
if err != nil {
return nil, nil, fmt.Errorf("problem retrieving user's UTXOs: %w", err)
}
return utxos, kc, user.Close()
}
// selectChangeAddr returns the change address to be used for [kc] when [changeAddr] is given
// as the optional change address argument
func (vm *VM) selectChangeAddr(defaultAddr ids.ShortID, changeAddr string) (ids.ShortID, error) {
if changeAddr == "" {
return defaultAddr, nil
}
addr, err := avax.ParseServiceAddress(vm, changeAddr)
if err != nil {
return ids.ShortID{}, fmt.Errorf("couldn't parse changeAddr: %w", err)
}
return addr, nil
}
// lookupAssetID looks for an ID aliased by [asset] and if it fails
// attempts to parse [asset] into an ID
func (vm *VM) lookupAssetID(asset string) (ids.ID, error) {
if assetID, err := vm.Lookup(asset); err == nil {
return assetID, nil
}
if assetID, err := ids.FromString(asset); err == nil {
return assetID, nil
}
return ids.ID{}, fmt.Errorf("asset '%s' not found", asset)
}
// Invariant: onAccept is called when [tx] is being marked as accepted, but
// before its state changes are applied.
// Invariant: any error returned by onAccept should be considered fatal.
// TODO: Remove [onAccept] once the deprecated APIs this powers are removed.
func (vm *VM) onAccept(tx *txs.Tx) error {
// Fetch the input UTXOs
txID := tx.ID()
inputUTXOIDs := tx.Unsigned.InputUTXOs()
inputUTXOs := make([]*avax.UTXO, 0, len(inputUTXOIDs))
for _, utxoID := range inputUTXOIDs {
// Don't bother fetching the input UTXO if its symbolic
if utxoID.Symbolic() {
continue
}
utxo, err := vm.state.GetUTXO(utxoID.InputID())
if err == database.ErrNotFound {
vm.ctx.Log.Debug("dropping utxo from index",
zap.Stringer("txID", txID),
zap.Stringer("utxoTxID", utxoID.TxID),
zap.Uint32("utxoOutputIndex", utxoID.OutputIndex),
)
continue
}
if err != nil {
// should never happen because the UTXO was previously verified to
// exist
return fmt.Errorf("error finding UTXO %s: %w", utxoID, err)
}
inputUTXOs = append(inputUTXOs, utxo)
}
outputUTXOs := tx.UTXOs()
// index input and output UTXOs
if err := vm.addressTxsIndexer.Accept(txID, inputUTXOs, outputUTXOs); err != nil {
return fmt.Errorf("error indexing tx: %w", err)
}
vm.pubsub.Publish(NewPubSubFilterer(tx))
vm.walletService.decided(txID)
return nil
}