-
Notifications
You must be signed in to change notification settings - Fork 660
/
vm.go
523 lines (447 loc) · 13.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
// Copyright (C) 2019-2024, Ava Labs, Inc. All rights reserved.
// See the file LICENSE for licensing terms.
package platformvm
import (
"context"
"errors"
"fmt"
"math"
"net/http"
"time"
"github.com/gorilla/rpc/v2"
"go.uber.org/zap"
"github.com/ava-labs/avalanchego/api/metrics"
"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/ids"
"github.com/ava-labs/avalanchego/snow"
"github.com/ava-labs/avalanchego/snow/consensus/snowman"
"github.com/ava-labs/avalanchego/snow/engine/common"
"github.com/ava-labs/avalanchego/snow/uptime"
"github.com/ava-labs/avalanchego/snow/validators"
"github.com/ava-labs/avalanchego/utils"
"github.com/ava-labs/avalanchego/utils/constants"
"github.com/ava-labs/avalanchego/utils/json"
"github.com/ava-labs/avalanchego/utils/logging"
"github.com/ava-labs/avalanchego/utils/timer/mockable"
"github.com/ava-labs/avalanchego/version"
"github.com/ava-labs/avalanchego/vms/components/avax"
"github.com/ava-labs/avalanchego/vms/platformvm/block"
"github.com/ava-labs/avalanchego/vms/platformvm/config"
"github.com/ava-labs/avalanchego/vms/platformvm/fx"
"github.com/ava-labs/avalanchego/vms/platformvm/network"
"github.com/ava-labs/avalanchego/vms/platformvm/reward"
"github.com/ava-labs/avalanchego/vms/platformvm/state"
"github.com/ava-labs/avalanchego/vms/platformvm/txs"
"github.com/ava-labs/avalanchego/vms/platformvm/utxo"
"github.com/ava-labs/avalanchego/vms/secp256k1fx"
"github.com/ava-labs/avalanchego/vms/txs/mempool"
snowmanblock "github.com/ava-labs/avalanchego/snow/engine/snowman/block"
blockbuilder "github.com/ava-labs/avalanchego/vms/platformvm/block/builder"
blockexecutor "github.com/ava-labs/avalanchego/vms/platformvm/block/executor"
platformvmmetrics "github.com/ava-labs/avalanchego/vms/platformvm/metrics"
txexecutor "github.com/ava-labs/avalanchego/vms/platformvm/txs/executor"
pmempool "github.com/ava-labs/avalanchego/vms/platformvm/txs/mempool"
pvalidators "github.com/ava-labs/avalanchego/vms/platformvm/validators"
)
var (
_ snowmanblock.ChainVM = (*VM)(nil)
_ secp256k1fx.VM = (*VM)(nil)
_ validators.State = (*VM)(nil)
_ validators.SubnetConnector = (*VM)(nil)
)
type VM struct {
config.Config
blockbuilder.Builder
*network.Network
validators.State
metrics platformvmmetrics.Metrics
// Used to get time. Useful for faking time during tests.
clock mockable.Clock
uptimeManager uptime.Manager
// The context of this vm
ctx *snow.Context
db database.Database
state state.State
fx fx.Fx
codecRegistry codec.Registry
// Bootstrapped remembers if this chain has finished bootstrapping or not
bootstrapped utils.Atomic[bool]
manager blockexecutor.Manager
// Cancelled on shutdown
onShutdownCtx context.Context
// Call [onShutdownCtxCancel] to cancel [onShutdownCtx] during Shutdown()
onShutdownCtxCancel context.CancelFunc
}
// Initialize this blockchain.
// [vm.ChainManager] and [vm.vdrMgr] must be set before this function is called.
func (vm *VM) Initialize(
ctx context.Context,
chainCtx *snow.Context,
db database.Database,
genesisBytes []byte,
_ []byte,
configBytes []byte,
toEngine chan<- common.Message,
_ []*common.Fx,
appSender common.AppSender,
) error {
chainCtx.Log.Verbo("initializing platform chain")
execConfig, err := config.GetExecutionConfig(configBytes)
if err != nil {
return err
}
chainCtx.Log.Info("using VM execution config", zap.Reflect("config", execConfig))
registerer, err := metrics.MakeAndRegister(chainCtx.Metrics, "")
if err != nil {
return err
}
// Initialize metrics as soon as possible
vm.metrics, err = platformvmmetrics.New(registerer)
if err != nil {
return fmt.Errorf("failed to initialize metrics: %w", err)
}
vm.ctx = chainCtx
vm.db = db
// Note: this codec is never used to serialize anything
vm.codecRegistry = linearcodec.NewDefault()
vm.fx = &secp256k1fx.Fx{}
if err := vm.fx.Initialize(vm); err != nil {
return err
}
rewards := reward.NewCalculator(vm.RewardConfig)
vm.state, err = state.New(
vm.db,
genesisBytes,
registerer,
&vm.Config,
execConfig,
vm.ctx,
vm.metrics,
rewards,
)
if err != nil {
return err
}
validatorManager := pvalidators.NewManager(chainCtx.Log, vm.Config, vm.state, vm.metrics, &vm.clock)
vm.State = validatorManager
utxoVerifier := utxo.NewVerifier(vm.ctx, &vm.clock, vm.fx)
vm.uptimeManager = uptime.NewManager(vm.state, &vm.clock)
vm.UptimeLockedCalculator.SetCalculator(&vm.bootstrapped, &chainCtx.Lock, vm.uptimeManager)
txExecutorBackend := &txexecutor.Backend{
Config: &vm.Config,
Ctx: vm.ctx,
Clk: &vm.clock,
Fx: vm.fx,
FlowChecker: utxoVerifier,
Uptimes: vm.uptimeManager,
Rewards: rewards,
Bootstrapped: &vm.bootstrapped,
}
mempool, err := pmempool.New("mempool", registerer, toEngine)
if err != nil {
return fmt.Errorf("failed to create mempool: %w", err)
}
vm.manager = blockexecutor.NewManager(
mempool,
vm.metrics,
vm.state,
txExecutorBackend,
validatorManager,
)
txVerifier := network.NewLockedTxVerifier(&txExecutorBackend.Ctx.Lock, vm.manager)
vm.Network, err = network.New(
chainCtx.Log,
chainCtx.NodeID,
chainCtx.SubnetID,
validators.NewLockedState(
&chainCtx.Lock,
validatorManager,
),
txVerifier,
mempool,
txExecutorBackend.Config.PartialSyncPrimaryNetwork,
appSender,
registerer,
execConfig.Network,
)
if err != nil {
return fmt.Errorf("failed to initialize network: %w", err)
}
vm.onShutdownCtx, vm.onShutdownCtxCancel = context.WithCancel(context.Background())
// TODO: Wait for this goroutine to exit during Shutdown once the platformvm
// has better control of the context lock.
go vm.Network.PushGossip(vm.onShutdownCtx)
go vm.Network.PullGossip(vm.onShutdownCtx)
vm.Builder = blockbuilder.New(
mempool,
txExecutorBackend,
vm.manager,
)
// Create all of the chains that the database says exist
if err := vm.initBlockchains(); err != nil {
return fmt.Errorf(
"failed to initialize blockchains: %w",
err,
)
}
lastAcceptedID := vm.state.GetLastAccepted()
chainCtx.Log.Info("initializing last accepted",
zap.Stringer("blkID", lastAcceptedID),
)
if err := vm.SetPreference(ctx, lastAcceptedID); err != nil {
return err
}
// Incrementing [awaitShutdown] would cause a deadlock since
// [periodicallyPruneMempool] grabs the context lock.
go vm.periodicallyPruneMempool(execConfig.MempoolPruneFrequency)
go func() {
err := vm.state.ReindexBlocks(&vm.ctx.Lock, vm.ctx.Log)
if err != nil {
vm.ctx.Log.Warn("reindexing blocks failed",
zap.Error(err),
)
}
}()
return nil
}
func (vm *VM) periodicallyPruneMempool(frequency time.Duration) {
ticker := time.NewTicker(frequency)
defer ticker.Stop()
for {
select {
case <-vm.onShutdownCtx.Done():
return
case <-ticker.C:
if err := vm.pruneMempool(); err != nil {
vm.ctx.Log.Debug("pruning mempool failed",
zap.Error(err),
)
}
}
}
}
func (vm *VM) pruneMempool() error {
vm.ctx.Lock.Lock()
defer vm.ctx.Lock.Unlock()
// Packing all of the transactions in order performs additional checks that
// the MempoolTxVerifier doesn't include. So, evicting transactions from
// here is expected to happen occasionally.
blockTxs, err := vm.Builder.PackBlockTxs(math.MaxInt)
if err != nil {
return err
}
for _, tx := range blockTxs {
if err := vm.Builder.Add(tx); err != nil {
vm.ctx.Log.Debug(
"failed to reissue tx",
zap.Stringer("txID", tx.ID()),
zap.Error(err),
)
}
}
return nil
}
// Create all chains that exist that this node validates.
func (vm *VM) initBlockchains() error {
if vm.Config.PartialSyncPrimaryNetwork {
vm.ctx.Log.Info("skipping primary network chain creation")
} else if err := vm.createSubnet(constants.PrimaryNetworkID); err != nil {
return err
}
if vm.SybilProtectionEnabled {
for subnetID := range vm.TrackedSubnets {
if err := vm.createSubnet(subnetID); err != nil {
return err
}
}
} else {
subnetIDs, err := vm.state.GetSubnetIDs()
if err != nil {
return err
}
for _, subnetID := range subnetIDs {
if err := vm.createSubnet(subnetID); err != nil {
return err
}
}
}
return nil
}
// Create the subnet with ID [subnetID]
func (vm *VM) createSubnet(subnetID ids.ID) error {
chains, err := vm.state.GetChains(subnetID)
if err != nil {
return err
}
for _, chain := range chains {
tx, ok := chain.Unsigned.(*txs.CreateChainTx)
if !ok {
return fmt.Errorf("expected tx type *txs.CreateChainTx but got %T", chain.Unsigned)
}
vm.Config.CreateChain(chain.ID(), tx)
}
return nil
}
// onBootstrapStarted marks this VM as bootstrapping
func (vm *VM) onBootstrapStarted() error {
vm.bootstrapped.Set(false)
return vm.fx.Bootstrapping()
}
// onNormalOperationsStarted marks this VM as bootstrapped
func (vm *VM) onNormalOperationsStarted() error {
if vm.bootstrapped.Get() {
return nil
}
vm.bootstrapped.Set(true)
if err := vm.fx.Bootstrapped(); err != nil {
return err
}
primaryVdrIDs := vm.Validators.GetValidatorIDs(constants.PrimaryNetworkID)
if err := vm.uptimeManager.StartTracking(primaryVdrIDs, constants.PrimaryNetworkID); err != nil {
return err
}
vl := validators.NewLogger(vm.ctx.Log, constants.PrimaryNetworkID, vm.ctx.NodeID)
vm.Validators.RegisterSetCallbackListener(constants.PrimaryNetworkID, vl)
for subnetID := range vm.TrackedSubnets {
vdrIDs := vm.Validators.GetValidatorIDs(subnetID)
if err := vm.uptimeManager.StartTracking(vdrIDs, subnetID); err != nil {
return err
}
vl := validators.NewLogger(vm.ctx.Log, subnetID, vm.ctx.NodeID)
vm.Validators.RegisterSetCallbackListener(subnetID, vl)
}
if err := vm.state.Commit(); err != nil {
return err
}
// Start the block builder
vm.Builder.StartBlockTimer()
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
}
}
// Shutdown this blockchain
func (vm *VM) Shutdown(context.Context) error {
if vm.db == nil {
return nil
}
vm.onShutdownCtxCancel()
vm.Builder.ShutdownBlockTimer()
if vm.bootstrapped.Get() {
primaryVdrIDs := vm.Validators.GetValidatorIDs(constants.PrimaryNetworkID)
if err := vm.uptimeManager.StopTracking(primaryVdrIDs, constants.PrimaryNetworkID); err != nil {
return err
}
for subnetID := range vm.TrackedSubnets {
vdrIDs := vm.Validators.GetValidatorIDs(subnetID)
if err := vm.uptimeManager.StopTracking(vdrIDs, subnetID); err != nil {
return err
}
}
if err := vm.state.Commit(); err != nil {
return err
}
}
return errors.Join(
vm.state.Close(),
vm.db.Close(),
)
}
func (vm *VM) ParseBlock(_ context.Context, b []byte) (snowman.Block, error) {
// Note: blocks to be parsed are not verified, so we must used blocks.Codec
// rather than blocks.GenesisCodec
statelessBlk, err := block.Parse(block.Codec, b)
if err != nil {
return nil, err
}
return vm.manager.NewBlock(statelessBlk), nil
}
func (vm *VM) GetBlock(_ context.Context, blkID ids.ID) (snowman.Block, error) {
return vm.manager.GetBlock(blkID)
}
// LastAccepted returns the block most recently accepted
func (vm *VM) LastAccepted(context.Context) (ids.ID, error) {
return vm.manager.LastAccepted(), nil
}
// SetPreference sets the preferred block to be the one with ID [blkID]
func (vm *VM) SetPreference(_ context.Context, blkID ids.ID) error {
if vm.manager.SetPreference(blkID) {
vm.Builder.ResetBlockTimer()
}
return nil
}
func (*VM) Version(context.Context) (string, error) {
return version.Current.String(), nil
}
// CreateHandlers returns a map where:
// * keys are API endpoint extensions
// * values are API handlers
func (vm *VM) CreateHandlers(context.Context) (map[string]http.Handler, error) {
server := rpc.NewServer()
server.RegisterCodec(json.NewCodec(), "application/json")
server.RegisterCodec(json.NewCodec(), "application/json;charset=UTF-8")
server.RegisterInterceptFunc(vm.metrics.InterceptRequest)
server.RegisterAfterFunc(vm.metrics.AfterRequest)
service := &Service{
vm: vm,
addrManager: avax.NewAddressManager(vm.ctx),
stakerAttributesCache: &cache.LRU[ids.ID, *stakerAttributes]{
Size: stakerAttributesCacheSize,
},
}
err := server.RegisterService(service, "platform")
return map[string]http.Handler{
"": server,
}, err
}
func (vm *VM) Connected(ctx context.Context, nodeID ids.NodeID, version *version.Application) error {
if err := vm.uptimeManager.Connect(nodeID, constants.PrimaryNetworkID); err != nil {
return err
}
return vm.Network.Connected(ctx, nodeID, version)
}
func (vm *VM) ConnectedSubnet(_ context.Context, nodeID ids.NodeID, subnetID ids.ID) error {
return vm.uptimeManager.Connect(nodeID, subnetID)
}
func (vm *VM) Disconnected(ctx context.Context, nodeID ids.NodeID) error {
if err := vm.uptimeManager.Disconnect(nodeID); err != nil {
return err
}
if err := vm.state.Commit(); err != nil {
return err
}
return vm.Network.Disconnected(ctx, nodeID)
}
func (vm *VM) CodecRegistry() codec.Registry {
return vm.codecRegistry
}
func (vm *VM) Clock() *mockable.Clock {
return &vm.clock
}
func (vm *VM) Logger() logging.Logger {
return vm.ctx.Log
}
func (vm *VM) GetBlockIDAtHeight(_ context.Context, height uint64) (ids.ID, error) {
return vm.state.GetBlockIDAtHeight(height)
}
func (vm *VM) issueTxFromRPC(tx *txs.Tx) error {
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", tx.ID()),
zap.Error(err),
)
return err
}
return nil
}