-
Notifications
You must be signed in to change notification settings - Fork 211
/
hare.go
677 lines (599 loc) · 18.7 KB
/
hare.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
package hare
import (
"context"
"errors"
"fmt"
"math"
"sync"
"time"
"golang.org/x/sync/errgroup"
"github.com/spacemeshos/go-spacemesh/codec"
"github.com/spacemeshos/go-spacemesh/common/types"
"github.com/spacemeshos/go-spacemesh/datastore"
"github.com/spacemeshos/go-spacemesh/hare/config"
"github.com/spacemeshos/go-spacemesh/log"
"github.com/spacemeshos/go-spacemesh/p2p/pubsub"
"github.com/spacemeshos/go-spacemesh/signing"
"github.com/spacemeshos/go-spacemesh/sql"
"github.com/spacemeshos/go-spacemesh/sql/ballots"
"github.com/spacemeshos/go-spacemesh/sql/layers"
"github.com/spacemeshos/go-spacemesh/sql/proposals"
"github.com/spacemeshos/go-spacemesh/system"
)
type consensusFactory func(
context.Context,
config.Config,
types.LayerID,
*Set,
Rolacle,
*signing.EdSigner,
*types.VRFPostIndex,
pubsub.Publisher,
communication,
RoundClock,
) Consensus
// Consensus represents an item that acts like a consensus process.
type Consensus interface {
ID() types.LayerID
Start()
Stop()
}
// TerminationOutput represents an output of a consensus process.
type TerminationOutput interface {
ID() types.LayerID
Set() *Set
Coinflip() bool
Completed() bool
}
// RoundClock is a timer interface.
type RoundClock interface {
AwaitWakeup() <-chan struct{}
// RoundEnd returns the time at which round ends, passing round-1 will
// return the time at which round starts.
RoundEnd(round uint32) time.Time
AwaitEndOfRound(round uint32) <-chan struct{}
}
// LayerClock provides a timer for the start of a given layer, as well as the current layer and allows converting a
// layer number to a clock time.
type LayerClock interface {
LayerToTime(types.LayerID) time.Time
AwaitLayer(types.LayerID) chan struct{}
CurrentLayer() types.LayerID
}
// LayerOutput is the output of each hare consensus process.
type LayerOutput struct {
Ctx context.Context
Layer types.LayerID
Proposals []types.ProposalID
}
type defaultMesh struct {
*datastore.CachedDB
}
func (m defaultMesh) Proposals(lid types.LayerID) ([]*types.Proposal, error) {
return proposals.GetByLayer(m, lid)
}
func (m defaultMesh) Ballot(bid types.BallotID) (*types.Ballot, error) {
return ballots.Get(m, bid)
}
func (m defaultMesh) SetWeakCoin(lid types.LayerID, wc bool) error {
return layers.SetWeakCoin(m, lid, wc)
}
// Opt for configuring beacon protocol.
type Opt func(*Hare)
func withMesh(m mesh) Opt {
return func(h *Hare) {
h.msh = m
}
}
// Hare is the orchestrator that starts new consensus processes and collects their output.
type Hare struct {
log.Log
msh mesh
config config.Config
publisher pubsub.Publisher
layerClock LayerClock
broker *Broker
sign *signing.EdSigner
blockGenCh chan LayerOutput
// channel to receive MalfeasanceGossip generated by the broker and the consensus processes.
mchMalfeasance chan *types.MalfeasanceGossip
beacons system.BeaconGetter
rolacle Rolacle
patrol layerPatrol
newRoundClock func(LayerID types.LayerID) RoundClock
networkDelta time.Duration
outputChan chan TerminationOutput
mu sync.Mutex
lastLayer types.LayerID
outputs map[types.LayerID][]types.ProposalID
cps map[types.LayerID]Consensus
factory consensusFactory
nodeID types.NodeID
ctx context.Context
cancel context.CancelFunc
eg errgroup.Group
}
// New returns a new Hare struct.
func New(
cdb *datastore.CachedDB,
conf config.Config,
publisher pubsub.PublishSubsciber,
sign *signing.EdSigner,
pke *signing.PubKeyExtractor,
nid types.NodeID,
ch chan LayerOutput,
syncState system.SyncStateProvider,
beacons system.BeaconGetter,
rolacle Rolacle,
patrol layerPatrol,
stateQ stateQuerier,
layerClock LayerClock,
logger log.Log,
opts ...Opt,
) *Hare {
h := new(Hare)
h.Log = logger
h.config = conf
h.publisher = publisher
h.layerClock = layerClock
h.newRoundClock = func(layerID types.LayerID) RoundClock {
layerTime := layerClock.LayerToTime(layerID)
wakeupDelta := conf.WakeupDelta
roundDuration := h.config.RoundDuration
h.With().Debug("creating hare round clock", layerID,
log.String("layer_time", layerTime.String()),
log.Duration("wakeup_delta", wakeupDelta),
log.Duration("round_duration", roundDuration),
)
return NewSimpleRoundClock(layerTime, wakeupDelta, roundDuration)
}
ev := newEligibilityValidator(rolacle, conf.N, conf.ExpectedLeaders, logger)
h.mchMalfeasance = make(chan *types.MalfeasanceGossip, conf.N)
h.sign = sign
h.blockGenCh = ch
h.beacons = beacons
h.rolacle = rolacle
h.patrol = patrol
h.networkDelta = conf.WakeupDelta
h.outputChan = make(chan TerminationOutput, h.config.Hdist)
h.outputs = make(map[types.LayerID][]types.ProposalID, h.config.Hdist) // we keep results about LayerBuffer past layers
h.cps = make(map[types.LayerID]Consensus, h.config.LimitConcurrent)
h.factory = func(ctx context.Context, conf config.Config, instanceId types.LayerID, s *Set, oracle Rolacle, signing *signing.EdSigner, nonce *types.VRFPostIndex, p2p pubsub.Publisher, comm communication, clock RoundClock) Consensus {
return newConsensusProcess(ctx, conf, instanceId, s, oracle, stateQ, signing, pke, nid, nonce, p2p, comm, ev, clock, logger)
}
h.nodeID = nid
h.ctx, h.cancel = context.WithCancel(context.Background())
for _, opt := range opts {
opt(h)
}
if h.msh == nil {
h.msh = defaultMesh{CachedDB: cdb}
}
h.broker = newBroker(h.msh, pke, ev, stateQ, syncState, h.mchMalfeasance, conf.LimitConcurrent, logger)
return h
}
// GetHareMsgHandler returns the gossip handler for hare protocol message.
func (h *Hare) GetHareMsgHandler() pubsub.GossipHandler {
return h.broker.HandleMessage
}
func (h *Hare) HandleEligibility(ctx context.Context, emsg *types.HareEligibilityGossip) {
h.broker.HandleEligibility(ctx, emsg)
}
func (h *Hare) getLastLayer() types.LayerID {
h.mu.Lock()
defer h.mu.Unlock()
return h.lastLayer
}
func (h *Hare) setLastLayer(layerID types.LayerID) {
if layerID == 0 {
// layers starts from 0. nothing to do here.
return
}
h.mu.Lock()
defer h.mu.Unlock()
if layerID.After(h.lastLayer) {
h.lastLayer = layerID
} else {
h.With().Error("received out of order layer tick", log.FieldNamed("last_layer", h.lastLayer))
}
}
// checks if the provided id is too late/old to be requested.
func (h *Hare) outOfBufferRange(id types.LayerID) bool {
last := h.getLastLayer()
if !last.After(types.LayerID(h.config.Hdist)) {
return false
}
if id.Before(last.Sub(h.config.Hdist)) { // bufferSize>=0
return true
}
return false
}
func (h *Hare) oldestResultInBuffer() types.LayerID {
h.mu.Lock()
defer h.mu.Unlock()
return h.oldestResultInBufferLocked()
}
func (h *Hare) oldestResultInBufferLocked() types.LayerID {
// buffer is usually quite small so its cheap to iterate.
// TODO: if it gets bigger change `outputs` to array.
lyr := types.LayerID(math.MaxUint32)
for k := range h.outputs {
if k.Before(lyr) {
lyr = k
}
}
return lyr
}
// ErrTooLate means that the consensus was terminated too late.
var ErrTooLate = errors.New("consensus process finished too late")
// records the provided output.
func (h *Hare) collectOutput(ctx context.Context, output TerminationOutput) error {
layerID := output.ID()
var pids []types.ProposalID
if output.Completed() {
consensusOkCnt.Inc()
h.WithContext(ctx).With().Info("hare terminated with success", layerID, log.Int("num_proposals", output.Set().Size()))
set := output.Set()
postNumProposals.Add(float64(set.Size()))
pids = set.ToSlice()
select {
case h.blockGenCh <- LayerOutput{
Ctx: ctx,
Layer: layerID,
Proposals: pids,
}:
case <-ctx.Done():
}
} else {
consensusFailCnt.Inc()
h.WithContext(ctx).With().Warning("hare terminated with failure", layerID)
}
if h.outOfBufferRange(layerID) {
return ErrTooLate
}
h.mu.Lock()
defer h.mu.Unlock()
if uint32(len(h.outputs)) >= h.config.Hdist {
delete(h.outputs, h.oldestResultInBufferLocked())
}
h.outputs[layerID] = pids
return nil
}
func (h *Hare) isClosed() bool {
select {
case <-h.ctx.Done():
return true
default:
return false
}
}
// the logic that happens when a new layer arrives.
// this function triggers the start of new consensus processes.
func (h *Hare) onTick(ctx context.Context, lid types.LayerID) (bool, error) {
logger := h.WithContext(ctx).WithFields(lid)
if h.isClosed() {
logger.Info("hare exiting")
return false, nil
}
h.setLastLayer(lid)
if lid.GetEpoch().IsGenesis() {
logger.Info("not starting hare: genesis")
return false, nil
}
// call to start the calculation of active set size beforehand
h.eg.Go(func() error {
// this is called only for its side effects, but at least print the error if it returns one
if isActive, err := h.rolacle.IsIdentityActiveOnConsensusView(ctx, h.nodeID, lid); err != nil {
logger.With().Error("error checking if identity is active",
log.Bool("isActive", isActive), log.Err(err))
}
return nil
})
logger.With().Debug("hare got tick, sleeping", log.String("delta", fmt.Sprint(h.networkDelta)))
clock := h.newRoundClock(lid)
select {
case <-clock.AwaitWakeup():
break // keep going
case <-h.ctx.Done():
return false, errors.New("closed while waiting for hare delta")
}
if !h.broker.Synced(ctx, lid) {
// if not currently synced don't start consensus process
logger.Info("not starting hare: node not synced at this layer")
return false, nil
}
var err error
beacon, err := h.beacons.GetBeacon(lid.GetEpoch())
if err != nil {
logger.Info("not starting hare: beacon not retrieved")
return false, nil
}
var nonce *types.VRFPostIndex
nnc, err := h.msh.VRFNonce(h.nodeID, h.lastLayer.GetEpoch())
if err != nil && !errors.Is(err, sql.ErrNotFound) {
logger.With().Error("failed to get vrf nonce", log.Err(err))
return false, fmt.Errorf("vrf nonce: %w", err)
} else if err == nil {
nonce = &nnc
}
ch, err := h.broker.Register(ctx, lid)
if err != nil {
logger.With().Error("failed to register with broker", log.Err(err))
return false, fmt.Errorf("broker register: %w", err)
}
comm := communication{
inbox: ch,
mchOut: h.mchMalfeasance,
report: h.outputChan,
}
props := goodProposals(logger, h.msh, h.nodeID, lid, beacon)
preNumProposals.Add(float64(len(props)))
set := NewSet(props)
cp := h.factory(ctx, h.config, lid, set, h.rolacle, h.sign, nonce, h.publisher, comm, clock)
logger.With().Info("starting hare", log.Int("num_proposals", len(props)))
cp.Start()
h.addCP(logger, cp)
h.patrol.SetHareInCharge(lid)
return true, nil
}
func (h *Hare) addCP(logger log.Log, cp Consensus) {
h.mu.Lock()
defer h.mu.Unlock()
h.cps[cp.ID()] = cp
logger.With().Info("number of consensus processes (after register)",
log.Int("count", len(h.cps)))
}
func (h *Hare) getCP(lid types.LayerID) Consensus {
h.mu.Lock()
defer h.mu.Unlock()
return h.cps[lid]
}
func (h *Hare) removeCP(logger log.Log, lid types.LayerID) {
cp := h.getCP(lid)
if cp == nil {
logger.With().Error("failed to find consensus process", lid)
return
}
// do not hold lock while waiting for consensus process to terminate
cp.Stop()
h.mu.Lock()
defer h.mu.Unlock()
delete(h.cps, cp.ID())
logger.With().Info("number of consensus processes (after deregister)",
log.Int("count", len(h.cps)))
}
// goodProposals finds the "good proposals" for the specified layer. a proposal is good if
// it has the same beacon value as the node's beacon value.
// any error encountered will be ignored and an empty set is returned.
func goodProposals(logger log.Log, msh mesh, nodeID types.NodeID, lid types.LayerID, epochBeacon types.Beacon) []types.ProposalID {
props, err := msh.Proposals(lid)
if err != nil {
if errors.Is(err, sql.ErrNotFound) {
logger.With().Warning("no proposals found for hare, using empty set", log.Err(err))
} else {
logger.With().Error("failed to get proposals for hare", log.Err(err))
}
return []types.ProposalID{}
}
var (
beacon types.Beacon
result []types.ProposalID
ownHdr *types.ActivationTxHeader
ownTickHeight = uint64(math.MaxUint64)
)
// a non-smesher will not filter out any proposals, as it doesn't have voting power
// and only observes the consensus process.
ownHdr, err = msh.GetEpochAtx(lid.GetEpoch(), nodeID)
if err != nil && !errors.Is(err, sql.ErrNotFound) {
logger.With().Error("failed to get own atx", log.Err(err))
return []types.ProposalID{}
}
if ownHdr != nil {
ownTickHeight = ownHdr.TickHeight()
}
for _, p := range props {
if ownHdr != nil {
hdr, err := msh.GetAtxHeader(p.AtxID)
if err != nil {
logger.With().Error("failed to get atx", p.AtxID, log.Err(err))
return []types.ProposalID{}
}
if hdr.BaseTickHeight >= ownTickHeight {
// does not vote for future proposal
logger.With().Warning("proposal base tick height too high. skipping",
log.Uint64("proposal_height", hdr.BaseTickHeight),
log.Uint64("own_height", ownTickHeight),
)
continue
}
}
if p.EpochData != nil {
beacon = p.EpochData.Beacon
} else if p.RefBallot == types.EmptyBallotID {
logger.With().Error("proposal missing ref ballot", p.ID())
return []types.ProposalID{}
} else if refBallot, err := msh.Ballot(p.RefBallot); err != nil {
logger.With().Error("failed to get ref ballot", p.ID(), p.RefBallot, log.Err(err))
return []types.ProposalID{}
} else if refBallot.EpochData == nil {
logger.With().Error("ref ballot missing epoch data", refBallot.ID())
return []types.ProposalID{}
} else {
beacon = refBallot.EpochData.Beacon
}
if beacon == epochBeacon {
result = append(result, p.ID())
} else {
logger.With().Warning("proposal has different beacon value",
p.ID(),
log.String("proposal_beacon", beacon.ShortString()),
log.String("epoch_beacon", epochBeacon.ShortString()))
}
}
return result
}
var (
errTooOld = errors.New("layer has already been evacuated from buffer")
errNoResult = errors.New("no result for the requested layer")
)
func (h *Hare) getResult(lid types.LayerID) ([]types.ProposalID, error) {
if h.outOfBufferRange(lid) {
return nil, errTooOld
}
h.mu.Lock()
defer h.mu.Unlock()
props, ok := h.outputs[lid]
if !ok {
return nil, errNoResult
}
return props, nil
}
// listens to outputs arriving from consensus processes.
func (h *Hare) outputCollectionLoop(ctx context.Context) {
h.WithContext(ctx).With().Info("starting collection loop")
for {
select {
case out := <-h.outputChan:
layerID := out.ID()
coin := out.Coinflip()
ctx := log.WithNewSessionID(ctx)
logger := h.WithContext(ctx).WithFields(layerID)
// collect coinflip, regardless of success
logger.With().Debug("recording weak coin result for layer",
log.Bool("weak_coin", coin))
if err := h.msh.SetWeakCoin(layerID, coin); err != nil {
logger.With().Error("failed to set weak coin for layer", log.Err(err))
}
if err := h.collectOutput(ctx, out); err != nil {
logger.With().Warning("error collecting output from hare", log.Err(err))
}
h.broker.Unregister(ctx, out.ID())
h.removeCP(logger, out.ID())
case <-h.ctx.Done():
return
}
}
}
// listens to new layers.
func (h *Hare) tickLoop(ctx context.Context) {
for layer := h.layerClock.CurrentLayer(); ; layer = layer.Add(1) {
ctx := log.WithNewSessionID(ctx)
select {
case <-h.layerClock.AwaitLayer(layer):
if time.Since(h.layerClock.LayerToTime(layer)) > h.config.WakeupDelta {
h.WithContext(ctx).With().Warning("missed hare window, skipping layer", layer)
continue
}
_, _ = h.onTick(ctx, layer)
case <-h.ctx.Done():
return
}
}
}
// process two types of messages:
// - HareEligibilityGossip received from MalfeasanceProof gossip handler:
// relay to the running consensus instance if running.
// - MalfeasanceProofGossip generated during the consensus processes:
// save it to database and broadcast to network.
func (h *Hare) malfeasanceLoop(ctx context.Context) {
h.WithContext(ctx).With().Info("starting malfeasance loop")
for {
select {
case gossip := <-h.mchMalfeasance:
if gossip.Eligibility == nil {
h.WithContext(ctx).Fatal("missing hare eligibility")
}
logger := h.WithContext(ctx).WithFields(gossip.Eligibility.NodeID)
if malicious, err := h.msh.IsMalicious(gossip.Eligibility.NodeID); err != nil {
logger.With().Error("failed to check identity", log.Err(err))
continue
} else if malicious {
logger.Debug("known malicious identity")
continue
}
if err := h.msh.AddMalfeasanceProof(gossip.Eligibility.NodeID, &gossip.MalfeasanceProof, nil); err != nil {
logger.With().Error("failed to save MalfeasanceProof", log.Err(err))
continue
}
gossipBytes, err := codec.Encode(gossip)
if err != nil {
logger.With().Fatal("failed to encode MalfeasanceGossip", log.Err(err))
}
if err = h.publisher.Publish(ctx, pubsub.MalfeasanceProof, gossipBytes); err != nil {
logger.With().Error("failed to broadcast MalfeasanceProof")
}
case <-ctx.Done():
return
case <-h.ctx.Done():
return
}
}
}
// Start starts listening for layers and outputs.
func (h *Hare) Start(ctx context.Context) error {
{
h.mu.Lock()
defer h.mu.Unlock()
if h.cancel != nil {
h.cancel()
}
h.ctx, h.cancel = context.WithCancel(ctx)
ctx = h.ctx
}
h.WithContext(ctx).With().Info("starting protocol", log.String("protocol", pubsub.HareProtocol))
// Create separate contexts for each subprocess. This allows us to better track the flow of messages.
ctxBroker := log.WithNewSessionID(ctx, log.String("protocol", pubsub.HareProtocol+"_broker"))
ctxTickLoop := log.WithNewSessionID(ctx, log.String("protocol", pubsub.HareProtocol+"_tickloop"))
ctxOutputLoop := log.WithNewSessionID(ctx, log.String("protocol", pubsub.HareProtocol+"_outputloop"))
ctxMalfLoop := log.WithNewSessionID(ctx, log.String("protocol", pubsub.HareProtocol+"_malfloop"))
h.broker.Start(ctxBroker)
h.eg.Go(func() error {
h.tickLoop(ctxTickLoop)
return nil
})
h.eg.Go(func() error {
h.outputCollectionLoop(ctxOutputLoop)
return nil
})
h.eg.Go(func() error {
h.malfeasanceLoop(ctxMalfLoop)
return nil
})
return nil
}
// Close sends a termination signal to hare goroutines and waits for their termination.
func (h *Hare) Close() {
h.cancel()
_ = h.eg.Wait()
}
func reportEquivocation(
ctx context.Context,
pubKey types.NodeID,
old, new *types.HareProofMsg,
eligibility *types.HareEligibility,
mch chan<- *types.MalfeasanceGossip,
) error {
gossip := &types.MalfeasanceGossip{
MalfeasanceProof: types.MalfeasanceProof{
Layer: old.InnerMsg.Layer,
Proof: types.Proof{
Type: types.HareEquivocation,
Data: &types.HareProof{
Messages: [2]types.HareProofMsg{*old, *new},
},
},
},
Eligibility: &types.HareEligibilityGossip{
Layer: old.InnerMsg.Layer,
Round: old.InnerMsg.Round,
NodeID: pubKey,
Eligibility: *eligibility,
},
}
select {
case <-ctx.Done():
return ctx.Err()
case mch <- gossip:
}
return nil
}