-
Notifications
You must be signed in to change notification settings - Fork 7
/
host.go
767 lines (686 loc) · 24 KB
/
host.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
package f3
import (
"context"
"errors"
"fmt"
"slices"
"sync"
"time"
"github.com/filecoin-project/go-f3/certs"
"github.com/filecoin-project/go-f3/certstore"
"github.com/filecoin-project/go-f3/ec"
"github.com/filecoin-project/go-f3/gpbft"
"github.com/filecoin-project/go-f3/internal/clock"
"github.com/filecoin-project/go-f3/internal/psutil"
"github.com/filecoin-project/go-f3/internal/writeaheadlog"
"github.com/filecoin-project/go-f3/manifest"
pubsub "github.com/libp2p/go-libp2p-pubsub"
"github.com/libp2p/go-libp2p/core/peer"
"go.uber.org/multierr"
"golang.org/x/sync/errgroup"
)
type BroadcastMessage func(*gpbft.MessageBuilder)
// gpbftRunner is responsible for running gpbft.Participant, taking in all concurrent events and
// passing them to gpbft in a single thread.
type gpbftRunner struct {
certStore *certstore.Store
manifest *manifest.Manifest
ec ec.Backend
pubsub *pubsub.PubSub
clock clock.Clock
verifier gpbft.Verifier
wal *writeaheadlog.WriteAheadLog[walEntry, *walEntry]
outMessages chan<- *gpbft.MessageBuilder
equivFilter equivocationFilter
participant *gpbft.Participant
topic *pubsub.Topic
alertTimer *clock.Timer
runningCtx context.Context
errgrp *errgroup.Group
ctxCancel context.CancelFunc
// msgsMutex guards access to selfMessages
msgsMutex sync.Mutex
selfMessages map[uint64]map[roundPhase][]*gpbft.GMessage
inputs gpbftInputs
msgEncoding gMessageEncoding
}
type roundPhase struct {
round uint64
phase gpbft.Phase
}
func newRunner(
ctx context.Context,
cs *certstore.Store,
ec ec.Backend,
ps *pubsub.PubSub,
verifier gpbft.Verifier,
out chan<- *gpbft.MessageBuilder,
m *manifest.Manifest,
wal *writeaheadlog.WriteAheadLog[walEntry, *walEntry],
pID peer.ID,
) (*gpbftRunner, error) {
runningCtx, ctxCancel := context.WithCancel(context.WithoutCancel(ctx))
errgrp, runningCtx := errgroup.WithContext(runningCtx)
runner := &gpbftRunner{
certStore: cs,
manifest: m,
ec: ec,
pubsub: ps,
clock: clock.GetClock(ctx),
verifier: verifier,
wal: wal,
outMessages: out,
runningCtx: runningCtx,
errgrp: errgrp,
ctxCancel: ctxCancel,
equivFilter: newEquivocationFilter(pID),
selfMessages: make(map[uint64]map[roundPhase][]*gpbft.GMessage),
inputs: newInputs(m, cs, ec, verifier, clock.GetClock(ctx)),
}
// create a stopped timer to facilitate alerts requested from gpbft
runner.alertTimer = runner.clock.Timer(0)
if !runner.alertTimer.Stop() {
<-runner.alertTimer.C
}
walEntries, err := wal.All()
if err != nil {
return nil, fmt.Errorf("reading WAL: %w", err)
}
var maxInstance uint64
for _, v := range walEntries {
runner.equivFilter.ProcessBroadcast(v.Message)
instance := v.Message.Vote.Instance
if runner.selfMessages[instance] == nil {
runner.selfMessages[instance] = make(map[roundPhase][]*gpbft.GMessage)
}
// WAL is dumb. To avoid relying on it returning sorted entries or making it
// searchable add all messages, then trim down to the last instance.
key := roundPhase{
round: v.Message.Vote.Round,
phase: v.Message.Vote.Phase,
}
runner.selfMessages[instance][key] = append(runner.selfMessages[instance][key], v.Message)
maxInstance = max(maxInstance, instance)
}
// Trim down to the largest instance.
for instance := range runner.selfMessages {
if instance < maxInstance {
delete(runner.selfMessages, instance)
}
}
log.Infof("Starting gpbft runner")
opts := append(m.GpbftOptions(), gpbft.WithTracer(tracer))
p, err := gpbft.NewParticipant((*gpbftHost)(runner), opts...)
if err != nil {
return nil, fmt.Errorf("creating participant: %w", err)
}
runner.participant = p
if runner.manifest.PubSub.CompressionEnabled {
runner.msgEncoding, err = newZstdGMessageEncoding()
if err != nil {
return nil, err
}
} else {
runner.msgEncoding = &cborGMessageEncoding{}
}
return runner, nil
}
func (h *gpbftRunner) Start(ctx context.Context) (_err error) {
defer func() {
if _err != nil {
_err = multierr.Append(_err, h.Stop(ctx))
}
}()
messageQueue, err := h.startPubsub()
if err != nil {
return err
}
finalityCertificates, unsubCerts := h.certStore.Subscribe()
select {
case c := <-finalityCertificates:
if err := h.receiveCertificate(c); err != nil {
log.Errorf("error when receiving certificate: %+v", err)
}
default:
if err := h.startInstanceAt(h.manifest.InitialInstance, h.clock.Now()); err != nil {
log.Errorf("error when starting instance %d: %+v", h.manifest.InitialInstance, err)
}
}
h.errgrp.Go(func() (_err error) {
defer func() {
unsubCerts()
if _err != nil && h.runningCtx.Err() == nil {
log.Errorf("exited GPBFT runner early: %+v", _err)
}
}()
for h.runningCtx.Err() == nil {
// prioritise finality certificates and alarm delivery
select {
case c := <-finalityCertificates:
if err := h.receiveCertificate(c); err != nil {
log.Errorf("error when recieving certificate: %+v", err)
}
continue
case <-h.alertTimer.C:
if err := h.participant.ReceiveAlarm(); err != nil {
// TODO: Probably want to just abort the instance and wait
// for a finality certificate at this point?
log.Errorf("error when receiving alarm: %+v", err)
}
continue
default:
}
// Handle messages, finality certificates, and alarms
select {
case c := <-finalityCertificates:
if err := h.receiveCertificate(c); err != nil {
log.Errorf("error when recieving certificate: %+v", err)
}
case <-h.alertTimer.C:
if err := h.participant.ReceiveAlarm(); err != nil {
// TODO: Probably want to just abort the instance and wait
// for a finality certificate at this point?
log.Errorf("error when receiving alarm: %+v", err)
}
case msg, ok := <-messageQueue:
if !ok {
return fmt.Errorf("incoming message queue closed")
}
if err := h.participant.ReceiveMessage(msg); err != nil {
// We silently drop failed messages because GPBFT will
// return errors for, e.g., messages from old instances.
// Given the async nature of our pubsub message handling, we
// could easily receive these.
// TODO: we need to distinguish between "fatal" and
// "non-fatal" errors here. Ideally only returning "real"
// errors.
log.Errorf("error when processing message: %+v", err)
}
case <-h.runningCtx.Done():
return nil
}
}
return nil
})
// Asynchronously checkpoint the decided tipset keys by explicitly making a
// separate subscription to the cert store. This may cause a sync in a case where
// the finalized tipset is not already stored by the chain store, which is a
// blocking operation. Hence, the asynchronous checkpointing.
//
// Note, there is no guarantee that every finalized tipset will be checkpointed.
// Because:
// 1. the subscription only returns the latest certificate, i.e. may
// miss intermediate certificates, and
// 2. errors that may occur during checkpointing are silently logged
// to allow checkpointing of future finality certificates.
//
// Triggering the checkpointing here means that certstore remains the sole source
// of truth in terms of tipsets that have been finalised.
finalize, unsubFinalize := h.certStore.Subscribe()
h.errgrp.Go(func() error {
defer unsubFinalize()
for h.runningCtx.Err() == nil {
select {
case <-h.runningCtx.Done():
return nil
case cert, ok := <-finalize:
if !ok {
// This should never happen according to certstore subscribe semantic. If it
// does, error loudly since the chances are the cause is a programmer error.
return errors.New("cert store subscription to finalize tipsets was closed unexpectedly")
}
if h.manifest.EC.Finalize {
key := cert.ECChain.Head().Key
if err := h.ec.Finalize(h.runningCtx, key); err != nil {
// There is not much we can do here other than logging. The next instance start
// will effectively retry checkpointing the latest finalized tipset. This error
// will not impact the selection of next instance chain.
log.Errorf("error while finalizing decision at EC: %+v", err)
}
} else {
ts := cert.ECChain.Head()
log.Infow("skipping finalization of a new head because the current manifest specifies that tipsets should not be finalized",
"tsk", ts.Key,
"epoch", ts.Epoch,
)
}
const keepInstancesInWAL = 5
if cert.GPBFTInstance > keepInstancesInWAL {
err := h.wal.Purge(cert.GPBFTInstance - keepInstancesInWAL)
if err != nil {
log.Errorw("failed to purge messages from WAL", "error", err)
}
}
h.msgsMutex.Lock()
for instance := range h.selfMessages {
if instance < cert.GPBFTInstance {
delete(h.selfMessages, instance)
}
}
h.msgsMutex.Unlock()
}
}
return nil
})
return nil
}
func (h *gpbftRunner) receiveCertificate(c *certs.FinalityCertificate) error {
nextInstance := c.GPBFTInstance + 1
currentInstance := h.participant.Progress().ID
if currentInstance >= nextInstance {
return nil
}
log.Debugw("skipping forwards based on cert", "from", currentInstance, "to", nextInstance)
nextInstanceStart := h.computeNextInstanceStart(c)
return h.startInstanceAt(nextInstance, nextInstanceStart)
}
func (h *gpbftRunner) startInstanceAt(instance uint64, at time.Time) error {
// Look for any existing messages in WAL for the next instance, and if there is
// any replay them to self to aid the participant resume progress when possible.
//
// Collect the replay messages first then replay them to avid holding the lock
// for too long if for whatever reason validate/receive is slow.
var replay []*gpbft.GMessage
h.msgsMutex.Lock()
if messages, found := h.selfMessages[instance]; found {
replay = make([]*gpbft.GMessage, 0, len(messages))
for _, message := range messages {
replay = append(replay, message...)
}
}
h.msgsMutex.Unlock()
// Order of messages does not matter to GPBFT. But sort them in ascending order
// of instance, round, phase, sender for a more optimal resumption.
slices.SortFunc(replay, func(one *gpbft.GMessage, other *gpbft.GMessage) int {
switch {
case one.Vote.Instance < other.Vote.Instance:
return -1
case one.Vote.Instance > other.Vote.Instance:
return 1
case one.Vote.Round < other.Vote.Round:
return -1
case one.Vote.Round > other.Vote.Round:
return 1
case one.Vote.Phase < other.Vote.Phase:
return -1
case one.Vote.Phase > other.Vote.Phase:
return 1
case one.Sender < other.Sender:
return -1
case one.Sender > other.Sender:
return 1
default:
return 0
}
})
for _, message := range replay {
if validated, err := h.participant.ValidateMessage(message); err != nil {
log.Warnw("invalid self message", "message", message, "err", err)
} else if err := h.participant.ReceiveMessage(validated); err != nil {
log.Warnw("failed to send resumption message", "message", message, "err", err)
}
}
return h.participant.StartInstanceAt(instance, at)
}
func (h *gpbftRunner) computeNextInstanceStart(cert *certs.FinalityCertificate) (_nextStart time.Time) {
ecDelay := time.Duration(h.manifest.EC.DelayMultiplier * float64(h.manifest.EC.Period))
head, err := h.ec.GetHead(h.runningCtx)
if err != nil {
// this should not happen
log.Errorf("ec.GetHead returned error: %+v", err)
return h.clock.Now().Add(ecDelay)
}
// the head of the cert becomes the new base
baseTipSet := cert.ECChain.Head()
// we are not trying to fetch the new base tipset from EC as it might not be available
// instead we compute the relative time from the EC.Head
baseTimestamp := computeTipsetTimestampAtEpoch(head, baseTipSet.Epoch, h.manifest.EC.Period)
// Try to align instances while catching up, if configured.
if h.manifest.CatchUpAlignment > 0 {
defer func() {
now := h.clock.Now()
// If we were supposed to start this instance more than one GPBFT round ago, assume
// we're behind and try to align our start times. This helps keep nodes
// in-sync when bootstrapping and catching up.
if _nextStart.Before(now.Add(-h.manifest.CatchUpAlignment)) {
delay := now.Sub(baseTimestamp)
if offset := delay % h.manifest.CatchUpAlignment; offset > 0 {
delay += h.manifest.CatchUpAlignment - offset
}
_nextStart = baseTimestamp.Add(delay)
}
}()
}
lookbackDelay := h.manifest.EC.Period * time.Duration(h.manifest.EC.HeadLookback)
if cert.ECChain.HasSuffix() {
// we decided on something new, the tipset that got finalized can at minimum be 30-60s old.
return baseTimestamp.Add(ecDelay).Add(lookbackDelay)
}
if cert.GPBFTInstance == h.manifest.InitialInstance {
// if we are at initial instance, there is no history to look at
return baseTimestamp.Add(ecDelay).Add(lookbackDelay)
}
backoffTable := h.manifest.EC.BaseDecisionBackoffTable
attempts := 0
backoffMultipler := 2.0 // baseline 1 + 1 to account for the one ECDelay after which we got the base decistion
for instance := cert.GPBFTInstance - 1; instance > h.manifest.InitialInstance; instance-- {
cert, err := h.certStore.Get(h.runningCtx, instance)
if err != nil {
log.Errorf("error while getting instance %d from certstore: %+v", instance, err)
break
}
if cert.ECChain.HasSuffix() {
break
}
attempts += 1
if attempts < len(backoffTable) {
backoffMultipler += backoffTable[attempts]
} else {
// if we are beyond backoffTable, reuse the last element
backoffMultipler += backoffTable[len(backoffTable)-1]
}
}
backoff := time.Duration(float64(ecDelay) * backoffMultipler)
log.Debugf("backing off for: %v", backoff)
return baseTimestamp.Add(backoff).Add(lookbackDelay)
}
// Sends a message to all other participants.
// The message's sender must be one that the network interface can sign on behalf of.
func (h *gpbftRunner) BroadcastMessage(ctx context.Context, msg *gpbft.GMessage) error {
if !h.equivFilter.ProcessBroadcast(msg) {
// equivocation filter does its own logging and this error just gets logged
return nil
}
err := h.wal.Append(walEntry{msg})
if err != nil {
log.Errorw("appending to WAL", "error", err)
}
h.msgsMutex.Lock()
if h.selfMessages[msg.Vote.Instance] == nil {
h.selfMessages[msg.Vote.Instance] = make(map[roundPhase][]*gpbft.GMessage)
}
key := roundPhase{
round: msg.Vote.Round,
phase: msg.Vote.Phase,
}
h.selfMessages[msg.Vote.Instance][key] = append(h.selfMessages[msg.Vote.Instance][key], msg)
h.msgsMutex.Unlock()
if h.topic == nil {
return pubsub.ErrTopicClosed
}
encoded, err := h.msgEncoding.Encode(msg)
if err != nil {
return fmt.Errorf("encoding GMessage for broadcast: %w", err)
}
err = h.topic.Publish(ctx, encoded)
if err != nil {
return fmt.Errorf("publishing message: %w", err)
}
return nil
}
func (h *gpbftRunner) rebroadcastMessage(msg *gpbft.GMessage) error {
if !h.equivFilter.ProcessBroadcast(msg) {
// equivocation filter does its own logging and this error just gets logged
return nil
}
if h.topic == nil {
return pubsub.ErrTopicClosed
}
encoded, err := h.msgEncoding.Encode(msg)
if err != nil {
return fmt.Errorf("encoding GMessage for broadcast: %w", err)
}
if err := h.topic.Publish(h.runningCtx, encoded); err != nil {
return fmt.Errorf("publishing message: %w", err)
}
return nil
}
var _ pubsub.ValidatorEx = (*gpbftRunner)(nil).validatePubsubMessage
func (h *gpbftRunner) validatePubsubMessage(ctx context.Context, _ peer.ID, msg *pubsub.Message) (_result pubsub.ValidationResult) {
defer func(start time.Time) {
recordValidationTime(ctx, start, _result)
}(time.Now())
gmsg, err := h.msgEncoding.Decode(msg.Data)
if err != nil {
log.Debugw("failed to decode message", "from", msg.GetFrom(), "err", err)
return pubsub.ValidationReject
}
switch validatedMessage, err := h.participant.ValidateMessage(gmsg); {
case errors.Is(err, gpbft.ErrValidationInvalid):
log.Debugf("validation error during validation: %+v", err)
return pubsub.ValidationReject
case errors.Is(err, gpbft.ErrValidationTooOld):
// we got the message too late
return pubsub.ValidationIgnore
case errors.Is(err, gpbft.ErrValidationNotRelevant):
// The message is valid but will not effectively aid progress of GPBFT. Ignore it
// to stop its further propagation across the network.
return pubsub.ValidationIgnore
case errors.Is(err, gpbft.ErrValidationNoCommittee):
log.Debugf("commitee error during validation: %+v", err)
return pubsub.ValidationIgnore
case err != nil:
log.Infof("unknown error during validation: %+v", err)
return pubsub.ValidationIgnore
default:
recordValidatedMessage(ctx, validatedMessage)
msg.ValidatorData = validatedMessage
return pubsub.ValidationAccept
}
}
func (h *gpbftRunner) setupPubsub() error {
pubsubTopicName := h.manifest.PubSubTopic()
err := h.pubsub.RegisterTopicValidator(pubsubTopicName, h.validatePubsubMessage)
if err != nil {
return fmt.Errorf("registering topic validator: %w", err)
}
// Force the default (sender + seqno) message de-duplication mechanism instead of hashing
// the message (as lotus does) as we need to be able to re-broadcast duplicate messages with
// the same content.
topic, err := h.pubsub.Join(pubsubTopicName, pubsub.WithTopicMessageIdFn(psutil.GPBFTMessageIdFn))
if err != nil {
return fmt.Errorf("could not join on pubsub topic: %s: %w", pubsubTopicName, err)
}
if err := topic.SetScoreParams(psutil.PubsubTopicScoreParams); err != nil {
log.Infow("failed to set topic score params", "error", err)
}
h.topic = topic
return nil
}
func (h *gpbftRunner) teardownPubsub() error {
var err error
if h.topic != nil {
err = multierr.Combine(
h.topic.Close(),
h.pubsub.UnregisterTopicValidator(h.topic.String()),
)
if errors.Is(err, context.Canceled) {
err = nil
}
}
return err
}
func (h *gpbftRunner) startPubsub() (<-chan gpbft.ValidatedMessage, error) {
if err := h.setupPubsub(); err != nil {
return nil, err
}
const (
subBufferSize = 128
msgQueueBufferSize = 128
)
sub, err := h.topic.Subscribe(pubsub.WithBufferSize(subBufferSize))
if err != nil {
return nil, fmt.Errorf("could not subscribe to pubsub topic: %s: %w", sub.Topic(), err)
}
messageQueue := make(chan gpbft.ValidatedMessage, msgQueueBufferSize)
h.errgrp.Go(func() error {
defer func() {
sub.Cancel()
close(messageQueue)
}()
for h.runningCtx.Err() == nil {
var msg *pubsub.Message
msg, err := sub.Next(h.runningCtx)
if err != nil {
if h.runningCtx.Err() != nil {
return nil
}
return fmt.Errorf("pubsub message subscription returned an error: %w", err)
}
gmsg, ok := msg.ValidatorData.(gpbft.ValidatedMessage)
if !ok {
log.Errorf("invalid msgValidatorData: %+v", msg.ValidatorData)
continue
}
select {
case messageQueue <- gmsg:
case <-h.runningCtx.Done():
return nil
}
}
return nil
})
return messageQueue, nil
}
var (
_ gpbft.Host = (*gpbftHost)(nil)
_ gpbft.Progress = (*gpbftRunner)(nil).Progress
)
// gpbftHost is a newtype of gpbftRunner exposing APIs required by the gpbft.Participant
type gpbftHost gpbftRunner
func (h *gpbftHost) RequestRebroadcast(instant gpbft.Instant) error {
var rebroadcasts []*gpbft.GMessage
h.msgsMutex.Lock()
if roundPhaseMessages, found := h.selfMessages[instant.ID]; found {
if messages, found := roundPhaseMessages[roundPhase{round: instant.Round, phase: instant.Phase}]; found {
rebroadcasts = slices.Clone(messages)
}
}
h.msgsMutex.Unlock()
var err error
if len(rebroadcasts) > 0 {
obfuscatedHost := (*gpbftRunner)(h)
for _, message := range rebroadcasts {
err = multierr.Append(err, obfuscatedHost.rebroadcastMessage(message))
}
}
return err
}
func (h *gpbftHost) GetProposal(instance uint64) (*gpbft.SupplementalData, gpbft.ECChain, error) {
return h.inputs.GetProposal(h.runningCtx, instance)
}
func (h *gpbftHost) GetCommittee(instance uint64) (*gpbft.Committee, error) {
return h.inputs.GetCommittee(h.runningCtx, instance)
}
func (h *gpbftRunner) Stop(context.Context) error {
h.ctxCancel()
return multierr.Combine(
h.wal.Close(),
h.errgrp.Wait(),
h.teardownPubsub(),
)
}
// Progress returns the latest progress of GPBFT consensus in terms of instance
// ID, round and phase.
//
// This API is safe for concurrent use.
func (h *gpbftRunner) Progress() gpbft.Instant {
return h.participant.Progress()
}
// Returns the network's name (for signature separation)
func (h *gpbftHost) NetworkName() gpbft.NetworkName {
return h.manifest.NetworkName
}
// Sends a message to all other participants.
func (h *gpbftHost) RequestBroadcast(mb *gpbft.MessageBuilder) error {
select {
case h.outMessages <- mb:
return nil
case <-h.runningCtx.Done():
return h.runningCtx.Err()
}
}
// Returns the current network time.
func (h *gpbftHost) Time() time.Time {
return h.clock.Now()
}
// Sets an alarm to fire after the given timestamp.
// At most one alarm can be set at a time.
// Setting an alarm replaces any previous alarm that has not yet fired.
// The timestamp may be in the past, in which case the alarm will fire as soon as possible
// (but not synchronously).
func (h *gpbftHost) SetAlarm(at time.Time) {
log.Debugf("set alarm for %v", at)
// we cannot reuse the timer because we don't know if it was read or not
h.alertTimer.Stop()
if at.IsZero() {
// If "at" is zero, we cancel the timer entirely. Unfortunately, we still have to
// replace it for the reason stated above.
h.alertTimer = h.clock.Timer(0)
if !h.alertTimer.Stop() {
<-h.alertTimer.C
}
} else {
h.alertTimer = h.clock.Timer(max(0, h.clock.Until(at)))
}
}
// Receives a finality decision from the instance, with signatures from a strong quorum
// of participants justifying it.
// The decision payload always has round = 0 and phase = DECIDE.
// The notification must return the timestamp at which the next instance should begin,
// based on the decision received (which may be in the past).
// E.g. this might be: finalised tipset timestamp + epoch duration + stabilisation delay.
func (h *gpbftHost) ReceiveDecision(decision *gpbft.Justification) (time.Time, error) {
log.Infow("reached a decision", "instance", decision.Vote.Instance,
"ecHeadEpoch", decision.Vote.Value.Head().Epoch)
cert, err := h.saveDecision(decision)
if err != nil {
err := fmt.Errorf("error while saving decision: %+v", err)
log.Error(err)
return time.Time{}, err
}
return (*gpbftRunner)(h).computeNextInstanceStart(cert), nil
}
func (h *gpbftHost) saveDecision(decision *gpbft.Justification) (*certs.FinalityCertificate, error) {
instance := decision.Vote.Instance
current, err := h.GetCommittee(instance)
if err != nil {
return nil, fmt.Errorf("getting commitee for current instance %d: %w", instance, err)
}
next, err := h.GetCommittee(instance + 1)
if err != nil {
return nil, fmt.Errorf("getting commitee for next instance %d: %w", instance+1, err)
}
powerDiff := certs.MakePowerTableDiff(current.PowerTable.Entries, next.PowerTable.Entries)
cert, err := certs.NewFinalityCertificate(powerDiff, decision)
if err != nil {
return nil, fmt.Errorf("forming certificate out of decision: %w", err)
}
_, _, _, err = certs.ValidateFinalityCertificates(h, h.NetworkName(), current.PowerTable.Entries, decision.Vote.Instance, nil, cert)
if err != nil {
return nil, fmt.Errorf("certificate is invalid: %w", err)
}
err = h.certStore.Put(h.runningCtx, cert)
if err != nil {
return nil, fmt.Errorf("saving ceritifcate in a store: %w", err)
}
return cert, nil
}
// MarshalPayloadForSigning marshals the given payload into the bytes that should be signed.
// This should usually call `Payload.MarshalForSigning(NetworkName)` except when testing as
// that method is slow (computes a merkle tree that's necessary for testing).
func (h *gpbftHost) MarshalPayloadForSigning(nn gpbft.NetworkName, p *gpbft.Payload) []byte {
if m, ok := h.verifier.(gpbft.SigningMarshaler); ok {
return m.MarshalPayloadForSigning(nn, p)
} else {
return p.MarshalForSigning(nn)
}
}
// Verifies a signature for the given public key.
// Implementations must be safe for concurrent use.
func (h *gpbftHost) Verify(pubKey gpbft.PubKey, msg []byte, sig []byte) error {
return h.verifier.Verify(pubKey, msg, sig)
}
func (h *gpbftHost) Aggregate(pubKeys []gpbft.PubKey) (gpbft.Aggregate, error) {
return h.verifier.Aggregate(pubKeys)
}