-
Notifications
You must be signed in to change notification settings - Fork 658
/
vm.go
625 lines (537 loc) · 16.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
// Copyright (C) 2019-2022, Ava Labs, Inc. All rights reserved.
// See the file LICENSE for licensing terms.
package platformvm
import (
"errors"
"fmt"
"time"
"github.com/gorilla/rpc/v2"
"github.com/prometheus/client_golang/prometheus"
"go.uber.org/zap"
"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/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/engine/snowman/block"
"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/math"
"github.com/ava-labs/avalanchego/utils/timer/mockable"
"github.com/ava-labs/avalanchego/utils/window"
"github.com/ava-labs/avalanchego/utils/wrappers"
"github.com/ava-labs/avalanchego/version"
"github.com/ava-labs/avalanchego/vms/components/avax"
"github.com/ava-labs/avalanchego/vms/platformvm/api"
"github.com/ava-labs/avalanchego/vms/platformvm/blocks"
"github.com/ava-labs/avalanchego/vms/platformvm/fx"
"github.com/ava-labs/avalanchego/vms/platformvm/metrics"
"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/txs/mempool"
"github.com/ava-labs/avalanchego/vms/platformvm/utxo"
"github.com/ava-labs/avalanchego/vms/secp256k1fx"
blockbuilder "github.com/ava-labs/avalanchego/vms/platformvm/blocks/builder"
blockexecutor "github.com/ava-labs/avalanchego/vms/platformvm/blocks/executor"
txbuilder "github.com/ava-labs/avalanchego/vms/platformvm/txs/builder"
txexecutor "github.com/ava-labs/avalanchego/vms/platformvm/txs/executor"
)
const (
validatorSetsCacheSize = 64
maxRecentlyAcceptedWindowSize = 256
recentlyAcceptedWindowTTL = 5 * time.Minute
)
var (
_ block.ChainVM = (*VM)(nil)
_ secp256k1fx.VM = (*VM)(nil)
_ validators.State = (*VM)(nil)
errWrongCacheType = errors.New("unexpectedly cached type")
errMissingValidatorSet = errors.New("missing validator set")
)
type VM struct {
Factory
blockbuilder.Builder
metrics metrics.Metrics
atomicUtxosManager avax.AtomicUTXOManager
// Used to get time. Useful for faking time during tests.
clock mockable.Clock
uptimeManager uptime.Manager
// The context of this vm
ctx *snow.Context
dbManager manager.Manager
state state.State
fx fx.Fx
codecRegistry codec.Registry
// Bootstrapped remembers if this chain has finished bootstrapping or not
bootstrapped utils.AtomicBool
// Maps caches for each subnet that is currently whitelisted.
// Key: Subnet ID
// Value: cache mapping height -> validator set map
validatorSetCaches map[ids.ID]cache.Cacher
// sliding window of blocks that were recently accepted
recentlyAccepted window.Window[ids.ID]
txBuilder txbuilder.Builder
txExecutorBackend *txexecutor.Backend
manager blockexecutor.Manager
}
// Initialize this blockchain.
// [vm.ChainManager] and [vm.vdrMgr] must be set before this function is called.
func (vm *VM) Initialize(
ctx *snow.Context,
dbManager manager.Manager,
genesisBytes []byte,
upgradeBytes []byte,
configBytes []byte,
toEngine chan<- common.Message,
_ []*common.Fx,
appSender common.AppSender,
) error {
ctx.Log.Verbo("initializing platform chain")
registerer := prometheus.NewRegistry()
if err := ctx.Metrics.Register(registerer); err != nil {
return err
}
// Initialize metrics as soon as possible
var err error
vm.metrics, err = metrics.New("", registerer, vm.WhitelistedSubnets)
if err != nil {
return fmt.Errorf("failed to initialize metrics: %w", err)
}
vm.ctx = ctx
vm.dbManager = dbManager
vm.codecRegistry = linearcodec.NewDefault()
vm.fx = &secp256k1fx.Fx{}
if err := vm.fx.Initialize(vm); err != nil {
return err
}
vm.validatorSetCaches = make(map[ids.ID]cache.Cacher)
vm.recentlyAccepted = window.New[ids.ID](
window.Config{
Clock: &vm.clock,
MaxSize: maxRecentlyAcceptedWindowSize,
TTL: recentlyAcceptedWindowTTL,
},
)
rewards := reward.NewCalculator(vm.RewardConfig)
vm.state, err = state.New(
vm.dbManager.Current().Database,
genesisBytes,
registerer,
&vm.Config,
vm.ctx,
vm.metrics,
rewards,
)
if err != nil {
return err
}
vm.atomicUtxosManager = avax.NewAtomicUTXOManager(ctx.SharedMemory, txs.Codec)
utxoHandler := utxo.NewHandler(vm.ctx, &vm.clock, vm.state, vm.fx)
vm.uptimeManager = uptime.NewManager(vm.state)
vm.UptimeLockedCalculator.SetCalculator(&vm.bootstrapped, &ctx.Lock, vm.uptimeManager)
vm.txBuilder = txbuilder.New(
vm.ctx,
&vm.Config,
&vm.clock,
vm.fx,
vm.state,
vm.atomicUtxosManager,
utxoHandler,
)
vm.txExecutorBackend = &txexecutor.Backend{
Config: &vm.Config,
Ctx: vm.ctx,
Clk: &vm.clock,
Fx: vm.fx,
FlowChecker: utxoHandler,
Uptimes: vm.uptimeManager,
Rewards: rewards,
Bootstrapped: &vm.bootstrapped,
}
// Note: There is a circular dependency between the mempool and block
// builder which is broken by passing in the vm.
mempool, err := mempool.NewMempool("mempool", registerer, vm)
if err != nil {
return fmt.Errorf("failed to create mempool: %w", err)
}
vm.manager = blockexecutor.NewManager(
mempool,
vm.metrics,
vm.state,
vm.txExecutorBackend,
vm.recentlyAccepted,
)
vm.Builder = blockbuilder.New(
mempool,
vm.txBuilder,
vm.txExecutorBackend,
vm.manager,
toEngine,
appSender,
)
if err := vm.updateValidators(); err != nil {
return fmt.Errorf("failed to update validator sets: %w", err)
}
// 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()
ctx.Log.Info("initializing last accepted",
zap.Stringer("blkID", lastAcceptedID),
)
return vm.SetPreference(lastAcceptedID)
}
// Create all chains that exist that this node validates.
func (vm *VM) initBlockchains() error {
if err := vm.createSubnet(constants.PrimaryNetworkID); err != nil {
return err
}
if vm.StakingEnabled {
for subnetID := range vm.WhitelistedSubnets {
if err := vm.createSubnet(subnetID); err != nil {
return err
}
}
} else {
subnets, err := vm.state.GetSubnets()
if err != nil {
return err
}
for _, subnet := range subnets {
if err := vm.createSubnet(subnet.ID()); 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.SetValue(false)
return vm.fx.Bootstrapping()
}
// onNormalOperationsStarted marks this VM as bootstrapped
func (vm *VM) onNormalOperationsStarted() error {
if vm.bootstrapped.GetValue() {
return nil
}
vm.bootstrapped.SetValue(true)
if err := vm.fx.Bootstrapped(); err != nil {
return err
}
primaryValidatorSet, exist := vm.Validators.GetValidators(constants.PrimaryNetworkID)
if !exist {
return errNoPrimaryValidators
}
primaryValidators := primaryValidatorSet.List()
validatorIDs := make([]ids.NodeID, len(primaryValidators))
for i, vdr := range primaryValidators {
validatorIDs[i] = vdr.ID()
}
if err := vm.uptimeManager.StartTracking(validatorIDs); err != nil {
return err
}
if err := vm.state.Commit(); err != nil {
return err
}
// Start the block builder
vm.Builder.ResetBlockTimer()
return nil
}
func (vm *VM) SetState(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() error {
if vm.dbManager == nil {
return nil
}
vm.Builder.Shutdown()
if vm.bootstrapped.GetValue() {
primaryValidatorSet, exist := vm.Validators.GetValidators(constants.PrimaryNetworkID)
if !exist {
return errNoPrimaryValidators
}
primaryValidators := primaryValidatorSet.List()
validatorIDs := make([]ids.NodeID, len(primaryValidators))
for i, vdr := range primaryValidators {
validatorIDs[i] = vdr.ID()
}
if err := vm.uptimeManager.Shutdown(validatorIDs); err != nil {
return err
}
if err := vm.state.Commit(); err != nil {
return err
}
}
errs := wrappers.Errs{}
errs.Add(
vm.state.Close(),
vm.dbManager.Close(),
)
return errs.Err
}
func (vm *VM) ParseBlock(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 := blocks.Parse(blocks.Codec, b)
if err != nil {
return nil, err
}
return vm.manager.NewBlock(statelessBlk), nil
}
func (vm *VM) GetBlock(blkID ids.ID) (snowman.Block, error) {
return vm.manager.GetBlock(blkID)
}
// LastAccepted returns the block most recently accepted
func (vm *VM) LastAccepted() (ids.ID, error) {
return vm.manager.LastAccepted(), nil
}
// SetPreference sets the preferred block to be the one with ID [blkID]
func (vm *VM) SetPreference(blkID ids.ID) error {
vm.Builder.SetPreference(blkID)
return nil
}
func (vm *VM) Version() (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() (map[string]*common.HTTPHandler, 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)
if err := server.RegisterService(
&Service{
vm: vm,
addrManager: avax.NewAddressManager(vm.ctx),
},
"platform",
); err != nil {
return nil, err
}
return map[string]*common.HTTPHandler{
"": {
Handler: server,
},
}, nil
}
// CreateStaticHandlers returns a map where:
// * keys are API endpoint extensions
// * values are API handlers
func (vm *VM) CreateStaticHandlers() (map[string]*common.HTTPHandler, error) {
server := rpc.NewServer()
server.RegisterCodec(json.NewCodec(), "application/json")
server.RegisterCodec(json.NewCodec(), "application/json;charset=UTF-8")
if err := server.RegisterService(&api.StaticService{}, "platform"); err != nil {
return nil, err
}
return map[string]*common.HTTPHandler{
"": {
LockOptions: common.NoLock,
Handler: server,
},
}, nil
}
func (vm *VM) Connected(vdrID ids.NodeID, _ *version.Application) error {
return vm.uptimeManager.Connect(vdrID)
}
func (vm *VM) Disconnected(vdrID ids.NodeID) error {
if err := vm.uptimeManager.Disconnect(vdrID); err != nil {
return err
}
return vm.state.Commit()
}
// GetValidatorSet returns the validator set at the specified height for the
// provided subnetID.
func (vm *VM) GetValidatorSet(height uint64, subnetID ids.ID) (map[ids.NodeID]uint64, error) {
validatorSetsCache, exists := vm.validatorSetCaches[subnetID]
if !exists {
validatorSetsCache = &cache.LRU{Size: validatorSetsCacheSize}
// Only cache whitelisted subnets
if vm.WhitelistedSubnets.Contains(subnetID) || subnetID == constants.PrimaryNetworkID {
vm.validatorSetCaches[subnetID] = validatorSetsCache
}
}
if validatorSetIntf, ok := validatorSetsCache.Get(height); ok {
validatorSet, ok := validatorSetIntf.(map[ids.NodeID]uint64)
if !ok {
return nil, errWrongCacheType
}
vm.metrics.IncValidatorSetsCached()
return validatorSet, nil
}
lastAcceptedHeight, err := vm.GetCurrentHeight()
if err != nil {
return nil, err
}
if lastAcceptedHeight < height {
return nil, database.ErrNotFound
}
// get the start time to track metrics
startTime := vm.Clock().Time()
currentValidators, ok := vm.Validators.GetValidators(subnetID)
if !ok {
return nil, errMissingValidatorSet
}
currentValidatorList := currentValidators.List()
vdrSet := make(map[ids.NodeID]uint64, len(currentValidatorList))
for _, vdr := range currentValidatorList {
vdrSet[vdr.ID()] = vdr.Weight()
}
for i := lastAcceptedHeight; i > height; i-- {
diffs, err := vm.state.GetValidatorWeightDiffs(i, subnetID)
if err != nil {
return nil, err
}
for nodeID, diff := range diffs {
var op func(uint64, uint64) (uint64, error)
if diff.Decrease {
// The validator's weight was decreased at this block, so in the
// prior block it was higher.
op = math.Add64
} else {
// The validator's weight was increased at this block, so in the
// prior block it was lower.
op = math.Sub[uint64]
}
newWeight, err := op(vdrSet[nodeID], diff.Amount)
if err != nil {
return nil, err
}
if newWeight == 0 {
delete(vdrSet, nodeID)
} else {
vdrSet[nodeID] = newWeight
}
}
}
// cache the validator set
validatorSetsCache.Put(height, vdrSet)
endTime := vm.Clock().Time()
vm.metrics.IncValidatorSetsCreated()
vm.metrics.AddValidatorSetsDuration(endTime.Sub(startTime))
vm.metrics.AddValidatorSetsHeightDiff(lastAcceptedHeight - height)
return vdrSet, nil
}
// GetMinimumHeight returns the height of the most recent block beyond the
// horizon of our recentlyAccepted window.
//
// Because the time between blocks is arbitrary, we're only guaranteed that
// the window's configured TTL amount of time has passed once an element
// expires from the window.
//
// To try to always return a block older than the window's TTL, we return the
// parent of the oldest element in the window (as an expired element is always
// guaranteed to be sufficiently stale). If we haven't expired an element yet
// in the case of a process restart, we default to the lastAccepted block's
// height which is likely (but not guaranteed) to also be older than the
// window's configured TTL.
func (vm *VM) GetMinimumHeight() (uint64, error) {
oldest, ok := vm.recentlyAccepted.Oldest()
if !ok {
return vm.GetCurrentHeight()
}
blk, err := vm.GetBlock(oldest)
if err != nil {
return 0, err
}
return blk.Height() - 1, nil
}
// GetCurrentHeight returns the height of the last accepted block
func (vm *VM) GetCurrentHeight() (uint64, error) {
lastAccepted, err := vm.GetBlock(vm.state.GetLastAccepted())
if err != nil {
return 0, err
}
return lastAccepted.Height(), nil
}
func (vm *VM) updateValidators() error {
primaryValidators, err := vm.state.ValidatorSet(constants.PrimaryNetworkID)
if err != nil {
return err
}
if err := vm.Validators.Set(constants.PrimaryNetworkID, primaryValidators); err != nil {
return err
}
weight, _ := primaryValidators.GetWeight(vm.ctx.NodeID)
vm.metrics.SetLocalStake(weight)
vm.metrics.SetTotalStake(primaryValidators.Weight())
for subnetID := range vm.WhitelistedSubnets {
subnetValidators, err := vm.state.ValidatorSet(subnetID)
if err != nil {
return err
}
if err := vm.Validators.Set(subnetID, subnetValidators); err != nil {
return err
}
}
return nil
}
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 }
// Returns the percentage of the total stake of the subnet connected to this
// node.
func (vm *VM) getPercentConnected(subnetID ids.ID) (float64, error) {
vdrSet, exists := vm.Validators.GetValidators(subnetID)
if !exists {
return 0, errNoValidators
}
vdrSetWeight := vdrSet.Weight()
if vdrSetWeight == 0 {
return 1, nil
}
var (
connectedStake uint64
err error
)
for _, vdr := range vdrSet.List() {
if !vm.uptimeManager.IsConnected(vdr.ID()) {
continue // not connected to us --> don't include
}
connectedStake, err = math.Add64(connectedStake, vdr.Weight())
if err != nil {
return 0, err
}
}
return float64(connectedStake) / float64(vdrSetWeight), nil
}