-
Notifications
You must be signed in to change notification settings - Fork 661
/
transitive.go
854 lines (742 loc) · 25.2 KB
/
transitive.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
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
// Copyright (C) 2019-2021, Ava Labs, Inc. All rights reserved.
// See the file LICENSE for licensing terms.
package snowman
import (
"fmt"
"time"
"go.uber.org/zap"
"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/consensus/snowman/poll"
"github.com/ava-labs/avalanchego/snow/engine/common"
"github.com/ava-labs/avalanchego/snow/events"
"github.com/ava-labs/avalanchego/utils/set"
"github.com/ava-labs/avalanchego/utils/wrappers"
"github.com/ava-labs/avalanchego/version"
)
var _ Engine = &Transitive{}
func New(config Config) (Engine, error) {
return newTransitive(config)
}
// Transitive implements the Engine interface by attempting to fetch all
// Transitive dependencies.
type Transitive struct {
Config
metrics
// list of NoOpsHandler for messages dropped by engine
common.StateSummaryFrontierHandler
common.AcceptedStateSummaryHandler
common.AcceptedFrontierHandler
common.AcceptedHandler
common.AncestorsHandler
RequestID uint32
// track outstanding preference requests
polls poll.Set
// blocks that have we have sent get requests for but haven't yet received
blkReqs common.Requests
// blocks that are queued to be issued to consensus once missing dependencies are fetched
// Block ID --> Block
pending map[ids.ID]snowman.Block
// Block ID --> Parent ID
nonVerifieds AncestorTree
// operations that are blocked on a block being issued. This could be
// issuing another block, responding to a query, or applying votes to consensus
blocked events.Blocker
// number of times build block needs to be called once the number of
// processing blocks has gone below the optimal number.
pendingBuildBlocks int
// errs tracks if an error has occurred in a callback
errs wrappers.Errs
}
func newTransitive(config Config) (*Transitive, error) {
config.Ctx.Log.Info("initializing consensus engine")
factory := poll.NewEarlyTermNoTraversalFactory(config.Params.Alpha)
t := &Transitive{
Config: config,
StateSummaryFrontierHandler: common.NewNoOpStateSummaryFrontierHandler(config.Ctx.Log),
AcceptedStateSummaryHandler: common.NewNoOpAcceptedStateSummaryHandler(config.Ctx.Log),
AcceptedFrontierHandler: common.NewNoOpAcceptedFrontierHandler(config.Ctx.Log),
AcceptedHandler: common.NewNoOpAcceptedHandler(config.Ctx.Log),
AncestorsHandler: common.NewNoOpAncestorsHandler(config.Ctx.Log),
pending: make(map[ids.ID]snowman.Block),
nonVerifieds: NewAncestorTree(),
polls: poll.NewSet(factory,
config.Ctx.Log,
"",
config.Ctx.Registerer,
),
}
return t, t.metrics.Initialize("", config.Ctx.Registerer)
}
func (t *Transitive) Put(nodeID ids.NodeID, requestID uint32, blkBytes []byte) error {
blk, err := t.VM.ParseBlock(blkBytes)
if err != nil {
t.Ctx.Log.Debug("failed to parse block",
zap.Stringer("nodeID", nodeID),
zap.Uint32("requestID", requestID),
zap.Error(err),
)
t.Ctx.Log.Verbo("failed to parse block",
zap.Stringer("nodeID", nodeID),
zap.Uint32("requestID", requestID),
zap.Binary("block", blkBytes),
zap.Error(err),
)
// because GetFailed doesn't utilize the assumption that we actually
// sent a Get message, we can safely call GetFailed here to potentially
// abandon the request.
return t.GetFailed(nodeID, requestID)
}
if t.wasIssued(blk) {
t.metrics.numUselessPutBytes.Add(float64(len(blkBytes)))
}
// issue the block into consensus. If the block has already been issued,
// this will be a noop. If this block has missing dependencies, vdr will
// receive requests to fill the ancestry. dependencies that have already
// been fetched, but with missing dependencies themselves won't be requested
// from the vdr.
if _, err := t.issueFrom(nodeID, blk); err != nil {
return err
}
return t.buildBlocks()
}
func (t *Transitive) GetFailed(nodeID ids.NodeID, requestID uint32) error {
// We don't assume that this function is called after a failed Get message.
// Check to see if we have an outstanding request and also get what the request was for if it exists.
blkID, ok := t.blkReqs.Remove(nodeID, requestID)
if !ok {
t.Ctx.Log.Debug("unexpected GetFailed",
zap.Stringer("nodeID", nodeID),
zap.Uint32("requestID", requestID),
)
return nil
}
// Because the get request was dropped, we no longer expect blkID to be issued.
t.blocked.Abandon(blkID)
t.metrics.numBlockers.Set(float64(t.blocked.Len()))
return t.buildBlocks()
}
func (t *Transitive) PullQuery(nodeID ids.NodeID, requestID uint32, blkID ids.ID) error {
// TODO: once everyone supports ChitsV2 - we should be sending that message
// type here.
t.Sender.SendChits(nodeID, requestID, []ids.ID{t.Consensus.Preference()})
// Try to issue [blkID] to consensus.
// If we're missing an ancestor, request it from [vdr]
if _, err := t.issueFromByID(nodeID, blkID); err != nil {
return err
}
return t.buildBlocks()
}
func (t *Transitive) PushQuery(nodeID ids.NodeID, requestID uint32, blkBytes []byte) error {
// TODO: once everyone supports ChitsV2 - we should be sending that message
// type here.
t.Sender.SendChits(nodeID, requestID, []ids.ID{t.Consensus.Preference()})
blk, err := t.VM.ParseBlock(blkBytes)
// If parsing fails, we just drop the request, as we didn't ask for it
if err != nil {
t.Ctx.Log.Debug("failed to parse block",
zap.Stringer("nodeID", nodeID),
zap.Uint32("requestID", requestID),
zap.Error(err),
)
t.Ctx.Log.Verbo("failed to parse block",
zap.Stringer("nodeID", nodeID),
zap.Uint32("requestID", requestID),
zap.Binary("block", blkBytes),
zap.Error(err),
)
return nil
}
if t.wasIssued(blk) {
t.metrics.numUselessPushQueryBytes.Add(float64(len(blkBytes)))
}
// issue the block into consensus. If the block has already been issued,
// this will be a noop. If this block has missing dependencies, nodeID will
// receive requests to fill the ancestry. dependencies that have already
// been fetched, but with missing dependencies themselves won't be requested
// from the vdr.
if _, err := t.issueFrom(nodeID, blk); err != nil {
return err
}
return t.buildBlocks()
}
func (t *Transitive) Chits(nodeID ids.NodeID, requestID uint32, votes []ids.ID) error {
// Since this is a linear chain, there should only be one ID in the vote set
if len(votes) != 1 {
t.Ctx.Log.Debug("failing Chits",
zap.String("reason", "expected only 1 vote"),
zap.Int("numVotes", len(votes)),
zap.Stringer("nodeID", nodeID),
zap.Uint32("requestID", requestID),
)
// because QueryFailed doesn't utilize the assumption that we actually
// sent a Query message, we can safely call QueryFailed here to
// potentially abandon the request.
return t.QueryFailed(nodeID, requestID)
}
blkID := votes[0]
t.Ctx.Log.Verbo("called Chits for the block",
zap.Stringer("blkID", blkID),
zap.Stringer("nodeID", nodeID),
zap.Uint32("requestID", requestID))
// Will record chits once [blkID] has been issued into consensus
v := &voter{
t: t,
vdr: nodeID,
requestID: requestID,
response: blkID,
}
added, err := t.issueFromByID(nodeID, blkID)
if err != nil {
return err
}
// Wait until [blkID] has been issued to consensus before applying this chit.
if !added {
v.deps.Add(blkID)
}
t.blocked.Register(v)
t.metrics.numBlockers.Set(float64(t.blocked.Len()))
return t.buildBlocks()
}
func (t *Transitive) ChitsV2(vdr ids.NodeID, requestID uint32, _ []ids.ID, vote ids.ID) error {
return t.Chits(vdr, requestID, []ids.ID{vote})
}
func (t *Transitive) QueryFailed(vdr ids.NodeID, requestID uint32) error {
t.blocked.Register(&voter{
t: t,
vdr: vdr,
requestID: requestID,
})
t.metrics.numBlockers.Set(float64(t.blocked.Len()))
return t.buildBlocks()
}
func (t *Transitive) AppRequest(nodeID ids.NodeID, requestID uint32, deadline time.Time, request []byte) error {
// Notify the VM of this request
return t.VM.AppRequest(nodeID, requestID, deadline, request)
}
func (t *Transitive) AppRequestFailed(nodeID ids.NodeID, requestID uint32) error {
// Notify the VM that a request it made failed
return t.VM.AppRequestFailed(nodeID, requestID)
}
func (t *Transitive) AppResponse(nodeID ids.NodeID, requestID uint32, response []byte) error {
// Notify the VM of a response to its request
return t.VM.AppResponse(nodeID, requestID, response)
}
func (t *Transitive) AppGossip(nodeID ids.NodeID, msg []byte) error {
// Notify the VM of this message which has been gossiped to it
return t.VM.AppGossip(nodeID, msg)
}
func (t *Transitive) Connected(nodeID ids.NodeID, nodeVersion *version.Application) error {
return t.VM.Connected(nodeID, nodeVersion)
}
func (t *Transitive) Disconnected(nodeID ids.NodeID) error {
return t.VM.Disconnected(nodeID)
}
func (t *Transitive) Timeout() error { return nil }
func (t *Transitive) Gossip() error {
blkID, err := t.VM.LastAccepted()
if err != nil {
return err
}
blk, err := t.GetBlock(blkID)
if err != nil {
t.Ctx.Log.Warn("dropping gossip request",
zap.String("reason", "block couldn't be loaded"),
zap.Stringer("blkID", blkID),
zap.Error(err),
)
return nil
}
t.Ctx.Log.Verbo("gossiping accepted block to the network",
zap.Stringer("blkID", blkID),
)
t.Sender.SendGossip(blkID, blk.Bytes())
return nil
}
func (t *Transitive) Halt() {}
func (t *Transitive) Shutdown() error {
t.Ctx.Log.Info("shutting down consensus engine")
return t.VM.Shutdown()
}
func (t *Transitive) Notify(msg common.Message) error {
if msg != common.PendingTxs {
t.Ctx.Log.Warn("received an unexpected message from the VM",
zap.Stringer("message", msg),
)
return nil
}
// the pending txs message means we should attempt to build a block.
t.pendingBuildBlocks++
return t.buildBlocks()
}
func (t *Transitive) Context() *snow.ConsensusContext {
return t.Ctx
}
func (t *Transitive) Start(startReqID uint32) error {
t.RequestID = startReqID
lastAcceptedID, err := t.VM.LastAccepted()
if err != nil {
return err
}
lastAccepted, err := t.GetBlock(lastAcceptedID)
if err != nil {
t.Ctx.Log.Error("failed to get last accepted block",
zap.Error(err),
)
return err
}
// initialize consensus to the last accepted blockID
if err := t.Consensus.Initialize(t.Ctx, t.Params, lastAcceptedID, lastAccepted.Height()); err != nil {
return err
}
// to maintain the invariant that oracle blocks are issued in the correct
// preferences, we need to handle the case that we are bootstrapping into an oracle block
if oracleBlk, ok := lastAccepted.(snowman.OracleBlock); ok {
options, err := oracleBlk.Options()
switch {
case err == snowman.ErrNotOracle:
// if there aren't blocks we need to deliver on startup, we need to set
// the preference to the last accepted block
if err := t.VM.SetPreference(lastAcceptedID); err != nil {
return err
}
case err != nil:
return err
default:
for _, blk := range options {
// note that deliver will set the VM's preference
if err := t.deliver(blk); err != nil {
return err
}
}
}
} else if err := t.VM.SetPreference(lastAcceptedID); err != nil {
return err
}
t.Ctx.Log.Info("consensus starting",
zap.Stringer("lastAcceptedBlock", lastAcceptedID),
)
t.metrics.bootstrapFinished.Set(1)
t.Ctx.SetState(snow.NormalOp)
if err := t.VM.SetState(snow.NormalOp); err != nil {
return fmt.Errorf("failed to notify VM that consensus is starting: %w",
err)
}
return nil
}
func (t *Transitive) HealthCheck() (interface{}, error) {
consensusIntf, consensusErr := t.Consensus.HealthCheck()
vmIntf, vmErr := t.VM.HealthCheck()
intf := map[string]interface{}{
"consensus": consensusIntf,
"vm": vmIntf,
}
if consensusErr == nil {
return intf, vmErr
}
if vmErr == nil {
return intf, consensusErr
}
return intf, fmt.Errorf("vm: %s ; consensus: %s", vmErr, consensusErr)
}
func (t *Transitive) GetVM() common.VM {
return t.VM
}
func (t *Transitive) GetBlock(blkID ids.ID) (snowman.Block, error) {
if blk, ok := t.pending[blkID]; ok {
return blk, nil
}
return t.VM.GetBlock(blkID)
}
// Build blocks if they have been requested and the number of processing blocks
// is less than optimal.
func (t *Transitive) buildBlocks() error {
if err := t.errs.Err; err != nil {
return err
}
for t.pendingBuildBlocks > 0 && t.Consensus.NumProcessing() < t.Params.OptimalProcessing {
t.pendingBuildBlocks--
blk, err := t.VM.BuildBlock()
if err != nil {
t.Ctx.Log.Debug("failed building block",
zap.Error(err),
)
t.numBuildsFailed.Inc()
return nil
}
t.numBuilt.Inc()
// a newly created block is expected to be processing. If this check
// fails, there is potentially an error in the VM this engine is running
if status := blk.Status(); status != choices.Processing {
t.Ctx.Log.Warn("attempting to issue block with unexpected status",
zap.Stringer("expectedStatus", choices.Processing),
zap.Stringer("status", status),
)
}
// The newly created block should be built on top of the preferred block.
// Otherwise, the new block doesn't have the best chance of being confirmed.
parentID := blk.Parent()
if pref := t.Consensus.Preference(); parentID != pref {
t.Ctx.Log.Warn("built block with unexpected parent",
zap.Stringer("expectedParentID", pref),
zap.Stringer("parentID", parentID),
)
}
added, err := t.issueWithAncestors(blk)
if err != nil {
return err
}
// issuing the block shouldn't have any missing dependencies
if added {
t.Ctx.Log.Verbo("successfully issued new block from the VM")
} else {
t.Ctx.Log.Warn("built block with unissued ancestors")
}
}
return nil
}
// Issue another poll to the network, asking what it prefers given the block we prefer.
// Helps move consensus along.
func (t *Transitive) repoll() {
// if we are issuing a repoll, we should gossip our current preferences to
// propagate the most likely branch as quickly as possible
prefID := t.Consensus.Preference()
for i := t.polls.Len(); i < t.Params.ConcurrentRepolls; i++ {
t.pullQuery(prefID)
}
}
// issueFromByID attempts to issue the branch ending with a block [blkID] into consensus.
// If we do not have [blkID], request it.
// Returns true if the block is processing in consensus or is decided.
func (t *Transitive) issueFromByID(nodeID ids.NodeID, blkID ids.ID) (bool, error) {
blk, err := t.GetBlock(blkID)
if err != nil {
t.sendRequest(nodeID, blkID)
return false, nil
}
return t.issueFrom(nodeID, blk)
}
// issueFrom attempts to issue the branch ending with block [blkID] to consensus.
// Returns true if the block is processing in consensus or is decided.
// If a dependency is missing, request it from [vdr].
func (t *Transitive) issueFrom(nodeID ids.NodeID, blk snowman.Block) (bool, error) {
blkID := blk.ID()
// issue [blk] and its ancestors to consensus.
for !t.wasIssued(blk) {
if err := t.issue(blk); err != nil {
return false, err
}
blkID = blk.Parent()
var err error
blk, err = t.GetBlock(blkID)
// If we don't have this ancestor, request it from [vdr]
if err != nil || !blk.Status().Fetched() {
t.sendRequest(nodeID, blkID)
return false, nil
}
}
// Remove any outstanding requests for this block
t.blkReqs.RemoveAny(blkID)
issued := t.Consensus.Decided(blk) || t.Consensus.Processing(blkID)
if issued {
// A dependency should never be waiting on a decided or processing
// block. However, if the block was marked as rejected by the VM, the
// dependencies may still be waiting. Therefore, they should abandoned.
t.blocked.Abandon(blkID)
}
// Tracks performance statistics
t.metrics.numRequests.Set(float64(t.blkReqs.Len()))
t.metrics.numBlockers.Set(float64(t.blocked.Len()))
return issued, t.errs.Err
}
// issueWithAncestors attempts to issue the branch ending with [blk] to consensus.
// Returns true if the block is processing in consensus or is decided.
// If a dependency is missing and the dependency hasn't been requested, the issuance will be abandoned.
func (t *Transitive) issueWithAncestors(blk snowman.Block) (bool, error) {
blkID := blk.ID()
// issue [blk] and its ancestors into consensus
status := blk.Status()
for status.Fetched() && !t.wasIssued(blk) {
if err := t.issue(blk); err != nil {
return false, err
}
blkID = blk.Parent()
var err error
if blk, err = t.GetBlock(blkID); err != nil {
status = choices.Unknown
break
}
status = blk.Status()
}
// The block was issued into consensus. This is the happy path.
if status != choices.Unknown && (t.Consensus.Decided(blk) || t.Consensus.Processing(blkID)) {
return true, nil
}
// There's an outstanding request for this block.
// We can just wait for that request to succeed or fail.
if t.blkReqs.Contains(blkID) {
return false, nil
}
// We don't have this block and have no reason to expect that we will get it.
// Abandon the block to avoid a memory leak.
t.blocked.Abandon(blkID)
t.metrics.numBlockers.Set(float64(t.blocked.Len()))
return false, t.errs.Err
}
// If the block has been decided, then it is marked as having been issued.
// If the block is processing, then it was issued.
// If the block is queued to be added to consensus, then it was issued.
func (t *Transitive) wasIssued(blk snowman.Block) bool {
blkID := blk.ID()
return t.Consensus.Decided(blk) || t.Consensus.Processing(blkID) || t.pendingContains(blkID)
}
// Issue [blk] to consensus once its ancestors have been issued.
func (t *Transitive) issue(blk snowman.Block) error {
blkID := blk.ID()
// mark that the block is queued to be added to consensus once its ancestors have been
t.pending[blkID] = blk
// Remove any outstanding requests for this block
t.blkReqs.RemoveAny(blkID)
// Will add [blk] to consensus once its ancestors have been
i := &issuer{
t: t,
blk: blk,
}
// block on the parent if needed
parentID := blk.Parent()
if parent, err := t.GetBlock(parentID); err != nil || !(t.Consensus.Decided(parent) || t.Consensus.Processing(parentID)) {
t.Ctx.Log.Verbo("block waiting for parent to be issued",
zap.Stringer("blkID", blkID),
zap.Stringer("parentID", parentID),
)
i.deps.Add(parentID)
}
t.blocked.Register(i)
// Tracks performance statistics
t.metrics.numRequests.Set(float64(t.blkReqs.Len()))
t.metrics.numBlocked.Set(float64(len(t.pending)))
t.metrics.numBlockers.Set(float64(t.blocked.Len()))
return t.errs.Err
}
// Request that [vdr] send us block [blkID]
func (t *Transitive) sendRequest(nodeID ids.NodeID, blkID ids.ID) {
// There is already an outstanding request for this block
if t.blkReqs.Contains(blkID) {
return
}
t.RequestID++
t.blkReqs.Add(nodeID, t.RequestID, blkID)
t.Ctx.Log.Verbo("sending Get request",
zap.Stringer("nodeID", nodeID),
zap.Uint32("requestID", t.RequestID),
zap.Stringer("blkID", blkID),
)
t.Sender.SendGet(nodeID, t.RequestID, blkID)
// Tracks performance statistics
t.metrics.numRequests.Set(float64(t.blkReqs.Len()))
}
// send a pull query for this block ID
func (t *Transitive) pullQuery(blkID ids.ID) {
t.Ctx.Log.Verbo("sampling from validators",
zap.Stringer("validators", t.Validators),
)
// The validators we will query
vdrs, err := t.Validators.Sample(t.Params.K)
if err != nil {
t.Ctx.Log.Error("dropped query for block",
zap.String("reason", "insufficient number of validators"),
zap.Stringer("blkID", blkID),
)
return
}
vdrBag := ids.NodeIDBag{}
for _, vdr := range vdrs {
vdrBag.Add(vdr.ID())
}
t.RequestID++
if t.polls.Add(t.RequestID, vdrBag) {
vdrList := vdrBag.List()
vdrSet := set.NewSet[ids.NodeID](len(vdrList))
vdrSet.Add(vdrList...)
t.Sender.SendPullQuery(vdrSet, t.RequestID, blkID)
}
}
// Send a query for this block. Some validators will be sent
// a Push Query and some will be sent a Pull Query.
func (t *Transitive) sendMixedQuery(blk snowman.Block) {
t.Ctx.Log.Verbo("sampling from validators",
zap.Stringer("validators", t.Validators),
)
vdrs, err := t.Validators.Sample(t.Params.K)
if err != nil {
t.Ctx.Log.Error("dropped query for block",
zap.String("reason", "insufficient number of validators"),
zap.Stringer("blkID", blk.ID()),
)
return
}
vdrBag := ids.NodeIDBag{}
for _, vdr := range vdrs {
vdrBag.Add(vdr.ID())
}
t.RequestID++
if t.polls.Add(t.RequestID, vdrBag) {
// Send a push query to some of the validators, and a pull query to the rest.
numPushTo := t.Params.MixedQueryNumPushVdr
if !t.Validators.Contains(t.Ctx.NodeID) {
numPushTo = t.Params.MixedQueryNumPushNonVdr
}
common.SendMixedQuery(
t.Sender,
vdrBag.List(), // Note that this doesn't contain duplicates; length may be < k
numPushTo,
t.RequestID,
blk.ID(),
blk.Bytes(),
)
}
}
// issue [blk] to consensus
func (t *Transitive) deliver(blk snowman.Block) error {
blkID := blk.ID()
if t.Consensus.Decided(blk) || t.Consensus.Processing(blkID) {
return nil
}
// we are no longer waiting on adding the block to consensus, so it is no
// longer pending
t.removeFromPending(blk)
parentID := blk.Parent()
parent, err := t.GetBlock(parentID)
// Because the dependency must have been fulfilled by the time this function
// is called - we don't expect [err] to be non-nil. But it is handled for
// completness and future proofing.
if err != nil || !(parent.Status() == choices.Accepted || t.Consensus.Processing(parentID)) {
// if the parent isn't processing or the last accepted block, then this
// block is effectively rejected
t.blocked.Abandon(blkID)
t.metrics.numBlocked.Set(float64(len(t.pending))) // Tracks performance statistics
t.metrics.numBlockers.Set(float64(t.blocked.Len()))
return t.errs.Err
}
// By ensuring that the parent is either processing or accepted, it is
// guaranteed that the parent was successfully verified. This means that
// calling Verify on this block is allowed.
// make sure this block is valid
if err := blk.Verify(); err != nil {
t.Ctx.Log.Debug("block verification failed",
zap.Error(err),
)
// if verify fails, then all descendants are also invalid
t.addToNonVerifieds(blk)
t.blocked.Abandon(blkID)
t.metrics.numBlocked.Set(float64(len(t.pending))) // Tracks performance statistics
t.metrics.numBlockers.Set(float64(t.blocked.Len()))
return t.errs.Err
}
t.nonVerifieds.Remove(blkID)
t.metrics.numNonVerifieds.Set(float64(t.nonVerifieds.Len()))
t.Ctx.Log.Verbo("adding block to consensus",
zap.Stringer("blkID", blkID),
)
wrappedBlk := &memoryBlock{
Block: blk,
metrics: &t.metrics,
tree: t.nonVerifieds,
}
if err := t.Consensus.Add(wrappedBlk); err != nil {
return err
}
// Add all the oracle blocks if they exist. We call verify on all the blocks
// and add them to consensus before marking anything as fulfilled to avoid
// any potential reentrant bugs.
added := []snowman.Block{}
dropped := []snowman.Block{}
if blk, ok := blk.(snowman.OracleBlock); ok {
options, err := blk.Options()
if err != snowman.ErrNotOracle {
if err != nil {
return err
}
for _, blk := range options {
if err := blk.Verify(); err != nil {
t.Ctx.Log.Debug("block verification failed",
zap.Error(err),
)
dropped = append(dropped, blk)
// block fails verification, hold this in memory for bubbling
t.addToNonVerifieds(blk)
} else {
// correctly verified will be passed to consensus as processing block
// no need to keep it anymore
t.nonVerifieds.Remove(blk.ID())
t.metrics.numNonVerifieds.Set(float64(t.nonVerifieds.Len()))
wrappedBlk := &memoryBlock{
Block: blk,
metrics: &t.metrics,
tree: t.nonVerifieds,
}
if err := t.Consensus.Add(wrappedBlk); err != nil {
return err
}
added = append(added, blk)
}
}
}
}
if err := t.VM.SetPreference(t.Consensus.Preference()); err != nil {
return err
}
// If the block is now preferred, query the network for its preferences
// with this new block.
if t.Consensus.IsPreferred(blk) {
t.sendMixedQuery(blk)
}
t.blocked.Fulfill(blkID)
for _, blk := range added {
if t.Consensus.IsPreferred(blk) {
t.sendMixedQuery(blk)
}
blkID := blk.ID()
t.removeFromPending(blk)
t.blocked.Fulfill(blkID)
t.blkReqs.RemoveAny(blkID)
}
for _, blk := range dropped {
blkID := blk.ID()
t.removeFromPending(blk)
t.blocked.Abandon(blkID)
t.blkReqs.RemoveAny(blkID)
}
// If we should issue multiple queries at the same time, we need to repoll
t.repoll()
// Tracks performance statistics
t.metrics.numRequests.Set(float64(t.blkReqs.Len()))
t.metrics.numBlocked.Set(float64(len(t.pending)))
t.metrics.numBlockers.Set(float64(t.blocked.Len()))
return t.errs.Err
}
// Returns true if the block whose ID is [blkID] is waiting to be issued to consensus
func (t *Transitive) pendingContains(blkID ids.ID) bool {
_, ok := t.pending[blkID]
return ok
}
func (t *Transitive) removeFromPending(blk snowman.Block) {
delete(t.pending, blk.ID())
}
func (t *Transitive) addToNonVerifieds(blk snowman.Block) {
// don't add this blk if it's decided or processing.
blkID := blk.ID()
if t.Consensus.Decided(blk) || t.Consensus.Processing(blkID) {
return
}
parentID := blk.Parent()
// we might still need this block so we can bubble votes to the parent
// only add blocks with parent already in the tree or processing.
// decided parents should not be in this map.
if t.nonVerifieds.Has(parentID) || t.Consensus.Processing(parentID) {
t.nonVerifieds.Add(blkID, parentID)
t.metrics.numNonVerifieds.Set(float64(t.nonVerifieds.Len()))
}
}