-
Notifications
You must be signed in to change notification settings - Fork 666
/
vm.go
641 lines (541 loc) · 17.4 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
// Copyright (C) 2019-2021, 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"
"github.com/ava-labs/avalanchego/cache"
"github.com/ava-labs/avalanchego/chains"
"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/choices"
"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/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/fx"
"github.com/ava-labs/avalanchego/vms/platformvm/reward"
"github.com/ava-labs/avalanchego/vms/secp256k1fx"
safemath "github.com/ava-labs/avalanchego/utils/math"
)
const (
// MaxValidatorWeightFactor is the maximum factor of the validator stake
// that is allowed to be placed on a validator.
MaxValidatorWeightFactor uint64 = 5
validatorSetsCacheSize = 64
// Maximum future start time for staking/delegating
maxFutureStartTime = 24 * 7 * 2 * time.Hour
maxRecentlyAcceptedWindowSize = 256
recentlyAcceptedWindowTTL = 5 * time.Minute
)
var (
errInvalidID = errors.New("invalid ID")
errDSCantValidate = errors.New("new blockchain can't be validated by primary network")
errStartTimeTooEarly = errors.New("start time is before the current chain time")
errStartAfterEndTime = errors.New("start time is after the end time")
errWrongCacheType = errors.New("unexpectedly cached type")
_ block.ChainVM = &VM{}
_ validators.Connector = &VM{}
_ secp256k1fx.VM = &VM{}
_ validators.State = &VM{}
)
type VM struct {
Factory
metrics
avax.AddressManager
avax.AtomicUTXOManager
*network
// Used to get time. Useful for faking time during tests.
clock mockable.Clock
blockBuilder blockBuilder
uptimeManager uptime.Manager
rewards reward.Calculator
// The context of this vm
ctx *snow.Context
dbManager manager.Manager
internalState InternalState
// ID of the preferred block
preferred ids.ID
// ID of the last accepted block
lastAcceptedID ids.ID
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
// Key: block ID
// Value: the block
currentBlocks map[ids.ID]Block
// sliding window of blocks that were recently accepted
recentlyAccepted *window.Window
}
// 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
if err := vm.metrics.Initialize("", registerer, vm.WhitelistedSubnets); err != nil {
return err
}
// Initialize the utility to parse addresses
vm.AddressManager = avax.NewAddressManager(ctx)
// Initialize the utility to fetch atomic UTXOs
vm.AtomicUTXOManager = avax.NewAtomicUTXOManager(ctx.SharedMemory, Codec)
vm.fx = &secp256k1fx.Fx{}
vm.ctx = ctx
vm.dbManager = dbManager
vm.codecRegistry = linearcodec.NewDefault()
if err := vm.fx.Initialize(vm); err != nil {
return err
}
vm.validatorSetCaches = make(map[ids.ID]cache.Cacher)
vm.currentBlocks = make(map[ids.ID]Block)
if err := vm.blockBuilder.Initialize(vm, toEngine, registerer); err != nil {
return fmt.Errorf(
"failed to initialize the block builder: %w",
err,
)
}
vm.network = newNetwork(vm.ApricotPhase4Time, appSender, vm)
vm.rewards = reward.NewCalculator(vm.RewardConfig)
is, err := NewMeteredInternalState(vm, vm.dbManager.Current().Database, genesisBytes, registerer)
if err != nil {
return err
}
vm.internalState = is
// Initialize the utility to track validator uptimes
vm.uptimeManager = uptime.NewManager(is)
vm.UptimeLockedCalculator.SetCalculator(&vm.bootstrapped, &ctx.Lock, vm.uptimeManager)
if err := vm.updateValidators(); err != nil {
return fmt.Errorf(
"failed to initialize 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,
)
}
vm.recentlyAccepted = window.New(
window.Config{
Clock: &vm.clock,
MaxSize: maxRecentlyAcceptedWindowSize,
TTL: recentlyAcceptedWindowTTL,
},
)
vm.lastAcceptedID = is.GetLastAccepted()
ctx.Log.Info("initializing last accepted block as %s", vm.lastAcceptedID)
// Build off the most recently accepted block
return vm.SetPreference(vm.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.internalState.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.internalState.GetChains(subnetID)
if err != nil {
return err
}
for _, chain := range chains {
if err := vm.createChain(chain); err != nil {
return err
}
}
return nil
}
// Create the blockchain described in [tx], but only if this node is a member of
// the subnet that validates the chain
func (vm *VM) createChain(tx *Tx) error {
unsignedTx, ok := tx.UnsignedTx.(*UnsignedCreateChainTx)
if !ok {
return errWrongTxType
}
if vm.StakingEnabled && // Staking is enabled, so nodes might not validate all chains
constants.PrimaryNetworkID != unsignedTx.SubnetID && // All nodes must validate the primary network
!vm.WhitelistedSubnets.Contains(unsignedTx.SubnetID) { // This node doesn't validate this blockchain
return nil
}
chainParams := chains.ChainParameters{
ID: tx.ID(),
SubnetID: unsignedTx.SubnetID,
GenesisData: unsignedTx.GenesisData,
VMAlias: unsignedTx.VMID.String(),
}
for _, fxID := range unsignedTx.FxIDs {
chainParams.FxAliases = append(chainParams.FxAliases, fxID.String())
}
vm.Chains.CreateChain(chainParams)
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
}
return vm.internalState.Commit()
}
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.blockBuilder.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.internalState.Commit(); err != nil {
return err
}
}
errs := wrappers.Errs{}
errs.Add(
vm.internalState.Close(),
vm.dbManager.Close(),
)
return errs.Err
}
// BuildBlock builds a block to be added to consensus
func (vm *VM) BuildBlock() (snowman.Block, error) { return vm.blockBuilder.BuildBlock() }
func (vm *VM) ParseBlock(b []byte) (snowman.Block, error) {
var blk Block
if _, err := Codec.Unmarshal(b, &blk); err != nil {
return nil, err
}
if err := blk.initialize(vm, b, choices.Processing, blk); err != nil {
return nil, err
}
// TODO: remove this to make ParseBlock stateless
if block, err := vm.GetBlock(blk.ID()); err == nil {
// If we have seen this block before, return it with the most up-to-date
// info
return block, nil
}
return blk, nil
}
func (vm *VM) GetBlock(blkID ids.ID) (snowman.Block, error) { return vm.getBlock(blkID) }
func (vm *VM) getBlock(blkID ids.ID) (Block, error) {
// If block is in memory, return it.
if blk, exists := vm.currentBlocks[blkID]; exists {
return blk, nil
}
return vm.internalState.GetBlock(blkID)
}
// LastAccepted returns the block most recently accepted
func (vm *VM) LastAccepted() (ids.ID, error) {
return vm.lastAcceptedID, nil
}
// SetPreference sets the preferred block to be the one with ID [blkID]
func (vm *VM) SetPreference(blkID ids.ID) error {
if blkID == vm.preferred {
// If the preference didn't change, then this is a noop
return nil
}
vm.preferred = blkID
vm.blockBuilder.ResetTimer()
return nil
}
func (vm *VM) Preferred() (Block, error) {
return vm.getBlock(vm.preferred)
}
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.apiRequestMetrics.InterceptRequest)
server.RegisterAfterFunc(vm.metrics.apiRequestMetrics.AfterRequest)
if err := server.RegisterService(&Service{vm: vm}, "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(&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.internalState.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.validatorSetsCached.Inc()
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, errNotEnoughValidators
}
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.internalState.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 = safemath.Add64
} else {
// The validator's weight was increased at this block, so in the
// prior block it was lower.
op = safemath.Sub64
}
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.validatorSetsCreated.Inc()
vm.metrics.validatorSetsDuration.Add(float64(endTime.Sub(startTime)))
vm.metrics.validatorSetsHeightDiff.Add(float64(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.(ids.ID))
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.lastAcceptedID)
if err != nil {
return 0, err
}
return lastAccepted.Height(), nil
}
func (vm *VM) updateValidators() error {
currentValidators := vm.internalState.CurrentStakerChainState()
primaryValidators, err := currentValidators.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.localStake.Set(float64(weight))
vm.totalStake.Set(float64(primaryValidators.Weight()))
for subnetID := range vm.WhitelistedSubnets {
subnetValidators, err := currentValidators.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 = safemath.Add64(connectedStake, vdr.Weight())
if err != nil {
return 0, err
}
}
return float64(connectedStake) / float64(vdrSetWeight), nil
}