forked from ava-labs/avalanchego
-
Notifications
You must be signed in to change notification settings - Fork 4
/
vm.go
725 lines (630 loc) · 18.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
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
// Copyright (C) 2019-2021, Ava Labs, Inc. All rights reserved.
// See the file LICENSE for licensing terms.
package proposervm
import (
"context"
"fmt"
"time"
"go.uber.org/zap"
"github.com/MetalBlockchain/metalgo/database"
"github.com/MetalBlockchain/metalgo/database/manager"
"github.com/MetalBlockchain/metalgo/database/prefixdb"
"github.com/MetalBlockchain/metalgo/database/versiondb"
"github.com/MetalBlockchain/metalgo/ids"
"github.com/MetalBlockchain/metalgo/snow"
"github.com/MetalBlockchain/metalgo/snow/choices"
"github.com/MetalBlockchain/metalgo/snow/consensus/snowman"
"github.com/MetalBlockchain/metalgo/snow/engine/common"
"github.com/MetalBlockchain/metalgo/snow/engine/snowman/block"
"github.com/MetalBlockchain/metalgo/utils"
"github.com/MetalBlockchain/metalgo/utils/math"
"github.com/MetalBlockchain/metalgo/utils/timer/mockable"
"github.com/MetalBlockchain/metalgo/vms/proposervm/indexer"
"github.com/MetalBlockchain/metalgo/vms/proposervm/proposer"
"github.com/MetalBlockchain/metalgo/vms/proposervm/scheduler"
"github.com/MetalBlockchain/metalgo/vms/proposervm/state"
"github.com/MetalBlockchain/metalgo/vms/proposervm/tree"
statelessblock "github.com/MetalBlockchain/metalgo/vms/proposervm/block"
)
const (
// minBlockDelay should be kept as whole seconds because block timestamps
// are only specific to the second.
minBlockDelay = time.Second
checkIndexedFrequency = 10 * time.Second
)
var (
_ block.ChainVM = &VM{}
_ block.BatchedChainVM = &VM{}
_ block.HeightIndexedChainVM = &VM{}
_ block.StateSyncableVM = &VM{}
dbPrefix = []byte("proposervm")
)
type VM struct {
block.ChainVM
bVM block.BatchedChainVM
hVM block.HeightIndexedChainVM
ssVM block.StateSyncableVM
activationTime time.Time
minimumPChainHeight uint64
state.State
hIndexer indexer.HeightIndexer
resetHeightIndexOngoing utils.AtomicBool
proposer.Windower
tree.Tree
scheduler.Scheduler
mockable.Clock
ctx *snow.Context
db *versiondb.Database
toScheduler chan<- common.Message
// Block ID --> Block
// Each element is a block that passed verification but
// hasn't yet been accepted/rejected
verifiedBlocks map[ids.ID]PostForkBlock
preferred ids.ID
consensusState snow.State
context context.Context
onShutdown func()
// lastAcceptedTime is set to the last accepted PostForkBlock's timestamp
// if the last accepted block has been a PostForkOption block since having
// initialized the VM.
lastAcceptedTime time.Time
// lastAcceptedHeight is set to the last accepted PostForkBlock's height.
lastAcceptedHeight uint64
}
func New(
vm block.ChainVM,
activationTime time.Time,
minimumPChainHeight uint64,
) *VM {
bVM, _ := vm.(block.BatchedChainVM)
hVM, _ := vm.(block.HeightIndexedChainVM)
ssVM, _ := vm.(block.StateSyncableVM)
return &VM{
ChainVM: vm,
bVM: bVM,
hVM: hVM,
ssVM: ssVM,
activationTime: activationTime,
minimumPChainHeight: minimumPChainHeight,
}
}
func (vm *VM) Initialize(
ctx *snow.Context,
dbManager manager.Manager,
genesisBytes []byte,
upgradeBytes []byte,
configBytes []byte,
toEngine chan<- common.Message,
fxs []*common.Fx,
appSender common.AppSender,
) error {
vm.ctx = ctx
rawDB := dbManager.Current().Database
prefixDB := prefixdb.New(dbPrefix, rawDB)
vm.db = versiondb.New(prefixDB)
vm.State = state.New(vm.db)
vm.Windower = proposer.New(ctx.ValidatorState, ctx.SubnetID, ctx.ChainID)
vm.Tree = tree.New()
indexerDB := versiondb.New(vm.db)
indexerState := state.New(indexerDB)
vm.hIndexer = indexer.NewHeightIndexer(vm, vm.ctx.Log, indexerState)
scheduler, vmToEngine := scheduler.New(vm.ctx.Log, toEngine)
vm.Scheduler = scheduler
vm.toScheduler = vmToEngine
go ctx.Log.RecoverAndPanic(func() {
scheduler.Dispatch(time.Now())
})
vm.verifiedBlocks = make(map[ids.ID]PostForkBlock)
context, cancel := context.WithCancel(context.Background())
vm.context = context
vm.onShutdown = cancel
err := vm.ChainVM.Initialize(
ctx,
dbManager,
genesisBytes,
upgradeBytes,
configBytes,
vmToEngine,
fxs,
appSender,
)
if err != nil {
return err
}
if err := vm.repair(indexerState); err != nil {
return err
}
return vm.setLastAcceptedMetadata()
}
// shutdown ops then propagate shutdown to innerVM
func (vm *VM) Shutdown() error {
vm.onShutdown()
if err := vm.db.Commit(); err != nil {
return err
}
return vm.ChainVM.Shutdown()
}
func (vm *VM) SetState(newState snow.State) error {
if err := vm.ChainVM.SetState(newState); err != nil {
return err
}
oldState := vm.consensusState
vm.consensusState = newState
if oldState != snow.StateSyncing {
return nil
}
// When finishing StateSyncing, if state sync has failed or was skipped,
// repairAcceptedChainByHeight rolls back the chain to the previously last
// accepted block. If state sync has completed successfully, this call is a
// no-op.
if err := vm.repairAcceptedChainByHeight(); err != nil {
return err
}
return vm.setLastAcceptedMetadata()
}
func (vm *VM) BuildBlock() (snowman.Block, error) {
preferredBlock, err := vm.getBlock(vm.preferred)
if err != nil {
return nil, err
}
return preferredBlock.buildChild()
}
func (vm *VM) ParseBlock(b []byte) (snowman.Block, error) {
if blk, err := vm.parsePostForkBlock(b); err == nil {
return blk, nil
}
return vm.parsePreForkBlock(b)
}
func (vm *VM) GetBlock(id ids.ID) (snowman.Block, error) {
return vm.getBlock(id)
}
func (vm *VM) SetPreference(preferred ids.ID) error {
if vm.preferred == preferred {
return nil
}
vm.preferred = preferred
blk, err := vm.getPostForkBlock(preferred)
if err != nil {
return vm.ChainVM.SetPreference(preferred)
}
if err := vm.ChainVM.SetPreference(blk.getInnerBlk().ID()); err != nil {
return err
}
pChainHeight, err := blk.pChainHeight()
if err != nil {
return err
}
// reset scheduler
minDelay, err := vm.Windower.Delay(blk.Height()+1, pChainHeight, vm.ctx.NodeID)
if err != nil {
vm.ctx.Log.Debug("failed to fetch the expected delay",
zap.Error(err),
)
// A nil error is returned here because it is possible that
// bootstrapping caused the last accepted block to move past the latest
// P-chain height. This will cause building blocks to return an error
// until the P-chain's height has advanced.
return nil
}
if minDelay < minBlockDelay {
minDelay = minBlockDelay
}
preferredTime := blk.Timestamp()
nextStartTime := preferredTime.Add(minDelay)
vm.Scheduler.SetBuildBlockTime(nextStartTime)
vm.ctx.Log.Debug("set preference",
zap.Stringer("blkID", blk.ID()),
zap.Time("blockTimestamp", preferredTime),
zap.Time("nextStartTime", nextStartTime),
)
return nil
}
func (vm *VM) LastAccepted() (ids.ID, error) {
lastAccepted, err := vm.State.GetLastAccepted()
if err == database.ErrNotFound {
return vm.ChainVM.LastAccepted()
}
return lastAccepted, err
}
func (vm *VM) repair(indexerState state.State) error {
// check and possibly rebuild height index
if vm.hVM == nil {
return vm.repairAcceptedChainByIteration()
}
indexIsEmpty, err := vm.State.IsIndexEmpty()
if err != nil {
return err
}
if indexIsEmpty {
if err := vm.State.SetIndexHasReset(); err != nil {
return err
}
if err := vm.State.Commit(); err != nil {
return err
}
} else {
indexWasReset, err := vm.State.HasIndexReset()
if err != nil {
return fmt.Errorf("retrieving value of required index reset failed with: %w", err)
}
if !indexWasReset {
vm.resetHeightIndexOngoing.SetValue(true)
}
}
if !vm.resetHeightIndexOngoing.GetValue() {
// We are not going to wipe the height index
switch vm.hVM.VerifyHeightIndex() {
case nil:
// We are not going to wait for the height index to be repaired.
shouldRepair, err := vm.shouldHeightIndexBeRepaired()
if err != nil {
return err
}
if !shouldRepair {
vm.ctx.Log.Info("block height index was successfully verified")
vm.hIndexer.MarkRepaired(true)
return vm.repairAcceptedChainByHeight()
}
case block.ErrIndexIncomplete:
default:
return err
}
}
if err := vm.repairAcceptedChainByIteration(); err != nil {
return err
}
// asynchronously rebuild height index, if needed
go func() {
// If index reset has been requested, carry it out first
if vm.resetHeightIndexOngoing.GetValue() {
vm.ctx.Log.Info("block height indexing reset started")
if err := indexerState.ResetHeightIndex(vm.ctx.Log, vm); err != nil {
vm.ctx.Log.Error("block height indexing reset failed",
zap.Error(err),
)
return
}
vm.ctx.Log.Info("block height indexing reset finished")
vm.resetHeightIndexOngoing.SetValue(false)
}
// Poll until the underlying chain's index is complete or shutdown is
// called.
ticker := time.NewTicker(checkIndexedFrequency)
defer ticker.Stop()
for {
// The underlying VM expects the lock to be held here.
vm.ctx.Lock.Lock()
err := vm.hVM.VerifyHeightIndex()
vm.ctx.Lock.Unlock()
if err == nil {
// innerVM indexing complete. Let re-index this machine
break
}
if err != block.ErrIndexIncomplete {
vm.ctx.Log.Error("block height indexing failed",
zap.Error(err),
)
return
}
// innerVM index is incomplete. Wait for completion and retry
select {
case <-vm.context.Done():
return
case <-ticker.C:
}
}
vm.ctx.Lock.Lock()
shouldRepair, err := vm.shouldHeightIndexBeRepaired()
vm.ctx.Lock.Unlock()
if err != nil {
vm.ctx.Log.Error("could not verify height indexing status",
zap.Error(err),
)
return
}
if !shouldRepair {
vm.ctx.Log.Info("block height indexing is already complete")
vm.hIndexer.MarkRepaired(true)
return
}
err = vm.hIndexer.RepairHeightIndex(vm.context)
if err == nil {
vm.ctx.Log.Info("block height indexing finished")
return
}
// Note that we don't check if `err` is `context.Canceled` here because
// repairing the height index may have returned a non-standard error
// due to the chain shutting down.
if vm.context.Err() == nil {
// The context wasn't closed, so the chain hasn't been shutdown.
// This must have been an unexpected error.
vm.ctx.Log.Error("block height indexing failed",
zap.Error(err),
)
}
}()
return nil
}
func (vm *VM) repairAcceptedChainByIteration() error {
lastAcceptedID, err := vm.GetLastAccepted()
if err == database.ErrNotFound {
// If the last accepted block isn't indexed yet, then the underlying
// chain is the only chain and there is nothing to repair.
return nil
}
if err != nil {
return err
}
// Revert accepted blocks that weren't committed to the database.
for {
lastAccepted, err := vm.getPostForkBlock(lastAcceptedID)
if err == database.ErrNotFound {
// If the post fork block can't be found, it's because we're
// reverting past the fork boundary. If this is the case, then there
// is only one database to keep consistent, so there is nothing to
// repair anymore.
if err := vm.State.DeleteLastAccepted(); err != nil {
return err
}
if err := vm.State.DeleteCheckpoint(); err != nil {
return err
}
return vm.db.Commit()
}
if err != nil {
return err
}
shouldBeAccepted := lastAccepted.getInnerBlk()
// If the inner block is accepted, then we don't need to revert any more
// blocks.
if shouldBeAccepted.Status() == choices.Accepted {
return vm.db.Commit()
}
// Mark the last accepted block as processing - rather than accepted.
lastAccepted.setStatus(choices.Processing)
if err := vm.State.PutBlock(lastAccepted.getStatelessBlk(), choices.Processing); err != nil {
return err
}
// Advance to the parent block
previousLastAcceptedID := lastAcceptedID
lastAcceptedID = lastAccepted.Parent()
if err := vm.State.SetLastAccepted(lastAcceptedID); err != nil {
return err
}
// If the indexer checkpoint was previously pointing to the last
// accepted block, roll it back to the new last accepted block.
checkpoint, err := vm.State.GetCheckpoint()
if err == database.ErrNotFound {
continue
}
if err != nil {
return err
}
if previousLastAcceptedID != checkpoint {
continue
}
if err := vm.State.SetCheckpoint(lastAcceptedID); err != nil {
return err
}
}
}
func (vm *VM) repairAcceptedChainByHeight() error {
innerLastAcceptedID, err := vm.ChainVM.LastAccepted()
if err != nil {
return err
}
innerLastAccepted, err := vm.ChainVM.GetBlock(innerLastAcceptedID)
if err != nil {
return err
}
proLastAcceptedID, err := vm.State.GetLastAccepted()
if err == database.ErrNotFound {
// If the last accepted block isn't indexed yet, then the underlying
// chain is the only chain and there is nothing to repair.
return nil
}
if err != nil {
return err
}
proLastAccepted, err := vm.getPostForkBlock(proLastAcceptedID)
if err != nil {
return err
}
proLastAcceptedHeight := proLastAccepted.Height()
innerLastAcceptedHeight := innerLastAccepted.Height()
if proLastAcceptedHeight < innerLastAcceptedHeight {
return fmt.Errorf("proposervm height index (%d) should never be lower than the inner height index (%d)", proLastAcceptedHeight, innerLastAcceptedHeight)
}
if proLastAcceptedHeight == innerLastAcceptedHeight {
// There is nothing to repair - as the heights match
return nil
}
// The inner vm must be behind the proposer vm, so we must roll the proposervm back.
forkHeight, err := vm.State.GetForkHeight()
if err != nil {
return err
}
if forkHeight > innerLastAcceptedHeight {
// We are rolling back past the fork, so we should just forget about all of our proposervm indices.
if err := vm.State.DeleteLastAccepted(); err != nil {
return err
}
return vm.db.Commit()
}
newProLastAcceptedID, err := vm.State.GetBlockIDAtHeight(innerLastAcceptedHeight)
if err != nil {
return err
}
if err := vm.State.SetLastAccepted(newProLastAcceptedID); err != nil {
return err
}
return vm.db.Commit()
}
func (vm *VM) setLastAcceptedMetadata() error {
lastAcceptedID, err := vm.GetLastAccepted()
if err == database.ErrNotFound {
// If the last accepted block wasn't a PostFork block, then we don't
// initialize the metadata.
vm.lastAcceptedHeight = 0
vm.lastAcceptedTime = time.Time{}
return nil
}
if err != nil {
return err
}
lastAccepted, err := vm.getPostForkBlock(lastAcceptedID)
if err != nil {
return err
}
// Set the last accepted height
vm.lastAcceptedHeight = lastAccepted.Height()
if _, ok := lastAccepted.getStatelessBlk().(statelessblock.SignedBlock); ok {
// If the last accepted block wasn't a PostForkOption, then we don't
// initialize the time.
return nil
}
acceptedParent, err := vm.getPostForkBlock(lastAccepted.Parent())
if err != nil {
return err
}
vm.lastAcceptedTime = acceptedParent.Timestamp()
return nil
}
func (vm *VM) parsePostForkBlock(b []byte) (PostForkBlock, error) {
statelessBlock, err := statelessblock.Parse(b)
if err != nil {
return nil, err
}
// if the block already exists, then make sure the status is set correctly
blkID := statelessBlock.ID()
blk, err := vm.getPostForkBlock(blkID)
if err == nil {
return blk, nil
}
if err != database.ErrNotFound {
return nil, err
}
innerBlkBytes := statelessBlock.Block()
innerBlk, err := vm.ChainVM.ParseBlock(innerBlkBytes)
if err != nil {
return nil, err
}
if statelessSignedBlock, ok := statelessBlock.(statelessblock.SignedBlock); ok {
blk = &postForkBlock{
SignedBlock: statelessSignedBlock,
postForkCommonComponents: postForkCommonComponents{
vm: vm,
innerBlk: innerBlk,
status: choices.Processing,
},
}
} else {
blk = &postForkOption{
Block: statelessBlock,
postForkCommonComponents: postForkCommonComponents{
vm: vm,
innerBlk: innerBlk,
status: choices.Processing,
},
}
}
return blk, nil
}
func (vm *VM) parsePreForkBlock(b []byte) (*preForkBlock, error) {
blk, err := vm.ChainVM.ParseBlock(b)
return &preForkBlock{
Block: blk,
vm: vm,
}, err
}
func (vm *VM) getBlock(id ids.ID) (Block, error) {
if blk, err := vm.getPostForkBlock(id); err == nil {
return blk, nil
}
return vm.getPreForkBlock(id)
}
func (vm *VM) getPostForkBlock(blkID ids.ID) (PostForkBlock, error) {
block, exists := vm.verifiedBlocks[blkID]
if exists {
return block, nil
}
statelessBlock, status, err := vm.State.GetBlock(blkID)
if err != nil {
return nil, err
}
innerBlkBytes := statelessBlock.Block()
innerBlk, err := vm.ChainVM.ParseBlock(innerBlkBytes)
if err != nil {
return nil, err
}
if statelessSignedBlock, ok := statelessBlock.(statelessblock.SignedBlock); ok {
return &postForkBlock{
SignedBlock: statelessSignedBlock,
postForkCommonComponents: postForkCommonComponents{
vm: vm,
innerBlk: innerBlk,
status: status,
},
}, nil
}
return &postForkOption{
Block: statelessBlock,
postForkCommonComponents: postForkCommonComponents{
vm: vm,
innerBlk: innerBlk,
status: status,
},
}, nil
}
func (vm *VM) getPreForkBlock(blkID ids.ID) (*preForkBlock, error) {
blk, err := vm.ChainVM.GetBlock(blkID)
return &preForkBlock{
Block: blk,
vm: vm,
}, err
}
func (vm *VM) storePostForkBlock(blk PostForkBlock) error {
if err := vm.State.PutBlock(blk.getStatelessBlk(), blk.Status()); err != nil {
return err
}
height := blk.Height()
blkID := blk.ID()
if err := vm.updateHeightIndex(height, blkID); err != nil {
return err
}
return vm.db.Commit()
}
func (vm *VM) verifyAndRecordInnerBlk(postFork PostForkBlock) error {
// If inner block's Verify returned true, don't call it again.
//
// Note that if [innerBlk.Verify] returns nil, this method returns nil. This
// must always remain the case to maintain the inner block's invariant that
// if it's Verify() returns nil, it is eventually accepted or rejected.
currentInnerBlk := postFork.getInnerBlk()
if originalInnerBlk, contains := vm.Tree.Get(currentInnerBlk); !contains {
if err := currentInnerBlk.Verify(); err != nil {
return err
}
vm.Tree.Add(currentInnerBlk)
} else {
postFork.setInnerBlk(originalInnerBlk)
}
vm.verifiedBlocks[postFork.ID()] = postFork
return nil
}
// notifyInnerBlockReady tells the scheduler that the inner VM is ready to build
// a new block
func (vm *VM) notifyInnerBlockReady() {
select {
case vm.toScheduler <- common.PendingTxs:
default:
vm.ctx.Log.Debug("dropping message to consensus engine")
}
}
func (vm *VM) optimalPChainHeight(minPChainHeight uint64) (uint64, error) {
minimumHeight, err := vm.ctx.ValidatorState.GetMinimumHeight()
if err != nil {
return 0, err
}
return math.Max64(minimumHeight, minPChainHeight), nil
}