-
Notifications
You must be signed in to change notification settings - Fork 10
/
pacemaker.go
1322 lines (1155 loc) · 42.7 KB
/
pacemaker.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
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Copyright (c) 2020 The Meter.io developers
// Distributed under the GNU Lesser General Public License v3.0 software license, see the accompanying
// file LICENSE or <https://www.gnu.org/licenses/lgpl-3.0.html>
package consensus
import (
"errors"
"fmt"
"os"
"time"
"github.com/ethereum/go-ethereum/rlp"
"github.com/inconshreveable/log15"
"github.com/meterio/meter-pov/block"
"github.com/meterio/meter-pov/chain"
)
const (
RoundInterval = 2 * time.Second
RoundTimeoutInterval = 20 * time.Second // move the timeout from 30 to 20 secs.
MIN_MBLOCKS_AN_EPOCH = uint32(4)
CATCH_UP_THRESHOLD = 5
)
type PMMode uint32
const (
PMModeNormal PMMode = 1
PMModeCatchUp = 2
PMModeObserve = 3
)
func (m PMMode) String() string {
switch m {
case PMModeNormal:
return "Normal"
case PMModeCatchUp:
return "CatchUp"
case PMModeObserve:
return "Observe"
}
return ""
}
type Pacemaker struct {
csReactor *ConsensusReactor //global reactor info
proposalMap *ProposalMap
logger log15.Logger
// Current round (current_round - highest_qc_round determines the timeout).
// Current round is basically max(highest_qc_round, highest_received_tc, highest_local_tc) + 1
// update_current_round take care of updating current_round and sending new round event if
// it changes
currentRound uint32
stopped bool
mainLoopStarted bool
myActualCommitteeIndex int //record my index in actualcommittee
minMBlocks uint32
startHeight uint32
startRound uint32
// Utility data structures
newCommittee bool //pacemaker in replay mode?
mode PMMode
msgCache *MsgCache
sigAggregator *SignatureAggregator
pendingList *PendingList
// HotStuff fields
lastVotingHeight uint32
QCHigh *pmQuorumCert
blockLeaf *pmBlock
blockExecuted *pmBlock
blockLocked *pmBlock
// Channels
pacemakerMsgCh chan consensusMsgInfo
roundTimeoutCh chan PMRoundTimeoutInfo
cmdCh chan *PMCmdInfo
beatCh chan *PMBeatInfo
// Timeout
roundTimer *time.Timer
timeoutCertManager *PMTimeoutCertManager
timeoutCert *PMTimeoutCert
timeoutCounter uint64
}
func NewPaceMaker(conR *ConsensusReactor) *Pacemaker {
p := &Pacemaker{
csReactor: conR,
logger: log15.New("pkg", "pacemaker"),
mode: PMModeNormal,
msgCache: NewMsgCache(2048),
pacemakerMsgCh: make(chan consensusMsgInfo, 128),
cmdCh: make(chan *PMCmdInfo, 2),
beatCh: make(chan *PMBeatInfo, 2),
roundTimeoutCh: make(chan PMRoundTimeoutInfo, 2),
roundTimer: nil,
proposalMap: NewProposalMap(),
pendingList: NewPendingList(),
timeoutCounter: 0,
stopped: true,
}
p.timeoutCertManager = newPMTimeoutCertManager(p)
// p.stopCleanup()
return p
}
type BlockProbe struct {
Height uint32
Round uint32
Type uint32
Raw []byte
}
type PMProbeResult struct {
Mode string
StartHeight uint32
StartRound uint32
CurRound uint32
MyCommitteeIndex int
LastVotingHeight uint32
QCHigh *block.QuorumCert
BlockLeaf *BlockProbe
BlockExecuted *BlockProbe
BlockLocked *BlockProbe
ProposalCount int
PendingCount int
PendingLowest uint32
}
func (p *Pacemaker) Probe() *PMProbeResult {
result := &PMProbeResult{
Mode: p.mode.String(),
StartHeight: p.startHeight,
StartRound: p.startRound,
CurRound: p.currentRound,
MyCommitteeIndex: p.myActualCommitteeIndex,
LastVotingHeight: p.lastVotingHeight,
QCHigh: p.QCHigh.QC,
}
if p.QCHigh != nil && p.QCHigh.QC != nil {
result.QCHigh = p.QCHigh.QC
}
if p.blockLeaf != nil {
result.BlockLeaf = &BlockProbe{Height: p.blockLeaf.Height, Round: p.blockLeaf.Round, Type: uint32(p.blockLeaf.ProposedBlockType), Raw: p.blockLeaf.ProposedBlock}
}
if p.blockExecuted != nil {
result.BlockExecuted = &BlockProbe{Height: p.blockExecuted.Height, Round: p.blockExecuted.Round, Type: uint32(p.blockExecuted.ProposedBlockType), Raw: p.blockExecuted.ProposedBlock}
}
if p.blockLocked != nil {
result.BlockLocked = &BlockProbe{Height: p.blockLocked.Height, Round: p.blockLocked.Round, Type: uint32(p.blockLocked.ProposedBlockType), Raw: p.blockLocked.ProposedBlock}
}
if p.proposalMap != nil {
result.ProposalCount = p.proposalMap.Len()
}
if p.pendingList != nil {
result.PendingCount = p.pendingList.Len()
result.PendingLowest = p.pendingList.GetLowestHeight()
}
return result
}
func (p *Pacemaker) CreateLeaf(parent *pmBlock, qc *pmQuorumCert, height, round uint32) *pmBlock {
parentBlock, err := block.BlockDecodeFromBytes(parent.ProposedBlock)
if err != nil {
panic("Error decode the parent block")
}
p.logger.Info(fmt.Sprintf("CreateLeaf: height=%v, round=%v, QC(Height:%v,Round:%v), Parent(Height:%v,Round:%v)", height, round, qc.QC.QCHeight, qc.QC.QCRound, parent.Height, parent.Round))
// after kblock is proposed, we should propose 2 rounds of stopcommitteetype block
// to finish the pipeline. This mechnism guranttee kblock get into block server.
// resend the previous kblock as special type to get vote stop message to get vote
// This proposal will not get into block database
if parent.ProposedBlockType == KBlockType || parent.ProposedBlockType == StopCommitteeType {
p.logger.Info(fmt.Sprintf("Proposed Stop pacemaker message: height=%v, round=%v", height, round))
info, blockBytes := p.proposeStopCommitteeBlock(parentBlock, height, round, qc)
b := &pmBlock{
Height: height,
Round: round,
Parent: parent,
Justify: qc,
ProposedBlockInfo: info,
SuccessProcessed: true,
ProposedBlock: blockBytes,
ProposedBlockType: info.BlockType,
}
fmt.Print(b.ToString())
return b
}
info, blockBytes := p.proposeBlock(parentBlock, height, round, qc, (p.timeoutCert != nil))
p.logger.Info(fmt.Sprintf("Proposed Block: %v", info.ProposedBlock.Oneliner()))
b := &pmBlock{
Height: height,
Round: round,
Parent: parent,
Justify: qc,
ProposedBlockInfo: info, //save to local
SuccessProcessed: true,
ProposedBlock: blockBytes,
ProposedBlockType: info.BlockType,
}
// fmt.Print(b.ToString())
return b
}
// b_exec b_lock b <- b' <- b" b*
func (p *Pacemaker) Update(bnew *pmBlock) error {
var block, blockPrime, blockPrimePrime *pmBlock
//now pipeline full, roll this pipeline first
blockPrimePrime = bnew.Justify.QCNode
if blockPrimePrime == nil {
p.logger.Warn("blockPrimePrime is empty, early termination of Update")
return nil
}
blockPrime = blockPrimePrime.Justify.QCNode
if blockPrime == nil {
p.logger.Warn("blockPrime is empty, early termination of Update")
return nil
}
block = blockPrime.Justify.QCNode
if block == nil {
//bnew Justify is already higher than current QCHigh
p.UpdateQCHigh(bnew.Justify)
p.logger.Warn("block is empty, early termination of Update")
return nil
}
p.logger.Debug(fmt.Sprintf("bnew = %v", bnew.ToString()))
p.logger.Debug(fmt.Sprintf("b\" = %v", blockPrimePrime.ToString()))
p.logger.Debug(fmt.Sprintf("b' = %v", blockPrime.ToString()))
p.logger.Debug(fmt.Sprintf("b = %v", block.ToString()))
// pre-commit phase on b"
p.UpdateQCHigh(bnew.Justify)
if blockPrime.Height > p.blockLocked.Height {
p.blockLocked = blockPrime // commit phase on b'
}
/* commit requires direct parent */
if (blockPrimePrime.Parent != blockPrime) ||
(blockPrime.Parent != block) {
return nil
}
commitReady := []*pmBlock{}
for b := block; b.Height > p.blockExecuted.Height; b = b.Parent {
// XXX: b must be prepended the slice, so we can commit blocks in order
commitReady = append([]*pmBlock{b}, commitReady...)
}
p.OnCommit(commitReady)
p.blockExecuted = block // decide phase on b
return nil
}
// TBD: how to emboy b.cmd
func (p *Pacemaker) Execute(b *pmBlock) {
// p.csReactor.logger.Info("Exec cmd:", "height", b.Height, "round", b.Round)
}
func (p *Pacemaker) OnCommit(commitReady []*pmBlock) {
for _, b := range commitReady {
p.csReactor.logger.Debug("OnCommit", "height", b.Height, "round", b.Round)
// TBD: how to handle this case???
if b.SuccessProcessed == false {
p.csReactor.logger.Error("Process this proposal failed, possible my states are wrong", "height", b.Height, "round", b.Round, "action", "commit", "err", b.ProcessError)
continue
}
// commit the approved block
bestQC := p.proposalMap.Get(b.Height + 1).Justify.QC
err := p.csReactor.FinalizeCommitBlock(b.ProposedBlockInfo, bestQC)
if err != nil && err != chain.ErrBlockExist {
p.csReactor.logger.Warn("Commit block failed ...", "error", err)
//revert to checkpoint
best := p.csReactor.chain.BestBlock()
state, err := p.csReactor.stateCreator.NewState(best.Header().StateRoot())
if err != nil {
panic(fmt.Sprintf("revert the state faild ... %v", err))
}
state.RevertTo(b.ProposedBlockInfo.CheckPoint)
}
p.Execute(b) //b.cmd
if b.ProposedBlockType == KBlockType {
p.csReactor.logger.Info("committed a kblock, stop pacemaker", "height", b.Height, "round", b.Round)
p.SendKblockInfo(b)
// p.Stop()
}
// BUG FIX: normally proposal message are cleaned once it is committed. It is ok because this proposal
// is not needed any more. Only in one case, if somebody queries the more old message, we can not give.
// so proposals are kept in this committee and clean all of them at the stopping of pacemaker.
// remove this pmBlock from map.
//delete(p.proposalMap, b.Height)
}
}
func (p *Pacemaker) OnPreCommitBlock(b *pmBlock) error {
// This is the situation: 2/3 of committee agree the proposal while I disagree.
// posslible my state is deviated from the majority of committee, resatart pacemaker.
if b.SuccessProcessed == false {
p.csReactor.logger.Error("Process this proposal failed, possible my states are wrong, restart pacemaker", "height", b.Height, "round", b.Round, "action", "precommit", "err", b.ProcessError)
return errRestartPaceMakerRequired
}
err := p.csReactor.PreCommitBlock(b.ProposedBlockInfo)
if err != nil && err != chain.ErrBlockExist {
p.logger.Warn("precommit failed", "err", err)
return err
}
// p.csReactor.logger.Info("PreCommitted block", "height", b.Height, "round", b.Round)
return nil
}
func (p *Pacemaker) OnReceiveProposal(mi *consensusMsgInfo) error {
proposalMsg, _ := mi.Msg.(*PMProposalMessage), mi.Peer
msgHeader := proposalMsg.CSMsgCommonHeader
height := msgHeader.Height
round := msgHeader.Round
if height <= p.blockLocked.Height {
p.logger.Info("recved proposal with height <= bLocked.height, ignore ...", "height", height, "bLocked.height", p.blockLocked.Height)
return nil
}
// decode block to get qc
blk, err := block.BlockDecodeFromBytes(proposalMsg.ProposedBlock)
if err != nil {
return errors.New("can not decode proposed block")
}
// skip invalid proposal
if blk.Number() != uint32(height) {
p.logger.Error("invalid proposal: height mismatch", "proposalHeight", height, "proposedBlockHeight", blk.Number())
return errors.New("invalid proposal: height mismatch")
}
qc := blk.QC
p.logger.Debug("start to handle received block proposal ", "block", blk.Oneliner())
// address parent
parent := p.AddressBlock(proposalMsg.ParentHeight)
if parent == nil {
// put this proposal to pending list, and sent out query
if err := p.pendingProposal(proposalMsg.ParentHeight, proposalMsg.ParentRound, proposalMsg.CSMsgCommonHeader.EpochID, mi); err != nil {
p.logger.Error("handle pending proposal failed", "error", err)
}
return errParentMissing
}
// address qcNode
// TODO: qc should be verified before it is used
qcNode := p.AddressBlock(qc.QCHeight)
if qcNode == nil {
p.logger.Warn("OnReceiveProposal: can not address qcNode")
// put this proposal to pending list, and sent out query
if err := p.pendingProposal(qc.QCHeight, qc.QCRound, proposalMsg.CSMsgCommonHeader.EpochID, mi); err != nil {
p.logger.Error("handle pending proposal failed", "error", err)
}
return errQCNodeMissing
}
// we have qcNode, need to check qcNode and blk.QC is referenced the same
if match, err := p.BlockMatchQC(qcNode, qc); match == true && err == nil {
p.logger.Debug("addressed qcNode ...", "qcHeight", qc.QCHeight, "qcRound", qc.QCRound)
} else {
// possible fork !!! TODO: handle?
p.logger.Error("qcNode doesn't match qc from proposal, potential fork happens...", "qcHeight", qc.QCHeight, "qcRound", qc.QCRound)
// TBD: How to handle this??
// if this block does not have Qc yet, revertTo previous
// if this block has QC, The real one need to be replaced
// anyway, get the new one.
// put this proposal to pending list, and sent out query
if err := p.pendingProposal(qc.QCHeight, qc.QCRound, proposalMsg.CSMsgCommonHeader.EpochID, mi); err != nil {
p.logger.Error("handle pending proposal failed", "error", err)
}
return errors.New("qcNode doesn't match qc from proposal, potential fork ")
}
// create justify node
justify := newPMQuorumCert(qc, qcNode)
// revert the proposals if I'm not the round proposer and I received a proposal with a valid TC
validTimeout := p.verifyTimeoutCert(proposalMsg.TimeoutCert, height, round)
if validTimeout {
p.revertTo(height)
}
// update the proposalMap if current proposal was not tracked before
if p.proposalMap.Get(height) == nil {
p.proposalMap.Add(&pmBlock{
ProposalMessage: proposalMsg,
Height: height,
Round: round,
Parent: parent,
Justify: justify,
ProposedBlock: proposalMsg.ProposedBlock,
ProposedBlockType: proposalMsg.ProposedBlockType,
})
}
bnew := p.proposalMap.Get(height)
if ((bnew.Height > p.lastVotingHeight) &&
(p.IsExtendedFromBLocked(bnew) || bnew.Justify.QC.QCHeight > p.blockLocked.Height)) || validTimeout {
if validTimeout {
p.updateCurrentRound(bnew.Round, UpdateOnTimeoutCertProposal)
} else {
p.updateCurrentRound(bnew.Round, UpdateOnRegularProposal)
}
// parent got QC, pre-commit
justify := p.proposalMap.Get(bnew.Justify.QC.QCHeight) //Justify.QCNode
if (justify != nil) && (justify.Height > p.blockLocked.Height) {
err := p.OnPreCommitBlock(justify)
if err != nil {
return err
}
}
if err := p.ValidateProposal(bnew); err != nil {
p.logger.Error("HELP: Validate Proposal failed", "error", err)
return err
}
if p.mode == PMModeCatchUp && p.proposalMap.Len() > CATCH_UP_THRESHOLD-1 {
p.logger.Info("I'm ready to vote, switch back to normal mode")
p.mode = PMModeNormal
}
// vote back only if not in catch-up mode
if p.mode != PMModeCatchUp {
msg, err := p.BuildVoteForProposalMessage(proposalMsg, blk.ID(), blk.Header().TxsRoot(), blk.Header().StateRoot())
if err != nil {
return err
}
// send vote message to leader
p.SendConsensusMessage(proposalMsg.CSMsgCommonHeader.Round, msg, false)
p.lastVotingHeight = bnew.Height
} else {
p.logger.Info("No voting due to catch-up mode")
}
}
return p.Update(bnew)
}
func (p *Pacemaker) OnReceiveVote(mi *consensusMsgInfo) error {
if p.mode == PMModeCatchUp {
p.logger.Info("ignored vote due to catch-up mode")
return nil
}
voteMsg := mi.Msg.(*PMVoteMessage)
msgHeader := voteMsg.CSMsgCommonHeader
height := msgHeader.Height
round := msgHeader.Round
if round < p.currentRound {
p.logger.Info("expired voteForProposal message, dropped ...", "currentRound", p.currentRound, "voteRound", round)
}
b := p.AddressBlock(height)
if b == nil {
return errors.New("can not address block")
}
err := p.collectVoteSignature(voteMsg)
if err != nil {
return err
}
voteCount := p.sigAggregator.Count()
if MajorityTwoThird(voteCount, p.csReactor.committeeSize) == false {
// if voteCount < p.csReactor.committeeSize {
// not reach 2/3
p.csReactor.logger.Debug("not reach majority", "committeeSize", p.csReactor.committeeSize, "count", voteCount)
return nil
} else {
p.csReactor.logger.Info("*** Reached majority, new QC formed", "committeeSize", p.csReactor.committeeSize, "count", voteCount)
}
// seal the signature, avoid re-trigger
p.sigAggregator.Seal()
//reach 2/3 majority, trigger the pipeline cmd
qc, err := p.generateNewQCNode(b)
if err != nil {
return err
}
changed := p.UpdateQCHigh(qc)
if changed == true {
// if QC is updated, relay it to the next proposer
p.OnNextSyncView(qc.QC.QCHeight+1, qc.QC.QCRound+1, HigherQCSeen, nil)
}
return nil
}
func (p *Pacemaker) OnPropose(b *pmBlock, qc *pmQuorumCert, height, round uint32) (*pmBlock, error) {
// clean signature cache
// p.voterBitArray = cmn.NewBitArray(p.csReactor.committeeSize)
// p.voteSigs = make([]*PMSignature, 0)
bnew := p.CreateLeaf(b, qc, height, round)
proposedBlk := bnew.ProposedBlockInfo.ProposedBlock
proposedQC := bnew.ProposedBlockInfo.ProposedBlock.QC
if bnew.Height != height || height != proposedBlk.Number() {
p.logger.Error("proposed height mismatch", "expectedHeight", height, "proposedHeight", bnew.Height, "proposedBlockHeight", proposedBlk.Number())
return nil, errors.New("proposed height mismatch")
}
if bnew.Height <= proposedQC.QCHeight || proposedBlk.Number() <= proposedQC.QCHeight {
p.logger.Error("proposed block refers to an invalid qc", "qcHeight", proposedQC.QCHeight, "proposedHeight", bnew.Height, "proposedBlockHeight", proposedBlk.Number(), "expectedHeight", height)
return nil, errors.New("proposed block referes to an invalid qc")
}
msg, err := p.BuildProposalMessage(height, round, bnew, p.timeoutCert)
if err != nil {
p.logger.Error("could not build proposal message", "err", err)
return nil, err
}
p.timeoutCert = nil
// pre-compute msgHash and store it in signature aggregator
info := bnew.ProposedBlockInfo
blk := info.ProposedBlock
id := blk.ID()
txsRoot := blk.Header().TxsRoot()
stateRoot := blk.Header().StateRoot()
signMsg := p.csReactor.BuildProposalBlockSignMsg(uint32(info.BlockType), uint64(blk.Number()), &id, &txsRoot, &stateRoot)
msgHash := p.csReactor.csCommon.Hash256Msg([]byte(signMsg))
p.sigAggregator = newSignatureAggregator(p.csReactor.committeeSize, *p.csReactor.csCommon.GetSystem(), msgHash, p.csReactor.curCommittee.Validators)
// create slot in proposalMap directly, instead of sendmsg to self.
bnew.ProposalMessage = msg
p.proposalMap.Add(bnew)
//send proposal to all include myself
p.SendConsensusMessage(round, msg, true)
return bnew, nil
}
func (p *Pacemaker) UpdateQCHigh(qc *pmQuorumCert) bool {
updated := false
oqc := p.QCHigh
if qc.QC.QCHeight > p.QCHigh.QC.QCHeight {
p.QCHigh = qc
p.blockLeaf = p.QCHigh.QCNode
updated = true
}
p.logger.Debug("After update QCHigh", "updated", updated, "from", oqc.ToString(), "to", p.QCHigh.ToString())
return updated
}
func (p *Pacemaker) OnBeat(height, round uint32, reason beatReason) error {
if reason == BeatOnTimeout && p.QCHigh != nil && p.QCHigh.QC != nil && height <= (p.QCHigh.QC.QCHeight+1) {
return p.OnTimeoutBeat(height, round, reason)
}
p.logger.Info(" --------------------------------------------------")
p.logger.Info(fmt.Sprintf(" OnBeat Round:%v, Height:%v, Reason:%v", round, height, reason.String()))
p.logger.Info(" --------------------------------------------------")
// parent already got QC, pre-commit it
//b := p.QCHigh.QCNode
b := p.proposalMap.Get(p.QCHigh.QC.QCHeight)
if b.Height > p.blockLocked.Height {
err := p.OnPreCommitBlock(b)
if err != nil {
p.logger.Error("precommit block failed", "height", b.Height, "error", err)
return err
}
}
if reason == BeatOnInit {
// only reset the round timer at initialization
p.resetRoundTimer(round, TimerInit)
}
p.updateCurrentRound(round, UpdateOnBeat)
if p.csReactor.amIRoundProproser(round) {
pmRoleGauge.Set(2)
p.csReactor.logger.Info("OnBeat: I am round proposer", "round", round)
bleaf, err := p.OnPropose(p.blockLeaf, p.QCHigh, height, round)
if err != nil {
return err
}
if bleaf == nil {
return errors.New("propose failed")
}
p.blockLeaf = bleaf
} else {
p.csReactor.logger.Info("OnBeat: I am NOT round proposer", "round", round)
}
return nil
}
func (p *Pacemaker) OnTimeoutBeat(height, round uint32, reason beatReason) error {
p.logger.Info(" --------------------------------------------------")
p.logger.Info(fmt.Sprintf(" OnTimeoutBeat Round:%v, Height:%v, Reason:%v", round, height, reason.String()))
p.logger.Info(" --------------------------------------------------")
// parent already got QC, pre-commit it
//b := p.QCHigh.QCNode
parent := p.proposalMap.Get(height - 1)
replaced := p.proposalMap.Get(height)
if parent == nil {
p.logger.Error("missing parent proposal", "parentHeight", height-1, "height", height, "round", round)
return errors.New("missing parent proposal")
}
var parentQC *pmQuorumCert
// in most of timeout case, proposal of height is alway there. only for the 1st round timeout, it is not there.
// in this case, p.QCHigh is for it.
if replaced == nil {
if p.QCHigh.QC.QCHeight == (height - 1) {
parentQC = p.QCHigh
} else {
p.logger.Error("missing qc for proposal", "parentHeight", height-1, "height", height, "round", round)
return errors.New("missing qc for proposal")
}
} else {
parentQC = replaced.Justify
}
if reason == BeatOnInit {
// only reset the round timer at initialization
p.resetRoundTimer(round, TimerInit)
}
if p.csReactor.amIRoundProproser(round) {
pmRoleGauge.Set(2)
p.csReactor.logger.Info("OnBeat: I am round proposer", "round", round)
bleaf, err := p.OnPropose(parent, parentQC, height, round)
if err != nil {
return err
}
if bleaf == nil {
return errors.New("propose failed")
}
} else {
pmRoleGauge.Set(1)
p.csReactor.logger.Info("OnBeat: I am NOT round proposer", "round", round)
}
return nil
}
func (p *Pacemaker) OnNextSyncView(nextHeight, nextRound uint32, reason NewViewReason, ti *PMRoundTimeoutInfo) {
// set role back to validator
pmRoleGauge.Set(1)
// send new round msg to next round proposer
msg, err := p.BuildNewViewMessage(nextHeight, nextRound, p.QCHigh, reason, ti)
if err != nil {
p.logger.Error("could not build new view message", "err", err)
} else {
p.SendConsensusMessage(nextRound, msg, false)
}
}
func (p *Pacemaker) OnReceiveNewView(mi *consensusMsgInfo) error {
if p.mode == PMModeCatchUp {
p.logger.Info("ignored newView due to catch-up mode")
return nil
}
newViewMsg, peer := mi.Msg.(*PMNewViewMessage), mi.Peer
header := newViewMsg.CSMsgCommonHeader
qc := block.QuorumCert{}
err := rlp.DecodeBytes(newViewMsg.QCHigh, &qc)
if err != nil {
p.logger.Error("can not decode qc from new view message", "err", err)
return nil
}
// drop newview if it is old
if qc.QCHeight < p.csReactor.curHeight {
p.logger.Error("old newview message, dropped ...", "QCheight", qc.QCHeight)
return nil
}
qcNode := p.AddressBlock(qc.QCHeight)
if qcNode == nil {
p.logger.Error("can not address qcNode", "height", qc.QCHeight, "round", qc.QCRound)
// put this newView to pending list, and sent out query
if err := p.pendingNewView(qc.QCHeight, qc.QCRound, newViewMsg.CSMsgCommonHeader.EpochID, mi); err != nil {
p.logger.Error("handle pending newViewMsg failed", "error", err)
}
return nil
}
// now have qcNode, check qcNode and blk.QC is referenced the same
if match, err := p.BlockMatchQC(qcNode, &qc); match == true && err == nil {
p.logger.Debug("addressed qcNode ...", "qcHeight", qc.QCHeight, "qcRound", qc.QCRound)
} else {
// possible fork !!! TODO: handle?
p.logger.Error("qcNode does not match qc from proposal, potential fork happens...", "qcHeight", qc.QCHeight, "qcRound", qc.QCRound)
// TBD: How to handle this case??
// if this block does not have Qc yet, revertTo previous
// if this block has QC, the real one need to be replaced
// anyway, get the new one.
// put this newView to pending list, and sent out query
if err := p.pendingNewView(qc.QCHeight, qc.QCRound, newViewMsg.CSMsgCommonHeader.EpochID, mi); err != nil {
p.logger.Error("handle pending newViewMsg failed", "error", err)
}
return nil
}
pmQC := newPMQuorumCert(&qc, qcNode)
switch newViewMsg.Reason {
case RoundTimeout:
height := header.Height
round := header.Round
epoch := header.EpochID
if !p.csReactor.amIRoundProproser(round) {
p.logger.Info("Not round proposer, drops the newView timeout ...", "Height", height, "Round", round, "Epoch", epoch)
return nil
}
qcHeight := qc.QCHeight
qcRound := qc.QCRound
qcEpoch := qc.EpochID
// if I don't have the proposal at specified height, query my peer
if p.proposalMap.Get(qcHeight) == nil {
p.logger.Info("Send PMQueryProposal", "height", qcHeight, "round", qcRound, "epoch", qcEpoch)
fromHeight := p.lastVotingHeight
bestQC := p.csReactor.chain.BestQC()
if fromHeight < bestQC.QCHeight {
fromHeight = bestQC.QCHeight
}
if err := p.sendQueryProposalMsg(fromHeight, qcHeight, qcRound, qcEpoch, peer); err != nil {
p.logger.Warn("send PMQueryProposal message failed", "err", err)
}
}
// if peer's height is lower than me, forward all available proposals to fill the gap
if qcHeight < p.lastVotingHeight && peer.netAddr.IP.String() != p.csReactor.GetMyNetAddr().IP.String() {
// forward missing proposals to peers who just sent new view message with lower expected height
tmpHeight := qcHeight + 1
var proposal *pmBlock
missed := make([]*pmBlock, 0)
for {
proposal = p.proposalMap.Get(tmpHeight)
if proposal == nil {
break
}
tmpHeight++
missed = append(missed, proposal)
}
if len(missed) > 0 {
p.logger.Info(fmt.Sprintf("peer missed %v proposal, forward to it ... ", len(missed)), "fromHeight", qcHeight+1, "name", peer.name, "ip", peer.netAddr.IP.String())
for _, pmp := range missed {
p.logger.Debug("forwarding proposal", "height", pmp.Height, "name", peer.name, "ip", peer.netAddr.IP.String())
p.asyncSendPacemakerMsg(pmp.ProposalMessage, false, peer)
}
}
}
// now count the timeout
p.timeoutCertManager.collectSignature(newViewMsg)
timeoutCount := p.timeoutCertManager.count(newViewMsg.TimeoutHeight, newViewMsg.TimeoutRound)
if MajorityTwoThird(uint32(timeoutCount), p.csReactor.committeeSize) == false {
p.logger.Info("not reach majority on timeout", "count", timeoutCount, "timeoutHeight", newViewMsg.TimeoutHeight, "timeoutRound", newViewMsg.TimeoutRound, "timeoutCounter", newViewMsg.TimeoutCounter)
} else {
p.logger.Info("*** Reached majority on timeout", "count", timeoutCount, "timeoutHeight", newViewMsg.TimeoutHeight, "timeoutRound", newViewMsg.TimeoutRound, "timeoutCounter", newViewMsg.TimeoutCounter)
p.timeoutCert = p.timeoutCertManager.getTimeoutCert(newViewMsg.TimeoutHeight, newViewMsg.TimeoutRound)
p.timeoutCertManager.cleanup(newViewMsg.TimeoutHeight, newViewMsg.TimeoutRound)
// Schedule OnBeat due to timeout
p.logger.Info("Received a newview with timeoutCert, scheduleOnBeat now", "height", header.Height, "round", header.Round)
// Now reach timeout consensus on height/round, check myself states
if (p.QCHigh.QC.QCHeight + 1) < header.Height {
p.logger.Info("Can not OnBeat due to states lagging", "my QCHeight", p.QCHigh.QC.QCHeight, "timeoutCert Height", header.Height)
return nil
}
// should not schedule if timeout is too old. <= p.blocked
if header.Height <= p.blockLocked.Height {
p.logger.Info("Can not OnBeat due to old timeout", "my QCHeight", p.QCHigh.QC.QCHeight, "timeoutCert Height", header.Height, "my blockLocked", p.blockLocked.Height)
return nil
}
p.ScheduleOnBeat(header.Height, header.Round, BeatOnTimeout, RoundInterval)
}
case HigherQCSeen:
if header.Round <= p.currentRound {
p.logger.Info("expired newview message, dropped ... ", "currentRound", p.currentRound, "newViewNxtRound", header.Round)
return nil
}
changed := p.UpdateQCHigh(pmQC)
if changed {
if qc.QCHeight >= p.blockLocked.Height {
// Schedule OnBeat due to New QC
p.logger.Info("Received a newview with higher QC, scheduleOnBeat now", "qcHeight", qc.QCHeight, "qcRound", qc.QCRound, "onBeatHeight", qc.QCHeight+1, "onBeatRound", qc.QCRound+1)
p.ScheduleOnBeat(p.QCHigh.QC.QCHeight+1, qc.QCRound+1, BeatOnHigherQC, RoundInterval)
}
}
}
return nil
}
//Committee Leader triggers
func (p *Pacemaker) Start(mode PMMode) {
p.mode = mode
p.reset()
p.csReactor.chain.UpdateBestQC(nil, chain.None)
p.csReactor.chain.UpdateLeafBlock()
bestQC := p.csReactor.chain.BestQC()
bestBlock := p.csReactor.chain.BestBlock()
freshCommittee := (bestBlock.Header().BlockType() == block.BLOCK_TYPE_K_BLOCK) || (bestBlock.Header().Number() == 0)
height := bestQC.QCHeight
round := uint32(0)
if freshCommittee == false {
round = bestQC.QCRound
}
p.logger.Info(fmt.Sprintf("*** Pacemaker start at height %v, round %v", height, round), "qc", bestQC.CompactString(), "freshCommittee", freshCommittee, "mode", mode.String())
p.startHeight = height
p.startRound = round
// Hack here. We do not know it is the first pacemaker from beginning
// But it is not harmful, the worst case only misses one opportunity to propose kblock.
if p.csReactor.config.InitCfgdDelegates == false {
p.minMBlocks = MIN_MBLOCKS_AN_EPOCH
} else {
p.minMBlocks = p.csReactor.config.EpochMBlockCount
p.csReactor.config.InitCfgdDelegates = false // clean off InitCfgdDelegates
}
qcNode := p.AddressBlock(height)
if qcNode == nil {
p.logger.Warn("Started with empty qcNode")
}
qcInit := newPMQuorumCert(bestQC, qcNode)
bInit := &pmBlock{
Height: height,
Round: round,
Parent: nil,
Justify: qcInit,
ProposedBlock: p.csReactor.LoadBlockBytes(uint32(height)),
}
// now assign b_lock b_exec, b_leaf qc_high
p.blockLocked = bInit
p.blockExecuted = bInit
p.blockLeaf = bInit
p.proposalMap.Add(bInit)
if qcInit.QCNode == nil {
qcInit.QCNode = bInit
}
p.QCHigh = qcInit
p.stopped = false
pmRunningGauge.Set(1)
if p.mainLoopStarted == false {
go p.mainLoop()
}
switch p.mode {
case PMModeNormal:
p.ScheduleOnBeat(height+1, round, BeatOnInit, 1*time.Second) //delay 1s
case PMModeCatchUp:
p.SendCatchUpQuery()
case PMModeObserve:
// do nothing
}
}
func (p *Pacemaker) SendCatchUpQuery() {
bestQC := p.csReactor.chain.BestQC()
curProposer := p.getProposerByRound(p.currentRound)
err := p.sendQueryProposalMsg(p.blockLocked.Height, 0, p.currentRound, bestQC.EpochID, curProposer)
if err != nil {
fmt.Println("could not send query proposal, error:", err)
}
leader := p.csReactor.curCommittee.Validators[0]
leaderPeer := newConsensusPeer(leader.Name, leader.NetAddr.IP, leader.NetAddr.Port, p.csReactor.magic)
err = p.sendQueryProposalMsg(p.blockLocked.Height, 0, p.currentRound, bestQC.EpochID, leaderPeer)
if err != nil {
fmt.Println("could not send query proposal, error:", err)
}
}
func (p *Pacemaker) ScheduleOnBeat(height, round uint32, reason beatReason, d time.Duration) bool {
// p.updateCurrentRound(round, IncRoundOnBeat)
time.AfterFunc(d, func() {
p.beatCh <- &PMBeatInfo{height, round, reason}
})
return true
}
func (p *Pacemaker) mainLoopStopMode() {
// if pacemaker is already started, back to work
if p.stopped == false {
return
}
// sleep 500 milli second to avoid CPU spike
time.Sleep(500 * time.Millisecond)
}
func (p *Pacemaker) mainLoop() {
interruptCh := make(chan os.Signal, 1)
p.mainLoopStarted = true
// signal.Notify(interruptCh, syscall.SIGINT, syscall.SIGTERM)
for {
var err error
if p.stopped {
p.logger.Debug("Pacemaker stopped.")
p.mainLoopStopMode()
continue
}
select {
case si := <-p.cmdCh:
p.logger.Warn("Scheduled cmd", "cmd", si.cmd.String())
switch si.cmd {
case PMCmdStop:
p.stopCleanup()
p.logger.Info("--- Pacemaker stopped successfully")
p.stopped = true
continue
case PMCmdRestart:
p.stopCleanup()
p.logger.Info("--- Pacemaker stopped successfully, restart now")
p.Start(si.mode)
}
case ti := <-p.roundTimeoutCh:
p.OnRoundTimeout(ti)
case b := <-p.beatCh:
err = p.OnBeat(b.height, b.round, b.reason)
case m := <-p.pacemakerMsgCh:
// if in observe mode, ignore any incoming message
if p.mode == PMModeObserve {
continue
}
if m.Msg.EpochID() != p.csReactor.curEpoch {
p.logger.Info("receives message w/ mismatched epoch ID", "epoch", m.Msg.EpochID(), "myEpoch", p.csReactor.curEpoch, "type", getConcreteName(m.Msg))
break
}
switch msg := m.Msg.(type) {
case *PMProposalMessage:
err = p.OnReceiveProposal(&m)
if err != nil {
// 2 errors indicate linking message to pending list for the first time, does not need to check pending
if err != errParentMissing && err != errQCNodeMissing && err != errRestartPaceMakerRequired {
err = p.checkPendingMessages(msg.CSMsgCommonHeader.Height)
} else {
// qcHigh was supposed to be higher than bestQC at all times
// however sometimes, due to message transmission, proposals were lost, so the qcHigh is less than bestQC
// Usually, we'll use pending proposal to recover, but if the gap is too big between qcHigh and bestQC
// we'll have to restart the pacemaker in catch-up mode to "jump" the pacemaker ahead in order to
// process future proposals in time.
if (err == errRestartPaceMakerRequired) || (p.QCHigh != nil && p.QCHigh.QCNode != nil && p.QCHigh.QCNode.Height+CATCH_UP_THRESHOLD < p.csReactor.chain.BestQC().QCHeight) {
p.Restart(PMModeCatchUp)
}
}
} else {
err = p.checkPendingMessages(msg.CSMsgCommonHeader.Height)
}
case *PMVoteMessage:
err = p.OnReceiveVote(&m)
case *PMNewViewMessage:
err = p.OnReceiveNewView(&m)
case *PMQueryProposalMessage:
err = p.OnReceiveQueryProposal(&m)