-
Notifications
You must be signed in to change notification settings - Fork 0
/
viewchange_mgr.go
1992 lines (1785 loc) · 75.1 KB
/
viewchange_mgr.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 2016-2017 Hyperchain Corp.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package rbft
import (
"context"
"encoding/hex"
"sort"
"time"
"github.com/samber/lo"
"golang.org/x/crypto/sha3"
"github.com/axiomesh/axiom-bft/common"
"github.com/axiomesh/axiom-bft/common/consensus"
"github.com/axiomesh/axiom-bft/common/metrics"
"github.com/axiomesh/axiom-bft/types"
"github.com/axiomesh/axiom-kit/txpool"
)
var (
// initialNewView is the first new view cert in every epoch which indicates view = 0.
// However, the first new view cert is not generated by quorum view changes, so, for
// every new epoch, we need to initialize a cluster view change immediately after epoch
// change to advance view to 1 or higher, generate a valid and provable new view.
initialNewView = &consensus.NewView{}
)
// vcManager manages the whole process of view change
type vcManager struct {
viewChangePeriod uint64 // automatic vc period, default to 0 to disable automatic vc
viewChangeSeqNo uint64 // next seqNo to perform view change
lastNewViewTimeout time.Duration // last timeout we used during this view change
newViewTimerReason string // what triggered the timer
vcHandled bool // if we have finished process new view or not
qlist map[qidx]*consensus.VcPq // store Pre-Prepares for view change
plist map[uint64]*consensus.VcPq // store Prepares for view change
newViewStore map[uint64]*consensus.NewView // track last new-view we received or sent
newViewCache map[newViewIdx]*newViewCert // cache all correct new-view we received
viewChangeStore map[vcIdx]*consensus.ViewChange // track view-change messages
// track latest QuorumViewChange
latestQuorumViewChange *quorumViewChangeCache
// track latest NewView
latestNewView *consensus.NewView
// track higher view from other nodes, map node id to view.
higherViewRecord map[uint64]uint64
logger common.Logger
continuousNullRequestCounter uint64
lastNullRequestSeqNo uint64
}
// quorumViewChangeCache is the cache of a QuorumViewChange message.
type quorumViewChangeCache struct {
targetView uint64
*consensus.QuorumViewChange
}
// newViewIdx indicates a unique NewView message used to help single node recovery, which contains
// 1. target view to help lagging node recover to a correct view
// 2. new view hash to ensure a weak cert NewView
// 3. initial checkpoint height to help lagging node recover to a correct checkpoint height
type newViewIdx struct {
targetView uint64
newViewHash string
initialCheckpointState types.CheckpointState
}
// newViewCert is the certification for a new view.
type newViewCert struct {
forwardPeers []uint64
initialCheckpoints []*consensus.SignedCheckpoint
}
// dispatchViewChangeMsg dispatches view change consensus messages from
// other peers And push them into corresponding function
func (rbft *rbftImpl[T, Constraint]) dispatchViewChangeMsg(e consensusEvent) consensusEvent {
switch et := e.(type) {
case *consensus.ViewChange:
return rbft.recvViewChange(et, false)
case *consensus.NewView:
return rbft.recvNewView(et)
case *consensus.FetchBatchRequest:
return rbft.recvFetchRequestBatch(et)
case *consensus.FetchBatchResponse:
return rbft.recvFetchBatchResponse(et)
case *consensus.FetchView:
return rbft.recvFetchView(et)
case *consensus.RecoveryResponse:
return rbft.recvRecoveryResponse(et)
case *consensus.QuorumViewChange:
return rbft.recvQuorumViewChange(et)
}
return nil
}
// newVcManager init a instance of view change manager and initialize each parameter
// according to the configuration file.
func newVcManager(c Config) *vcManager {
vcm := &vcManager{
qlist: make(map[qidx]*consensus.VcPq),
plist: make(map[uint64]*consensus.VcPq),
newViewStore: make(map[uint64]*consensus.NewView),
newViewCache: make(map[newViewIdx]*newViewCert),
viewChangeStore: make(map[vcIdx]*consensus.ViewChange),
higherViewRecord: make(map[uint64]uint64),
logger: c.Logger,
}
vcm.lastNewViewTimeout = c.NewViewTimeout
return vcm
}
func (rbft *rbftImpl[T, Constraint]) punishAbnormalNodes(isTemp bool, isRecovery bool, view uint64, validatorDynamicInfoMap map[uint64]*ValidatorInfo) {
if view == 0 || view == rbft.chainConfig.LastStableView || view < rbft.chainConfig.View {
return
}
if !isTemp {
rbft.logger.Infof("Replica %d try punish abnormal nodes, LastStableView: %d, pre view: %d, now view: %d", rbft.chainConfig.SelfID, rbft.chainConfig.LastStableView, rbft.chainConfig.View, view)
}
punishAbnormalNode := func(v uint64) {
abnormalNodeID := rbft.chainConfig.calPrimaryIDByView(v, validatorDynamicInfoMap)
if validatorDynamicInfoMap[abnormalNodeID].ConsensusVotingPowerReduced && validatorDynamicInfoMap[abnormalNodeID].ConsensusVotingPowerReduceView == v {
// already reduce
return
}
if !isTemp {
rbft.logger.Warningf("Replica %d reduce the voting power of abnormal node %d, view %d", rbft.chainConfig.SelfID, abnormalNodeID, v)
}
validatorDynamicInfoMap[abnormalNodeID].ConsensusVotingPowerReduced = true
validatorDynamicInfoMap[abnormalNodeID].ConsensusVotingPowerReduceView = v
validatorDynamicInfoMap[abnormalNodeID].ConsensusVotingPower = rbft.chainConfig.EpochInfo.ConsensusParams.NotActiveWeight
}
// There may be multiple rounds of viewchange, so it is necessary to reduce the selected primary nodes in each round.
for v := rbft.chainConfig.LastStableView; v < view; v++ {
// if recover doesn't reduce the last view node
if v == view-1 && isRecovery {
continue
}
punishAbnormalNode(v)
}
}
func (rbft *rbftImpl[T, Constraint]) recoverAbnormalNodes(view uint64, validatorDynamicInfoMap map[uint64]*ValidatorInfo) {
if view == 0 || view < rbft.chainConfig.View {
return
}
// recover abnormal node voting power
for id, n := range validatorDynamicInfoMap {
if n.ConsensusVotingPowerReduced && view >= n.ConsensusVotingPowerReduceView+rbft.chainConfig.EpochInfo.ConsensusParams.AbnormalNodeExcludeView {
rbft.logger.Infof("Replica %d recover abnormal node %d voting power from %d to %d, reduce view: %d", rbft.chainConfig.SelfID, id, n.ConsensusVotingPower, rbft.chainConfig.ValidatorSet[id], n.ConsensusVotingPowerReduceView)
n.ConsensusVotingPower = rbft.chainConfig.ValidatorSet[id]
n.ConsensusVotingPowerReduced = false
n.ConsensusVotingPowerReduceView = 0
}
}
}
// setView sets the view with the viewLock.
func (rbft *rbftImpl[T, Constraint]) setView(view uint64) {
rbft.viewLock.Lock()
if !rbft.isTest {
unstableValidatorDynamicInfoMap := lo.MapEntries(rbft.chainConfig.LastStableValidatorDynamicInfoMap, func(k uint64, v *ValidatorInfo) (uint64, *ValidatorInfo) {
return k, &ValidatorInfo{
ID: v.ID,
ConsensusVotingPower: v.ConsensusVotingPower,
ConsensusVotingPowerReduced: v.ConsensusVotingPowerReduced,
ConsensusVotingPowerReduceView: v.ConsensusVotingPowerReduceView,
}
})
rbft.punishAbnormalNodes(false, false, view, unstableValidatorDynamicInfoMap)
rbft.recoverAbnormalNodes(view, unstableValidatorDynamicInfoMap)
rbft.chainConfig.ValidatorDynamicInfoMap = unstableValidatorDynamicInfoMap
}
rbft.chainConfig.View = view
rbft.chainConfig.updatePrimaryID()
rbft.viewLock.Unlock()
rbft.metrics.viewGauge.Set(float64(view))
}
func (rbft *rbftImpl[T, Constraint]) setViewWithRecovery(view uint64) {
rbft.viewLock.Lock()
if !rbft.isTest {
unstableValidatorDynamicInfoMap := lo.MapEntries(rbft.chainConfig.LastStableValidatorDynamicInfoMap, func(k uint64, v *ValidatorInfo) (uint64, *ValidatorInfo) {
return k, &ValidatorInfo{
ID: v.ID,
ConsensusVotingPower: v.ConsensusVotingPower,
ConsensusVotingPowerReduced: v.ConsensusVotingPowerReduced,
ConsensusVotingPowerReduceView: v.ConsensusVotingPowerReduceView,
}
})
rbft.punishAbnormalNodes(false, true, view, unstableValidatorDynamicInfoMap)
rbft.recoverAbnormalNodes(view, unstableValidatorDynamicInfoMap)
rbft.chainConfig.ValidatorDynamicInfoMap = unstableValidatorDynamicInfoMap
}
rbft.chainConfig.View = view
rbft.chainConfig.updatePrimaryID()
rbft.viewLock.Unlock()
rbft.metrics.viewGauge.Set(float64(view))
}
// getUnstableValidatorDynamicInfoMap returns the unstable validator dynamic info
// assumes that the abnormal node is restored after the view is stable
func (rbft *rbftImpl[T, Constraint]) getUnstableValidatorDynamicInfoMap(view uint64, isRecovery bool) []*consensus.NodeDynamicInfo {
unstableValidatorDynamicInfoMap := lo.MapEntries(rbft.chainConfig.LastStableValidatorDynamicInfoMap, func(k uint64, v *ValidatorInfo) (uint64, *ValidatorInfo) {
return k, &ValidatorInfo{
ID: v.ID,
ConsensusVotingPower: v.ConsensusVotingPower,
ConsensusVotingPowerReduced: v.ConsensusVotingPowerReduced,
ConsensusVotingPowerReduceView: v.ConsensusVotingPowerReduceView,
}
})
info := lo.MapToSlice(unstableValidatorDynamicInfoMap, func(id uint64, v *ValidatorInfo) ValidatorInfo {
return ValidatorInfo{
ID: v.ID,
ConsensusVotingPower: v.ConsensusVotingPower,
ConsensusVotingPowerReduced: v.ConsensusVotingPowerReduced,
ConsensusVotingPowerReduceView: v.ConsensusVotingPowerReduceView,
}
})
sort.Slice(info, func(i, j int) bool {
return info[i].ID < info[j].ID
})
rbft.punishAbnormalNodes(true, isRecovery, view, unstableValidatorDynamicInfoMap)
rbft.recoverAbnormalNodes(view, unstableValidatorDynamicInfoMap)
res := lo.MapToSlice(unstableValidatorDynamicInfoMap, func(id uint64, item *ValidatorInfo) *consensus.NodeDynamicInfo {
return &consensus.NodeDynamicInfo{
Id: item.ID,
ConsensusVotingPower: item.ConsensusVotingPower,
ConsensusVotingPowerReduced: item.ConsensusVotingPowerReduced,
ConsensusVotingPowerReduceView: item.ConsensusVotingPowerReduceView,
}
})
sort.Slice(res, func(i, j int) bool {
return res[i].Id < res[j].Id
})
return res
}
// setLastStableView after checkpoint or accept newView
func (rbft *rbftImpl[T, Constraint]) setLastStableView(view uint64) {
rbft.chainConfig.LastStableView = view
}
func (rbft *rbftImpl[T, Constraint]) checkView(msg *consensus.ConsensusMessage) {
if !rbft.chainConfig.CheckValidator(msg.From) {
return
}
// record higher view to actively fetch view periodically.
if msg.View > rbft.chainConfig.View {
rbft.vcMgr.higherViewRecord[msg.From] = msg.View
}
}
func (rbft *rbftImpl[T, Constraint]) initRecovery() consensusEvent {
return rbft.sendViewChange(true)
}
// sendViewChange broadcasts view change message to all other replicas to request
// all other replicas' current status, there will be two cases which need to trigger
// view change:
// 1. general view change: current node finds current primary behavior incorrectly.
// 2. recovery view change: current node finds itself primary behavior incorrectly, such as
// 2.1 restart node and trigger view change
// 2.2 epoch changed and trigger view change
// 2.3 view change resend timer out and trigger view change again
// 2.4 find self inconsistent with quorum nodes in sync state.
func (rbft *rbftImpl[T, Constraint]) sendViewChange(status ...bool) consensusEvent {
recovery := false
if len(status) != 0 {
recovery = status[0]
}
// reject view change when current node is in StateTransferring to avoid other (quorum-1) replicas
// finish view change but cannot reach consensus later if there are only quorum active replicas
// consisting of (quorum-1) normal replicas + 1 lagging replica.
if rbft.atomicIn(StateTransferring) {
rbft.logger.Warningf("Replica %d is in state transferring, not sending view change", rbft.chainConfig.SelfID)
return nil
}
// do some check and do some preparation
// such as stop nullRequest timer, clean vcMgr.viewChangeStore and so on.
err := rbft.beforeSendVC(recovery)
if err != nil {
return nil
}
if recovery {
rbft.atomicOn(InRecovery)
rbft.metrics.statusGaugeInRecovery.Set(InRecovery)
}
// create viewChange message
vcBasis := rbft.getVcBasis()
vc := &consensus.ViewChange{
Basis: vcBasis,
Recovery: recovery,
}
sig, sErr := rbft.signViewChange(vc)
if sErr != nil {
rbft.logger.Warningf("Replica %d sign view change failed: %s", rbft.chainConfig.SelfID, sErr)
return nil
}
vc.Signature = sig
rbft.logger.Infof("Replica %d sending viewChange, v:%d, h:%d, |C|:%d, |P|:%d, "+
"|Q|:%d, recovery: %+v", rbft.chainConfig.SelfID, vcBasis.GetView(), vcBasis.GetH(), len(vcBasis.GetCset()),
len(vcBasis.GetPset()), len(vcBasis.GetQset()), recovery)
rbft.logger.Debugf("Replica %d sending viewChange, if recover ValidatorDynamicInfo: %v", rbft.chainConfig.SelfID, showSimpleValidatorDynamicInfo(vc.Basis.IfRecoverValidatorDynamicInfo))
rbft.logger.Debugf("Replica %d sending viewChange, if not recover ValidatorDynamicInfo: %v", rbft.chainConfig.SelfID, showSimpleValidatorDynamicInfo(vc.Basis.IfNotRecoverValidatorDynamicInfo))
payload, err := vc.MarshalVTStrict()
if err != nil {
rbft.logger.Errorf("ConsensusMessage_VIEW_CHANGE Marshal Error: %s", err)
return nil
}
consensusMsg := &consensus.ConsensusMessage{
Type: consensus.Type_VIEW_CHANGE,
Payload: payload,
}
rbft.peerMgr.broadcast(context.TODO(), consensusMsg)
rbft.logger.Trace(consensus.TagNameViewChange, consensus.TagStageStart, consensus.TagContentViewChange{
Node: rbft.chainConfig.SelfID,
View: rbft.chainConfig.View,
})
event := &LocalEvent{
Service: ViewChangeService,
EventType: ViewChangeResendTimerEvent,
}
// start vcResendTimer. If peers can't viewChange successfully within the given time,
// enter recovery view change.
rbft.timerMgr.startTimer(vcResendTimer, event)
// start fetch view timer to actively fetch view periodically.
rbft.startFetchViewTimer()
return rbft.recvViewChange(vc, true)
}
// recvViewChange processes ViewChange message from itself or other peers
// if the number of ViewChange message for the same view reach on commonCaseQuorum, return ViewChangeQuorumEvent.
// else, peers may resend vc or wait more vc message arrived.
func (rbft *rbftImpl[T, Constraint]) recvViewChange(vc *consensus.ViewChange, verified bool) consensusEvent {
vcBasis := vc.Basis
remoteReplicaID := vcBasis.GetReplicaId()
targetView := vcBasis.GetView()
rbft.logger.Infof("Replica %d received viewChange from replica %d, v:%d, h:%d, "+
"|C|:%d, |P|:%d, |Q|:%d, recovery: %v", rbft.chainConfig.SelfID, remoteReplicaID, targetView, vcBasis.GetH(),
len(vcBasis.GetCset()), len(vcBasis.GetPset()), len(vcBasis.GetQset()), vc.Recovery)
rbft.logger.Debugf("Replica %d received viewChange from replica %d, if recover ValidatorDynamicInfo: %v", rbft.chainConfig.SelfID, remoteReplicaID, showSimpleValidatorDynamicInfo(vc.Basis.IfRecoverValidatorDynamicInfo))
rbft.logger.Debugf("Replica %d received viewChange from replica %d, if not recover ValidatorDynamicInfo: %v", rbft.chainConfig.SelfID, remoteReplicaID, showSimpleValidatorDynamicInfo(vc.Basis.IfNotRecoverValidatorDynamicInfo))
if targetView < rbft.chainConfig.View {
// for recovery node with a lower view, we can directly send back latest new view to help
// remote node advance to the latest new view if we are in normal status.
if vc.Recovery && rbft.isNormal() {
rbft.logger.Warningf("Replica %d found viewChange message for old view from "+
"replica %d, help remote recovery", rbft.chainConfig.SelfID, remoteReplicaID)
return rbft.sendRecoveryResponse(remoteReplicaID, targetView)
}
rbft.logger.Warningf("Replica %d found viewChange message for old view from "+
"replica %d: self view=%d, vc view=%d", rbft.chainConfig.SelfID, remoteReplicaID, rbft.chainConfig.View, targetView)
return nil
}
// check view change correctness
if !rbft.correctViewChange(vcBasis) {
rbft.logger.Warningf("Replica %d found viewChange message incorrect", rbft.chainConfig.SelfID)
return nil
}
// check if this view change has stored in viewChangeStore, if so, return nil
if old, ok := rbft.vcMgr.viewChangeStore[vcIdx{v: targetView, id: remoteReplicaID}]; ok {
if !vc.Recovery && old.Basis.EqualVT(vc.Basis) {
rbft.logger.Warningf("Replica %d already has a same viewChange message"+
" for view %d from replica %d, ignore it", rbft.chainConfig.SelfID, targetView, remoteReplicaID)
return nil
}
rbft.logger.Debugf("Replica %d already has an updated viewChange message"+
" for view %d from replica %d, replace it", rbft.chainConfig.SelfID, targetView, remoteReplicaID)
}
// verify view change signature if not verified.
if !verified {
vErr := rbft.verifySignedViewChange(vc, remoteReplicaID)
if vErr != nil {
rbft.logger.Errorf("Replica %d found invalid view change message, error: %s", rbft.chainConfig.SelfID, vErr)
return nil
}
}
vc.Timestamp = time.Now().UnixNano()
if rbft.chainConfig.CheckValidator(remoteReplicaID) {
// store vc to viewChangeStore
rbft.vcMgr.viewChangeStore[vcIdx{v: targetView, id: remoteReplicaID}] = vc
} else {
rbft.logger.Debugf("Replica %d not accept viewchane msg from non-validator %d",
rbft.chainConfig.SelfID, remoteReplicaID)
}
rbft.logger.Trace(consensus.TagNameViewChange, consensus.TagStageReceive, consensus.TagContentViewChange{
Node: remoteReplicaID,
View: targetView,
})
// RBFT TOCS 4.5.1 Liveness: "if a replica receives a set of
// f+1 valid VIEW-CHANGE messages from other replicas for
// views greater than its current view, it sends a VIEW-CHANGE
// message for the smallest view in the set, even if its timer
// has not expired"
replicas := make(map[uint64]bool)
minView := uint64(0)
for idx, remoteVC := range rbft.vcMgr.viewChangeStore {
if remoteVC.Timestamp+int64(rbft.timerMgr.getTimeoutValue(cleanViewChangeTimer)) < time.Now().UnixNano() {
rbft.logger.Debugf("Replica %d drop an out-of-time viewChange message from replica %d",
rbft.chainConfig.SelfID, idx.id)
delete(rbft.vcMgr.viewChangeStore, idx)
continue
}
if idx.v <= rbft.chainConfig.View {
continue
}
replicas[idx.id] = true
if minView == 0 || idx.v < minView {
minView = idx.v
}
}
// we only enter this if there are enough view change messages greater than our current view
if len(replicas) >= rbft.oneCorrectQuorum() {
rbft.logger.Infof("Replica %d received f+1 viewChange messages whose view is greater than "+
"current view %d, detailed: %v, triggering viewChange to view %d", rbft.chainConfig.SelfID, rbft.chainConfig.View, replicas, minView)
// subtract one, because sendViewChange() increments
newView := minView - uint64(1)
rbft.setView(newView)
return rbft.sendViewChange()
}
// calculate how many peers has view = rbft.chainConfig.View
quorum := 0
qvc := make([]*consensus.ViewChange, 0, len(rbft.vcMgr.viewChangeStore))
for idx, vcs := range rbft.vcMgr.viewChangeStore {
if idx.v == rbft.chainConfig.View {
quorum++
qvc = append(qvc, vcs)
}
}
rbft.logger.Debugf("Replica %d now has %d viewChange requests for view %d",
rbft.chainConfig.SelfID, quorum, rbft.chainConfig.View)
// if in viewChange and vc.view = rbft.chainConfig.View and quorum >= commonCaseQuorum,
// jump into ViewChangeQuorumEvent
if rbft.atomicIn(InViewChange) && targetView == rbft.chainConfig.View && quorum >= rbft.commonCaseQuorum() {
// close vcResendTimer
rbft.timerMgr.stopTimer(vcResendTimer)
// start newViewTimer and increase lastNewViewTimeout.
// if this view change failed, next viewChange will have more time to do it
// !!!NOTICE: only reset newViewTimer for the first time we reach the QuorumViewChange
rbft.softStartNewViewTimer(rbft.vcMgr.lastNewViewTimeout, "new viewChange", true)
rbft.vcMgr.lastNewViewTimeout = 2 * rbft.vcMgr.lastNewViewTimeout
if rbft.vcMgr.lastNewViewTimeout > 5*rbft.timerMgr.getTimeoutValue(newViewTimer) {
rbft.vcMgr.lastNewViewTimeout = 5 * rbft.timerMgr.getTimeoutValue(newViewTimer)
}
rbft.vcMgr.latestQuorumViewChange = &quorumViewChangeCache{
targetView: targetView,
QuorumViewChange: &consensus.QuorumViewChange{
ReplicaId: rbft.chainConfig.SelfID,
ViewChanges: qvc,
},
}
// packaging ViewChangeQuorumEvent message
return &LocalEvent{
Service: ViewChangeService,
EventType: ViewChangeQuorumEvent,
}
}
if rbft.isNormal() {
if rbft.chainConfig.isProposerElectionTypeWRF() {
if vc.Recovery {
rbft.logger.Warningf("Replica %d found viewChange message for higher view from "+
"replica %d, help remote recovery", rbft.chainConfig.SelfID, remoteReplicaID)
// for recovery node with a higher view, we can directly send back latest new view to help
// remote node rollback to the latest new view if we are in normal status.
return rbft.sendRecoveryResponse(remoteReplicaID, targetView)
}
// if received vc message from primary, send view change to other peers directly
if rbft.isPrimary(remoteReplicaID) {
rbft.logger.Infof("Replica %d received viewChange from old primary %d for view %d, "+
"trigger viewChange.", rbft.chainConfig.SelfID, remoteReplicaID, targetView)
return rbft.sendViewChange()
}
} else {
// if received vc message from primary, send view change to other peers directly
if rbft.isPrimary(remoteReplicaID) {
rbft.logger.Infof("Replica %d received viewChange from old primary %d for view %d, "+
"trigger viewChange.", rbft.chainConfig.SelfID, remoteReplicaID, targetView)
return rbft.sendViewChange()
}
if vc.Recovery {
rbft.logger.Warningf("Replica %d found viewChange message for higher view from "+
"replica %d, help remote recovery", rbft.chainConfig.SelfID, remoteReplicaID)
// for recovery node with a higher view, we can directly send back latest new view to help
// remote node rollback to the latest new view if we are in normal status.
return rbft.sendRecoveryResponse(remoteReplicaID, targetView)
}
}
}
return nil
}
func (rbft *rbftImpl[T, Constraint]) recvQuorumViewChange(qvc *consensus.QuorumViewChange) consensusEvent {
if len(qvc.ViewChanges) == 0 {
return nil
}
// TODO(DH): reject or not?
if rbft.atomicIn(StateTransferring) {
rbft.logger.Debugf("Replica %d reject QuorumViewChange as we are in state transfer", rbft.chainConfig.SelfID)
return nil
}
var (
remoteReplicaID = qvc.GetReplicaId()
targetView uint64
)
// ensure all ViewChanges have the same target view and target view is not lower than
// current view.
for i, vc := range qvc.ViewChanges {
vcBasis := vc.Basis
view := vcBasis.GetView()
if i == 0 {
targetView = view
if targetView < rbft.chainConfig.View {
rbft.logger.Warningf("Replica %d received an invalid QuorumViewChange from %d "+
"with a target view %d lower than current view %d", rbft.chainConfig.SelfID, remoteReplicaID,
targetView, rbft.chainConfig.View)
return nil
}
continue
}
if view != targetView {
rbft.logger.Warningf("Replica %d received an invalid QuorumViewChange from %d with "+
"mismatch target view %d and %d", rbft.chainConfig.SelfID, remoteReplicaID, view, targetView)
return nil
}
}
rbft.logger.Debugf("Replica %d received quorum view change from %d with target view %d, current view %d",
rbft.chainConfig.SelfID, remoteReplicaID, targetView, rbft.chainConfig.View)
// only process ViewChanges with higher view when node is in normal.
if rbft.isNormal() {
if targetView > rbft.chainConfig.View {
rbft.logger.Debugf("Replica %d process quorum view change in normal", rbft.chainConfig.SelfID)
rbft.processQuorumViewChange(qvc.ViewChanges, false)
}
return nil
}
// process ViewChanges with higher/equal view when node is in ViewChange status.
if rbft.atomicIn(InViewChange) {
if targetView >= rbft.chainConfig.View {
rbft.logger.Debugf("Replica %d process quorum view change in view change", rbft.chainConfig.SelfID)
rbft.processQuorumViewChange(qvc.ViewChanges, false)
}
return nil
}
return nil
}
// processQuorumViewChange loop process all view changes.
func (rbft *rbftImpl[T, Constraint]) processQuorumViewChange(vcs []*consensus.ViewChange, verified bool) {
for _, vc := range vcs {
// loop process potential events caused by receive view change.
if vc.Basis.GetReplicaId() == rbft.chainConfig.SelfID {
rbft.logger.Debugf("Replica %d reject process view change from itself", rbft.chainConfig.SelfID)
continue
}
next := rbft.recvViewChange(vc, verified)
if next != nil {
for {
next = rbft.processEvent(next)
if next == nil {
break
}
}
}
}
}
// sendNewView select suitable pqc from viewChangeStore as a new view message and
// broadcast to replica peers when peer is primary
func (rbft *rbftImpl[T, Constraint]) sendNewView() consensusEvent {
// if this new view has stored, return nil.
if _, ok := rbft.vcMgr.newViewStore[rbft.chainConfig.View]; ok {
rbft.logger.Warningf("Replica %d already has newView in store for view %d, ignore it",
rbft.chainConfig.SelfID, rbft.chainConfig.View)
return nil
}
var (
vcSet *consensus.QuorumViewChange
basis []*consensus.VcBasis
)
vcSet, basis = rbft.getViewChangeBasis()
validatorDynamicInfo, ok := rbft.selectValidatorDynamicInfo(vcSet.ViewChanges)
if !ok {
rbft.logger.Infof("Replica %d could not find consistent validatorDynamicInfo",
rbft.chainConfig.SelfID)
for _, vc := range vcSet.ViewChanges {
rbft.logger.Infof("Replica %d view change IfRecoverValidatorDynamicInfo: %v, IfNotRecoverValidatorDynamicInfo: %v", vc.Basis.ReplicaId, showSimpleValidatorDynamicInfo(vc.Basis.IfRecoverValidatorDynamicInfo), showSimpleValidatorDynamicInfo(vc.Basis.IfNotRecoverValidatorDynamicInfo))
}
return nil
}
// get suitable checkpoint for later recovery, replicas contains the peer no who has this checkpoint.
// if we can't find suitable checkpoint, ok return false.
checkpointState, checkpointSet, ok := rbft.selectInitialCheckpoint(basis)
if !ok {
rbft.logger.Infof("Replica %d could not find consistent checkpoint: %+v",
rbft.chainConfig.SelfID, rbft.vcMgr.viewChangeStore)
return nil
}
rbft.logger.Debugf("initial checkpoint: %+v", checkpointState)
// select suitable pqcCerts for later recovery. Their sequence is greater than cp
// if msgList is nil, must some bug happened
msgList := rbft.assignSequenceNumbers(basis, checkpointState.Meta.Height)
if msgList == nil {
rbft.logger.Infof("Replica %d could not assign sequence numbers for newView", rbft.chainConfig.SelfID)
return nil
}
rbft.logger.Debugf("x-set: %+v", msgList)
// create new view message
nv := &consensus.NewView{
View: rbft.chainConfig.View,
Xset: msgList,
ReplicaId: rbft.chainConfig.SelfID,
ViewChangeSet: vcSet,
QuorumCheckpoint: &consensus.QuorumCheckpoint{
Checkpoint: &consensus.Checkpoint{
ExecuteState: &consensus.Checkpoint_ExecuteState{
Height: checkpointState.Meta.Height,
Digest: checkpointState.Meta.Digest,
},
},
},
FromId: rbft.chainConfig.SelfID,
ValidatorDynamicInfo: validatorDynamicInfo,
}
sig, sErr := rbft.signNewView(nv)
if sErr != nil {
rbft.logger.Warningf("Replica %d sign new view failed: %s", rbft.chainConfig.SelfID, sErr)
return nil
}
nv.Signature = sig
// check if primary need state update
needStateUpdate := rbft.checkIfNeedStateUpdate(checkpointState, checkpointSet)
if needStateUpdate || rbft.atomicIn(StateTransferring) {
rbft.logger.Debugf("Primary %d needs to catch up in viewChange", rbft.chainConfig.SelfID)
return nil
}
rbft.logger.Infof("Replica %d is new primary, sending newView, v:%d, X:%+v",
rbft.chainConfig.SelfID, nv.View, msgList)
rbft.logger.Infof("Replica %d generated newView validatorDynamicInfo: %v",
rbft.chainConfig.SelfID, showSimpleValidatorDynamicInfo(validatorDynamicInfo))
payload, err := nv.MarshalVTStrict()
if err != nil {
rbft.logger.Errorf("ConsensusMessage_NEW_VIEW Marshal Error: %s", err)
return nil
}
consensusMsg := &consensus.ConsensusMessage{
Type: consensus.Type_NEW_VIEW,
Payload: payload,
}
// broadcast new view
rbft.peerMgr.broadcast(context.TODO(), consensusMsg)
// set new view to newViewStore
rbft.vcMgr.newViewStore[rbft.chainConfig.View] = nv
return rbft.primaryCheckNewView(msgList)
}
// recvNewView receives new view message and check if this node could
// process this message or not.
func (rbft *rbftImpl[T, Constraint]) recvNewView(nv *consensus.NewView) consensusEvent {
targetView, _, valid := rbft.checkNewView(nv)
if valid {
// direct process ViewChanges and then process new view.
rbft.processQuorumViewChange(nv.ViewChangeSet.ViewChanges, true)
// latestNewView mey be changed during above process(process vc -> primary generate new view ->
// update latestNewView), so we need to ensure not process the same new view again.
if rbft.vcMgr.latestNewView.View >= targetView {
rbft.logger.Noticef("Replica %d has advanced to view %d, ignore process new view %d",
rbft.chainConfig.SelfID, rbft.vcMgr.latestNewView.View, targetView)
return nil
}
rbft.vcMgr.newViewStore[targetView] = nv
return rbft.replicaCheckNewView()
}
return nil
}
// checkNewView checks the validity of new view message and returns new view info:
// 1. new view target view
// 2. new view hash
// 3. vc basis of new view
// 4. if new view is valid or not
func (rbft *rbftImpl[T, Constraint]) checkNewView(nv *consensus.NewView) (uint64, string, bool) {
rbft.logger.Infof("Replica %d received newView %d from replica %d", rbft.chainConfig.SelfID,
nv.View, nv.ReplicaId)
// view 0 is the initial view of every epoch, but valid NewView should start from 1.
if nv.View == 0 {
rbft.logger.Debugf("Replica %d reject invalid newView 0", rbft.chainConfig.SelfID)
return 0, "", false
}
// TODO(DH): reject or not?
if rbft.atomicIn(StateTransferring) {
rbft.logger.Debugf("Replica %d reject newView as we are in state transfer", rbft.chainConfig.SelfID)
return 0, "", false
}
// wrf recovery cannot check the PrimaryID
if !rbft.chainConfig.isProposerElectionTypeWRF() {
expectedPrimaryID := rbft.chainConfig.calPrimaryIDByView(nv.View, rbft.chainConfig.ValidatorDynamicInfoMap)
if expectedPrimaryID != nv.ReplicaId {
rbft.logger.Warningf("Replica %d reject invalid newView from %d, v:%d, expected primary: %d",
rbft.chainConfig.SelfID, nv.ReplicaId, nv.View, expectedPrimaryID)
rbft.logger.Debugf("Replica %d current height: %d, dig: %s",
rbft.chainConfig.SelfID, rbft.exec.lastExec, rbft.chainConfig.LastCheckpointExecBlockHash)
return 0, "", false
}
}
var (
targetView uint64
)
// ensure all ViewChanges have the same target view and target view is equal to
// NewView.view.
for i, vc := range nv.ViewChangeSet.ViewChanges {
vcBasis := vc.Basis
view := vcBasis.GetView()
if i == 0 {
targetView = view
if targetView != nv.View {
rbft.logger.Warningf("Replica %d received an invalid NewView with mismatch target "+
"view %d and NewView %d", rbft.chainConfig.SelfID, targetView, nv.View)
return 0, "", false
}
continue
}
if view != targetView {
rbft.logger.Warningf("Replica %d received an invalid NewView with mismatch target "+
"view %d and %d", rbft.chainConfig.SelfID, view, targetView)
return 0, "", false
}
}
validatorDynamicInfo, ok := rbft.selectValidatorDynamicInfo(nv.ViewChangeSet.ViewChanges)
if !ok {
rbft.logger.Infof("Replica %d received an invalid NewView that could not find consistent validatorDynamicInfo",
rbft.chainConfig.SelfID)
for _, vc := range nv.ViewChangeSet.ViewChanges {
rbft.logger.Infof("Replica %d view change IfRecoverValidatorDynamicInfo: %v, IfNotRecoverValidatorDynamicInfo: %v", vc.Basis.ReplicaId, showSimpleValidatorDynamicInfo(vc.Basis.IfRecoverValidatorDynamicInfo), showSimpleValidatorDynamicInfo(vc.Basis.IfNotRecoverValidatorDynamicInfo))
}
return 0, "", false
}
if !consensus.ValidatorDynamicInfoEqual(validatorDynamicInfo, nv.ValidatorDynamicInfo) {
rbft.logger.Warningf("Replica %d received an invalid NewView with mismatch validatorDynamicInfo, viewchange's: %v, newView's: %v", rbft.chainConfig.SelfID, showSimpleValidatorDynamicInfo(validatorDynamicInfo), showSimpleValidatorDynamicInfo(nv.ValidatorDynamicInfo))
return 0, "", false
}
// verify signature of new view.
nvHash, vErr := rbft.verifySignedNewView(nv)
if vErr != nil {
rbft.logger.Errorf("Replica %d found invalid new view message, error: %s", rbft.chainConfig.SelfID, vErr)
return 0, "", false
}
// verify the signatures of all view changes contained in new view are all correct.
for _, vc := range nv.ViewChangeSet.ViewChanges {
vErr = rbft.verifySignedViewChange(vc, vc.Basis.GetReplicaId())
if vErr != nil {
rbft.logger.Errorf("Replica %d found invalid view change message in new view, error: %s",
rbft.chainConfig.SelfID, vErr)
return 0, "", false
}
}
// if current node is in normal, check the target view
// 1. targetView > current view, process all view changes and new view to advance view
// 2. targetView <= current view, may be sent from some out-of-date nodes, ignore it as
// we are normal in a more advanced view.
if rbft.isNormal() {
if targetView > rbft.chainConfig.View {
return targetView, "", true
}
rbft.logger.Warningf("Replica %d reject process new view %d as we "+
"are in normal", rbft.chainConfig.SelfID, targetView)
return 0, "", false
} else if rbft.atomicIn(InRecovery) {
// if current node is in recovery, direct process new view.
return targetView, hex.EncodeToString(nvHash), true
} else if rbft.atomicIn(InViewChange) {
// if current node is in view change, check the target view
// 1. targetView >= current view, process all view changes and new view to advance view
// 2. targetView < current view, which indicates an invalid NewView of current view change
// progress, ignore it.
if targetView >= rbft.chainConfig.View {
return targetView, "", true
}
return 0, "", false
}
return targetView, "", true
}
// tryFetchView tries fetch view in view change status, compares local view and remote view:
// 1. remoteView > currentView, fetch view
// 2. remoteView <= currentView, ignore
func (rbft *rbftImpl[T, Constraint]) tryFetchView() {
if !rbft.atomicIn(InViewChange) {
rbft.logger.Debugf("Replica %d not try to fetch view in normal status", rbft.chainConfig.SelfID)
return
}
// fetch view when remote node has larger view and current node is in view change,
// ask remote node response new view info to help self advance view.
for remoteID, remoteView := range rbft.vcMgr.higherViewRecord {
if remoteView > rbft.chainConfig.View {
// create fetchView message
fv := &consensus.FetchView{
ReplicaId: rbft.chainConfig.SelfID,
View: rbft.chainConfig.View,
}
rbft.logger.Infof("Replica %d sending fetch view to %d, current view: %d, "+
"remote view: %d", rbft.chainConfig.SelfID, remoteID, rbft.chainConfig.View, remoteView)
payload, err := fv.MarshalVTStrict()
if err != nil {
rbft.logger.Errorf("ConsensusMessage_FETCH_VIEW Marshal Error: %s", err)
return
}
consensusMsg := &consensus.ConsensusMessage{
Type: consensus.Type_FETCH_VIEW,
Payload: payload,
}
rbft.peerMgr.unicast(context.TODO(), consensusMsg, remoteID)
return
}
delete(rbft.vcMgr.higherViewRecord, remoteID)
}
rbft.startFetchViewTimer()
}
// recvFetchView helps remote node recover view and height using latestQuorumViewChange and latestNewView cache.
func (rbft *rbftImpl[T, Constraint]) recvFetchView(fv *consensus.FetchView) consensusEvent {
rbft.logger.Debugf("Replica %d received fetch view from %d, current view: %d, "+
"remote view: %d", rbft.chainConfig.SelfID, fv.ReplicaId, rbft.chainConfig.View, fv.View)
if !(rbft.chainConfig.View > fv.View) {
rbft.logger.Debugf("Replica %d don't need to response fetch view as we don't "+
"have a larger view", rbft.chainConfig.SelfID)
return nil
}
// 1. check if we have latest QuorumViewChange record, which means we are in ViewChange status
// and received quorum correct ViewChanges, we can forward this QuorumViewChange to help remote
// node advance its view.
if qvc := rbft.vcMgr.latestQuorumViewChange; qvc != nil {
rbft.logger.Infof("Replica %d sending quorum view change to %d, current view: %d, "+
"remote view: %d", rbft.chainConfig.SelfID, fv.ReplicaId, rbft.chainConfig.View, fv.View)
payload, err := qvc.MarshalVTStrict()
if err != nil {
rbft.logger.Errorf("ConsensusMessage_QUORUM_VIEW_CHANGE Marshal Error: %s", err)
return nil
}
consensusMsg := &consensus.ConsensusMessage{
Type: consensus.Type_QUORUM_VIEW_CHANGE,
Payload: payload,
}
rbft.peerMgr.unicast(context.TODO(), consensusMsg, fv.ReplicaId)
return nil
}
// 2. send back NewView as response to help remote node advance its view if we have no QuorumViewChange
// cache.
nv := rbft.vcMgr.latestNewView
rbft.logger.Infof("Replica %d sending back newView to %d, v:%d", rbft.chainConfig.SelfID, fv.ReplicaId, nv.View)
payload, err := nv.MarshalVTStrict()
if err != nil {
rbft.logger.Errorf("ConsensusMessage_NEW_VIEW Marshal Error: %s", err)
return nil
}
consensusMsg := &consensus.ConsensusMessage{
Type: consensus.Type_NEW_VIEW,
Payload: payload,
}
rbft.peerMgr.unicast(context.TODO(), consensusMsg, fv.ReplicaId)
return nil
}
// sendRecoveryResponse sends recovery response to help remote node recover to a correct state including:
// 1. latest new view info to help remote node advance to a correct view
// 2. latest stable checkpoint info to help remote node advance to a correct initial checkpoint height
func (rbft *rbftImpl[T, Constraint]) sendRecoveryResponse(remoteReplicaID, remoteView uint64) error {
nv := rbft.vcMgr.latestNewView
// directly return NewView response to help remote node recover view as we are in normal.
rbft.logger.Infof("Replica %d sending new view response to %d, current view: %d, remote view: %d",
rbft.chainConfig.SelfID, remoteReplicaID, rbft.chainConfig.View, remoteView)
rcr := &consensus.RecoveryResponse{
NewView: nv,
InitialCheckpoint: rbft.storeMgr.localCheckpoints[rbft.chainConfig.H],
GenesisBlockDigest: rbft.config.GenesisBlockDigest,
}
payload, err := rcr.MarshalVTStrict()
if err != nil {
rbft.logger.Errorf("ConsensusMessage_RECOVERY_RESPONSE Marshal Error: %s", err)
return nil
}
consensusMsg := &consensus.ConsensusMessage{
Type: consensus.Type_RECOVERY_RESPONSE,
Payload: payload,
}
rbft.peerMgr.unicast(context.TODO(), consensusMsg, remoteReplicaID)
return nil
}
// recvRecoveryResponse process response.NewView to recover view and then process response.H to recover height.
func (rbft *rbftImpl[T, Constraint]) recvRecoveryResponse(rcr *consensus.RecoveryResponse) consensusEvent {
if rcr.GetNewView() == nil || rcr.GetInitialCheckpoint() == nil {
rbft.logger.Errorf("Replica %d received nil recovery response", rbft.chainConfig.SelfID)
return nil
}
rbft.logger.Debugf("Replica %d received recovery response from %d", rbft.chainConfig.SelfID,
rcr.GetInitialCheckpoint().GetAuthor())
// current node is in recovery, which is caused by single node view change, cache this NewView
// until received f+1 NewViews with the same targetView, and trigger single node recovery to
// this targetView.
if rbft.atomicIn(InRecovery) {
if rcr.GenesisBlockDigest != rbft.config.GenesisBlockDigest {
rbft.logger.Criticalf("Replica %d self genesis config is not consistent with most nodes, expected genesis block hash: %s, self genesis block hash: %s",
rbft.chainConfig.SelfID, rcr.GenesisBlockDigest, rbft.config.GenesisBlockDigest)
}
nv := rcr.GetNewView()
targetView, nvHash, valid := rbft.checkNewView(nv)
if valid {
// only process response in recovery status, which is caused by single node view change
return rbft.resetStateForRecovery(targetView, nvHash, rcr)
}
}
return nil
}
// primaryCheckNewView do some prepare for change to New view