forked from ava-labs/avalanchego
-
Notifications
You must be signed in to change notification settings - Fork 4
/
vm.go
811 lines (713 loc) · 22.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
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
// Copyright (C) 2019-2023, Ava Labs, Inc. All rights reserved.
// See the file LICENSE for licensing terms.
package proposervm
import (
"context"
"crypto"
"crypto/x509"
"fmt"
"time"
"github.com/prometheus/client_golang/prometheus"
"go.uber.org/zap"
"github.com/MetalBlockchain/metalgo/api/metrics"
"github.com/MetalBlockchain/metalgo/cache"
"github.com/MetalBlockchain/metalgo/cache/metercacher"
"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 (
// DefaultMinBlockDelay should be kept as whole seconds because block
// timestamps are only specific to the second.
DefaultMinBlockDelay = time.Second
checkIndexedFrequency = 10 * time.Second
innerBlkCacheSize = 512
)
var (
_ block.ChainVM = (*VM)(nil)
_ block.BatchedChainVM = (*VM)(nil)
_ block.HeightIndexedChainVM = (*VM)(nil)
_ block.StateSyncableVM = (*VM)(nil)
dbPrefix = []byte("proposervm")
)
type VM struct {
block.ChainVM
blockBuilderVM block.BuildBlockWithContextChainVM
batchedVM block.BatchedChainVM
hVM block.HeightIndexedChainVM
ssVM block.StateSyncableVM
activationTime time.Time
minimumPChainHeight uint64
minBlkDelay time.Duration
// block signer
stakingLeafSigner crypto.Signer
// block certificate
stakingCertLeaf *x509.Certificate
state.State
hIndexer indexer.HeightIndexer
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
// Stateless block ID --> inner block.
// Only contains post-fork blocks near the tip so that the cache doesn't get
// filled with random blocks every time this node parses blocks while
// processing a GetAncestors message from a bootstrapping node.
innerBlkCache cache.Cacher[ids.ID, snowman.Block]
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
}
// New performs best when [minBlkDelay] is whole seconds. This is because block
// timestamps are only specific to the second.
func New(
vm block.ChainVM,
activationTime time.Time,
minimumPChainHeight uint64,
minBlkDelay time.Duration,
stakingLeafSigner crypto.Signer,
stakingCertLeaf *x509.Certificate,
) *VM {
blockBuilderVM, _ := vm.(block.BuildBlockWithContextChainVM)
batchedVM, _ := vm.(block.BatchedChainVM)
hVM, _ := vm.(block.HeightIndexedChainVM)
ssVM, _ := vm.(block.StateSyncableVM)
return &VM{
ChainVM: vm,
blockBuilderVM: blockBuilderVM,
batchedVM: batchedVM,
hVM: hVM,
ssVM: ssVM,
activationTime: activationTime,
minimumPChainHeight: minimumPChainHeight,
minBlkDelay: minBlkDelay,
stakingLeafSigner: stakingLeafSigner,
stakingCertLeaf: stakingCertLeaf,
}
}
func (vm *VM) Initialize(
ctx context.Context,
chainCtx *snow.Context,
dbManager manager.Manager,
genesisBytes []byte,
upgradeBytes []byte,
configBytes []byte,
toEngine chan<- common.Message,
fxs []*common.Fx,
appSender common.AppSender,
) error {
// TODO: Add a helper for this metrics override, it is performed in multiple
// places.
multiGatherer := metrics.NewMultiGatherer()
registerer := prometheus.NewRegistry()
if err := multiGatherer.Register("proposervm", registerer); err != nil {
return err
}
optionalGatherer := metrics.NewOptionalGatherer()
if err := multiGatherer.Register("", optionalGatherer); err != nil {
return err
}
if err := chainCtx.Metrics.Register(multiGatherer); err != nil {
return err
}
chainCtx.Metrics = optionalGatherer
vm.ctx = chainCtx
rawDB := dbManager.Current().Database
prefixDB := prefixdb.New(dbPrefix, rawDB)
vm.db = versiondb.New(prefixDB)
vm.State = state.New(vm.db)
vm.Windower = proposer.New(chainCtx.ValidatorState, chainCtx.SubnetID, chainCtx.ChainID)
vm.Tree = tree.New()
innerBlkCache, err := metercacher.New[ids.ID, snowman.Block](
"inner_block_cache",
registerer,
&cache.LRU[ids.ID, snowman.Block]{Size: innerBlkCacheSize},
)
if err != nil {
return err
}
vm.innerBlkCache = innerBlkCache
indexerDB := versiondb.New(vm.db)
// TODO: Use [state.NewMetered] here to populate additional metrics.
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 chainCtx.Log.RecoverAndPanic(func() {
scheduler.Dispatch(time.Now())
})
vm.verifiedBlocks = make(map[ids.ID]PostForkBlock)
detachedCtx := utils.Detach(ctx)
context, cancel := context.WithCancel(detachedCtx)
vm.context = context
vm.onShutdown = cancel
err = vm.ChainVM.Initialize(
ctx,
chainCtx,
dbManager,
genesisBytes,
upgradeBytes,
configBytes,
vmToEngine,
fxs,
appSender,
)
if err != nil {
return err
}
if err := vm.repair(detachedCtx); err != nil {
return err
}
return vm.setLastAcceptedMetadata(ctx)
}
// shutdown ops then propagate shutdown to innerVM
func (vm *VM) Shutdown(ctx context.Context) error {
vm.onShutdown()
if err := vm.db.Commit(); err != nil {
return err
}
return vm.ChainVM.Shutdown(ctx)
}
func (vm *VM) SetState(ctx context.Context, newState snow.State) error {
if err := vm.ChainVM.SetState(ctx, 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(ctx); err != nil {
return err
}
return vm.setLastAcceptedMetadata(ctx)
}
func (vm *VM) BuildBlock(ctx context.Context) (snowman.Block, error) {
preferredBlock, err := vm.getBlock(ctx, vm.preferred)
if err != nil {
return nil, err
}
return preferredBlock.buildChild(ctx)
}
func (vm *VM) ParseBlock(ctx context.Context, b []byte) (snowman.Block, error) {
if blk, err := vm.parsePostForkBlock(ctx, b); err == nil {
return blk, nil
}
return vm.parsePreForkBlock(ctx, b)
}
func (vm *VM) GetBlock(ctx context.Context, id ids.ID) (snowman.Block, error) {
return vm.getBlock(ctx, id)
}
func (vm *VM) SetPreference(ctx context.Context, preferred ids.ID) error {
if vm.preferred == preferred {
return nil
}
vm.preferred = preferred
blk, err := vm.getPostForkBlock(ctx, preferred)
if err != nil {
return vm.ChainVM.SetPreference(ctx, preferred)
}
if err := vm.ChainVM.SetPreference(ctx, blk.getInnerBlk().ID()); err != nil {
return err
}
pChainHeight, err := blk.pChainHeight(ctx)
if err != nil {
return err
}
// reset scheduler
minDelay, err := vm.Windower.Delay(ctx, 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
}
// Note: The P-chain does not currently try to target any block time. It
// notifies the consensus engine as soon as a new block may be built. To
// avoid fast runs of blocks there is an additional minimum delay that
// validators can specify. This delay may be an issue for high performance,
// custom VMs. Until the P-chain is modified to target a specific block
// time, ProposerMinBlockDelay can be configured in the subnet config.
if minDelay < vm.minBlkDelay {
minDelay = vm.minBlkDelay
}
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(ctx context.Context) (ids.ID, error) {
lastAccepted, err := vm.State.GetLastAccepted()
if err == database.ErrNotFound {
return vm.ChainVM.LastAccepted(ctx)
}
return lastAccepted, err
}
// repair makes sure that vm and innerVM chains are in sync.
// Moreover it fixes vm's height index if defined.
func (vm *VM) repair(ctx context.Context) error {
if vm.hVM == nil {
// height index not defined. Just sync vms and innerVM chains.
return vm.repairAcceptedChainByIteration(ctx)
}
switch vm.hVM.VerifyHeightIndex(ctx) {
case nil:
// InnerVM height index is complete. We can immediately verify
// and repair this VM height index.
shouldRepair, err := vm.shouldHeightIndexBeRepaired(ctx)
if err != nil {
return err
}
if !shouldRepair {
vm.ctx.Log.Info("block height index was successfully verified")
vm.hIndexer.MarkRepaired(true)
return vm.repairAcceptedChainByHeight(ctx)
}
case block.ErrIndexIncomplete:
default:
return nil
}
// innerVM height index is incomplete. Sync vm and innerVM chains first.
if err := vm.repairAcceptedChainByIteration(ctx); err != nil {
return err
}
// asynchronously rebuild height index, if needed
go func() {
// 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(ctx)
vm.ctx.Lock.Unlock()
if err == nil {
// innerVM indexing complete. Let's re-index this VM
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(ctx)
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(ctx context.Context) 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(ctx, 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(ctx context.Context) error {
innerLastAcceptedID, err := vm.ChainVM.LastAccepted(ctx)
if err != nil {
return err
}
innerLastAccepted, err := vm.ChainVM.GetBlock(ctx, 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(ctx, 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(ctx context.Context) 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(ctx, 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(ctx, lastAccepted.Parent())
if err != nil {
return err
}
vm.lastAcceptedTime = acceptedParent.Timestamp()
return nil
}
func (vm *VM) parsePostForkBlock(ctx context.Context, 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(ctx, blkID)
if err == nil {
return blk, nil
}
if err != database.ErrNotFound {
return nil, err
}
innerBlkBytes := statelessBlock.Block()
innerBlk, err := vm.parseInnerBlock(ctx, blkID, 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(ctx context.Context, b []byte) (*preForkBlock, error) {
blk, err := vm.ChainVM.ParseBlock(ctx, b)
return &preForkBlock{
Block: blk,
vm: vm,
}, err
}
func (vm *VM) getBlock(ctx context.Context, id ids.ID) (Block, error) {
if blk, err := vm.getPostForkBlock(ctx, id); err == nil {
return blk, nil
}
return vm.getPreForkBlock(ctx, id)
}
func (vm *VM) getPostForkBlock(ctx context.Context, 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.parseInnerBlock(ctx, blkID, 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(ctx context.Context, blkID ids.ID) (*preForkBlock, error) {
blk, err := vm.ChainVM.GetBlock(ctx, 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(ctx context.Context, blockCtx *block.Context, postFork PostForkBlock) error {
innerBlk := postFork.getInnerBlk()
postForkID := postFork.ID()
originalInnerBlock, previouslyVerified := vm.Tree.Get(innerBlk)
if previouslyVerified {
innerBlk = originalInnerBlock
// We must update all of the mappings from postFork -> innerBlock to
// now point to originalInnerBlock.
postFork.setInnerBlk(originalInnerBlock)
vm.innerBlkCache.Put(postForkID, originalInnerBlock)
}
var (
shouldVerifyWithCtx = blockCtx != nil
blkWithCtx block.WithVerifyContext
err error
)
if shouldVerifyWithCtx {
blkWithCtx, shouldVerifyWithCtx = innerBlk.(block.WithVerifyContext)
if shouldVerifyWithCtx {
shouldVerifyWithCtx, err = blkWithCtx.ShouldVerifyWithContext(ctx)
if err != nil {
return err
}
}
}
// Invariant: If either [Verify] or [VerifyWithContext] returns nil, this
// function must return nil. This maintains the inner block's
// invariant that successful verification will eventually result
// in accepted or rejected being called.
if shouldVerifyWithCtx {
// This block needs to know the P-Chain height during verification.
// Note that [VerifyWithContext] with context may be called multiple
// times with multiple contexts.
err = blkWithCtx.VerifyWithContext(ctx, blockCtx)
} else if !previouslyVerified {
// This isn't a [block.WithVerifyContext] so we only call [Verify] once.
err = innerBlk.Verify(ctx)
}
if err != nil {
return err
}
// Since verification passed, we should ensure the inner block tree is
// populated.
if !previouslyVerified {
vm.Tree.Add(innerBlk)
}
vm.verifiedBlocks[postForkID] = 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(ctx context.Context, minPChainHeight uint64) (uint64, error) {
minimumHeight, err := vm.ctx.ValidatorState.GetMinimumHeight(ctx)
if err != nil {
return 0, err
}
return math.Max(minimumHeight, minPChainHeight), nil
}
// parseInnerBlock attempts to parse the provided bytes as an inner block. If
// the inner block happens to be cached, then the inner block will not be
// parsed.
func (vm *VM) parseInnerBlock(ctx context.Context, outerBlkID ids.ID, innerBlkBytes []byte) (snowman.Block, error) {
if innerBlk, ok := vm.innerBlkCache.Get(outerBlkID); ok {
return innerBlk, nil
}
innerBlk, err := vm.ChainVM.ParseBlock(ctx, innerBlkBytes)
if err != nil {
return nil, err
}
vm.cacheInnerBlock(outerBlkID, innerBlk)
return innerBlk, nil
}
// Caches proposervm block ID --> inner block if the inner block's height
// is within [innerBlkCacheSize] of the last accepted block's height.
func (vm *VM) cacheInnerBlock(outerBlkID ids.ID, innerBlk snowman.Block) {
diff := math.AbsDiff(innerBlk.Height(), vm.lastAcceptedHeight)
if diff < innerBlkCacheSize {
vm.innerBlkCache.Put(outerBlkID, innerBlk)
}
}