-
Notifications
You must be signed in to change notification settings - Fork 0
/
consensus_tbft_impl.go
2702 lines (2423 loc) · 97.9 KB
/
consensus_tbft_impl.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) THL A29 Limited, a Tencent company. All rights reserved.
SPDX-License-Identifier: Apache-2.0
*/
package tbft
import (
"bytes"
"context"
"encoding/base64"
"errors"
"fmt"
"math/rand"
"reflect"
"strconv"
"sync"
"time"
"chainmaker.org/chainmaker/chainconf/v2"
"chainmaker.org/chainmaker/localconf/v2"
"chainmaker.org/chainmaker/protocol/v2"
"chainmaker.org/chainmaker/utils/v2"
"chainmaker.org/chainmaker/common/v2/msgbus"
consensusUtils "chainmaker.org/chainmaker/consensus-utils/v2"
"chainmaker.org/chainmaker/consensus-utils/v2/consistent_service"
"chainmaker.org/chainmaker/consensus-utils/v2/wal_service"
"chainmaker.org/chainmaker/lws"
"chainmaker.org/chainmaker/pb-go/v2/common"
"chainmaker.org/chainmaker/pb-go/v2/config"
consensuspb "chainmaker.org/chainmaker/pb-go/v2/consensus"
tbftpb "chainmaker.org/chainmaker/pb-go/v2/consensus/tbft"
netpb "chainmaker.org/chainmaker/pb-go/v2/net"
"github.com/gogo/protobuf/proto"
"go.uber.org/zap"
)
var clog = zap.S()
var (
defaultChanCap = 1000
nilHash = []byte("NilHash")
//consensusStateKey = []byte("ConsensusStateKey")
defaultConsensusStateCacheSize = uint64(10)
defaultConsensusFutureCacheSize = uint64(10)
// TBFTAddtionalDataKey implements the block key for store tbft infos
TBFTAddtionalDataKey = "TBFTAddtionalDataKey"
// TBFT_propose_timeout_key implements the config key for chainconf
TBFT_propose_timeout_key = "TBFT_propose_timeout"
// TBFT_propose_delta_timeout_key implements the config key for chainconf
TBFT_propose_delta_timeout_key = "TBFT_propose_delta_timeout"
// TBFT_blocks_per_proposer implements the config key for chainconf
TBFT_blocks_per_proposer = "TBFT_blocks_per_proposer"
// TBFT_propose_timeout_optimal_key implements the config key for chainconf
TBFT_propose_timeout_optimal_key = "TBFT_propose_timeout_optimal"
// TBFT_propose_optimal_key implements the config key for chainconf
TBFT_propose_optimal_key = "TBFT_propose_optimal"
// blockVersion231 the blockchain v2.3.1 version
blockVersion231 = uint32(2030100)
)
const (
// DefaultTimeoutPropose Timeout of waitting for a proposal before prevoting nil
DefaultTimeoutPropose = 30 * time.Second
// DefaultTimeoutProposeDelta Increased time delta of TimeoutPropose between rounds
DefaultTimeoutProposeDelta = 1 * time.Second
// DefaultBlocksPerProposer The number of blocks each proposer can propose
DefaultBlocksPerProposer = uint64(1)
// DefaultTimeoutProposeOptimal optimal timeout of waitting for a proposal before prevoting nil
DefaultTimeoutProposeOptimal = 2 * time.Second
// TimeoutPrevote Timeout of waiting for >2/3 prevote
TimeoutPrevote = 30 * time.Second
// TimeoutPrevoteDelta Increased time delta of TimeoutPrevote between round
TimeoutPrevoteDelta = 1 * time.Second
// TimeoutPrecommit Timeout of waiting for >2/3 precommit
TimeoutPrecommit = 30 * time.Second
// TimeoutPrecommitDelta Increased time delta of TimeoutPrecommit between round
TimeoutPrecommitDelta = 1 * time.Second
// TimeoutCommit Timeout to wait for precommite
TimeoutCommit = 30 * time.Second
// TimeDisconnet the duration of node disconnectio(3000ms)
TimeDisconnet = 3000
)
var msgBusTopics = []msgbus.Topic{msgbus.ProposedBlock, msgbus.VerifyResult,
msgbus.RecvConsensusMsg, msgbus.RecvConsistentMsg, msgbus.BlockInfo}
// mustMarshal marshals protobuf message to byte slice or panic when marshal twice both failed
func mustMarshal(msg proto.Message) (data []byte) {
var err error
defer func() {
// while first marshal failed, retry marshal again
if recover() != nil {
data, err = proto.Marshal(msg)
if err != nil {
panic(err)
}
}
}()
data, err = proto.Marshal(msg)
if err != nil {
panic(err)
}
return
}
// mustUnmarshal unmarshals from byte slice to protobuf message or panic
func mustUnmarshal(b []byte, msg proto.Message) {
if err := proto.Unmarshal(b, msg); err != nil {
panic(err)
}
}
// ConsensusTBFTImpl is the implementation of TBFT algorithm
// and it implements the ConsensusEngine interface.
type ConsensusTBFTImpl struct {
sync.RWMutex
ctx context.Context
logger protocol.Logger
// chain id
chainID string
// node id
Id string
// Currently nil, not used
extendHandler protocol.ConsensusExtendHandler
// signer(node)
signer protocol.SigningMember
// sync service
syncService protocol.SyncService
// Access Control
ac protocol.AccessControlProvider
// Cache the latest block in ledger(wal)
ledgerCache protocol.LedgerCache
// The Proposer of the last block commit height
lastHeightProposer string
// block version
blockVersion uint32
// chain conf
chainConf protocol.ChainConf
// net service (Need to use network module method GetNodeUidByCertId)
netService protocol.NetService
// send/receive a message using msgbus
msgbus msgbus.MessageBus
// stop tbft
closeC chan struct{}
// wal is used to record the consensus state and prevent forks
wal *lws.Lws
// write wal sync: 0
walWriteMode wal_service.WalWriteMode
// validator Set
validatorSet *validatorSet
// Current Consensus State
*ConsensusState
// History Consensus State(Save 10)
// When adding n, delete the cache before n-10
consensusStateCache *consensusStateCache
// Cache future consensus msg
// When update height of consensus, delete the cache before height (triggered every 10 heights)
consensusFutureMsgCache *ConsensusFutureMsgCache
// timeScheduler is used by consensus for shecdule timeout events.
// Outdated timeouts will be ignored in processing.
timeScheduler *timeScheduler
// channel for processing a block
proposedBlockC chan *proposedProposal
// channel used to verify the results
verifyResultC chan *consensuspb.VerifyResult
// channel used to enter new height
blockHeightC chan uint64
// channel used to externalMsg(msgbus)
externalMsgC chan *ConsensusMsg
// Use in handleConsensusMsg method
internalMsgC chan *ConsensusMsg
invalidTxs []string
// Timeout = TimeoutPropose + TimeoutProposeDelta * round
TimeoutPropose time.Duration
TimeoutProposeDelta time.Duration
TimeoutProposeOptimal time.Duration
ProposeOptimal bool
ProposeOptimalTimer *time.Timer
// The specific time points of each stage of each round in each altitude
// for printing logs
metrics *heightMetrics
// Tbft Consistent Engine
// will only work if the node is abnormal
// prevent message loss
consistentEngine consistent_service.ConsistentEngine
// use block verifier from core module
blockVerifier protocol.BlockVerifier
messagePool MessagePool
}
// Type return Status Type(ConsistentEngine)
// @receiver consensus
// @return int
func (consensus *ConsensusTBFTImpl) Type() int8 {
return TypeLocalTBFTState
}
// Data return Status Data(ConsistentEngine)
// @receiver consensus
// @return interface{}
func (consensus *ConsensusTBFTImpl) Data() interface{} {
return consensus
}
// Update update state
// @receiver consensus
// @param state
func (consensus *ConsensusTBFTImpl) Update(state consistent_service.Status) {
consensus.logger.Debugf("update %s", state.Type())
}
// New creates a tbft consensus instance
func New(config *consensusUtils.ConsensusImplConfig) (*ConsensusTBFTImpl, error) {
var err error
consensus := &ConsensusTBFTImpl{}
consensus.logger = config.Logger
consensus.logger.Infof("New ConsensusTBFTImpl[%s]", config.NodeId)
consensus.chainID = config.ChainId
consensus.Id = config.NodeId
consensus.signer = config.Signer
consensus.ac = config.Ac
consensus.syncService = config.Sync
consensus.ledgerCache = config.LedgerCache
consensus.chainConf = config.ChainConf
consensus.netService = config.NetService
consensus.msgbus = config.MsgBus
consensus.closeC = make(chan struct{})
// init the wal service
consensus.wal, consensus.walWriteMode, err = InitLWS(config.ChainConf.ChainConfig().Consensus,
consensus.chainID, consensus.Id)
if err != nil {
return nil, err
}
consensus.proposedBlockC = make(chan *proposedProposal, defaultChanCap)
consensus.verifyResultC = make(chan *consensuspb.VerifyResult, defaultChanCap)
consensus.blockHeightC = make(chan uint64, defaultChanCap)
consensus.externalMsgC = make(chan *ConsensusMsg, defaultChanCap)
consensus.internalMsgC = make(chan *ConsensusMsg, defaultChanCap)
consensus.blockVerifier = config.Core.GetBlockVerifier()
validators, err := GetValidatorListFromConfig(consensus.chainConf.ChainConfig())
if err != nil {
return nil, err
}
consensus.validatorSet = newValidatorSet(consensus.logger, validators, DefaultBlocksPerProposer)
consensus.ConsensusState = NewConsensusState(consensus.logger, consensus.Id)
consensus.consensusStateCache = newConsensusStateCache(defaultConsensusStateCacheSize)
consensus.consensusFutureMsgCache = newConsensusFutureMsgCache(consensus.logger,
defaultConsensusFutureCacheSize, 0)
consensus.timeScheduler = newTimeSheduler(consensus.logger, config.NodeId)
consensus.ProposeOptimal = false
consensus.ProposeOptimalTimer = time.NewTimer(1 * time.Second)
consensus.ProposeOptimalTimer.Stop()
// get broadcaster interval from local config
broadcasterInterval := localconf.ChainMakerConfig.ConsensusConfig.TbftConfig.BroadcasterInterval
if broadcasterInterval != 0 {
TimerInterval = broadcasterInterval * time.Millisecond
}
consensus.messagePool = *newMessagePool(20, make([]*ConsensusMsg, 0))
return consensus, nil
}
// InitConsistentEngine init ConsistentEngine
// @receiver consensus
func (consensus *ConsensusTBFTImpl) InitConsistentEngine() {
status := make(map[int8]consistent_service.Status)
status[consensus.Type()] = consensus
localStatus := &Node{
id: consensus.Id,
status: status,
}
message := NewTbftConsistentMessage(consensus.msgbus, consensus.logger)
// create consistentEngine
consensus.consistentEngine = consistent_service.NewConsistentService(
localStatus,
message,
consensus.logger)
tbftStatusInterceptor := &StatusInterceptor{}
// register a tbftStatusInterceptor
err := consensus.consistentEngine.RegisterStatusInterceptor(InterceptorTbft, tbftStatusInterceptor)
if err != nil {
consensus.logger.Errorf(err.Error())
}
tbftDecoder := &StatusDecoder{log: consensus.logger,
tbftImpl: consensus}
// register a tbftDecoder
err = consensus.consistentEngine.RegisterStatusCoder(tbftDecoder.MsgType(), tbftDecoder)
if err != nil {
consensus.logger.Errorf("RegisterStatusCoder err:%s", err)
return
}
// add a remoter
for _, id := range consensus.validatorSet.Validators {
// local node do not need to be added to the consistency engine
if id == consensus.Id {
continue
}
remoteState := &RemoteState{Id: id, Height: 0}
status := make(map[int8]consistent_service.Status)
status[remoteState.Type()] = remoteState
remoteNodeStatus := &Node{id: id, status: status}
err = consensus.consistentEngine.PutRemoter(id, remoteNodeStatus)
if err != nil {
consensus.logger.Errorf(err.Error())
}
}
// create a tbftStatusBroadcaster
tbftStatusBroadcaster := NewTBFTStatusBroadcaster(
consensus.logger)
// add a tbftStatusBroadcaster to the consistentEngine
err = consensus.consistentEngine.AddBroadcaster(StatusBroadcasterTbft, tbftStatusBroadcaster)
if err != nil {
consensus.logger.Errorf("AddBroadcaster err:%s", err)
}
}
// StartConsistentEngine start consistent engine
// @Description: Start ConsistentEngine
// @receiver consensus
func (consensus *ConsensusTBFTImpl) StartConsistentEngine() error {
// start the consistentEngine
consensus.ctx = context.Background()
err := consensus.consistentEngine.Start(consensus.ctx)
if err != nil {
consensus.logger.Errorf(err.Error())
}
return err
}
// Start starts the tbft instance with:
// 1. Register to message bus for subscribing topics
// 2. Start background goroutinues for processing events
// 3. Start timeScheduler for processing timeout shedule
// the consensus module monitors the signal of the sync module,
// when the sync module synchronizes a relatively high block,
// it notifies the consensus module to start the consensus process
func (consensus *ConsensusTBFTImpl) Start() error {
go func() {
if consensus.syncService != nil &&
!(consensus.validatorSet.Size() == 1 && consensus.validatorSet.HasValidator(consensus.Id)) {
<-consensus.syncService.ListenSyncToIdealHeight()
}
for _, topic := range msgBusTopics {
consensus.msgbus.Register(topic, consensus)
}
_ = chainconf.RegisterVerifier(consensus.chainID, consensuspb.ConsensusType_TBFT, consensus)
consensus.logger.Infof("start ConsensusTBFTImpl[%s]", consensus.Id)
consensus.timeScheduler.Start()
consensus.InitConsistentEngine()
err := consensus.replayWal()
if err != nil {
consensus.logger.Warnf("replayWal failed, err = %v", err)
return
}
err = consensus.StartConsistentEngine()
if err != nil {
return
}
//consensus.startLogReader()
//consensus.gossip.start()
go consensus.handle()
}()
return nil
}
func (consensus *ConsensusTBFTImpl) startLogReader() {
consensus.logger.Infof("fuzzing: [%s] logReader start", consensus.Id)
defer consensus.logger.Infof("fuzzing: [%s] logReader end", consensus.Id)
// 检查共识日志
for i := 1; i <= 4; i = i + 1 {
id := i
go func() {
err := ReadSystemLog(id, &consensus.logger)
if err != nil {
consensus.logger.Errorf("fuzzing: LogReader %d failed:"+err.Error(), id)
return
}
}()
}
}
// sendProposeState
// @Description: Send propose state via msgbus
// @receiver consensus
// @param isProposer Is it a proposal node
func (consensus *ConsensusTBFTImpl) sendProposeState(isProposer bool) {
consensus.logger.Infof("[%s](%d/%d/%s) sendProposeState isProposer: %v",
consensus.Id, consensus.Height, consensus.Round, consensus.Step, isProposer)
new_isProposer := isProposer
nodeConfig := GetConfig()
var err error
if nodeConfig.IsFuzzNode {
if nodeConfig.SendProposeStateFuzz {
new_isProposer = MutateBool(isProposer)
if err != nil {
consensus.logger.Errorf(err.Error())
return
}
consensus.logger.Infof("we mutate proposestate message in sendProposeState function and send it")
} else {
consensus.logger.Infof("we don't mutate block message in sendProposeState function and send it")
}
if nodeConfig.Delay {
d := nodeConfig.DelayBase + rand.Int()%(nodeConfig.DelayLim-nodeConfig.DelayBase)
time.Sleep(time.Second * time.Duration(d))
}
}
consensus.msgbus.PublishSafe(msgbus.ProposeState, new_isProposer)
}
// Stop implements the Stop method of ConsensusEngine interface.
func (consensus *ConsensusTBFTImpl) Stop() error {
displayMsgPool(consensus, &consensus.messagePool)
consensus.Lock()
defer consensus.Unlock()
for _, topic := range msgBusTopics {
consensus.msgbus.UnRegister(topic, consensus)
}
consensus.logger.Infof("[%s](%d/%d/%s) stopped", consensus.Id, consensus.Height, consensus.Round,
consensus.Step)
if consensus.consistentEngine != nil {
err := consensus.consistentEngine.Stop(consensus.ctx)
if err != nil {
consensus.logger.Errorf(err.Error())
}
}
consensus.wal.Close()
close(consensus.closeC)
return nil
}
// InitExtendHandler r egistered extendHandler
func (consensus *ConsensusTBFTImpl) InitExtendHandler(handler protocol.ConsensusExtendHandler) {
consensus.extendHandler = handler
}
// 1. when leadership transfer, change consensus state and send singal
// atomic.StoreInt32()
// proposable <- atomic.LoadInt32(consensus.isLeader)
// 2. when receive pre-prepare block, send block to verifyBlockC
// verifyBlockC <- block
// 3. when receive commit block, send block to commitBlockC
// commitBlockC <- block
// OnMessage implements the OnMessage method of msgbus.
func (consensus *ConsensusTBFTImpl) OnMessage(message *msgbus.Message) {
consensus.logger.Debugf("[%s] OnMessage receive topic: %s", consensus.Id, message.Topic)
switch message.Topic {
case msgbus.ProposedBlock:
if proposedBlock, ok := message.Payload.(*consensuspb.ProposalBlock); ok {
consensus.proposedBlockC <- &proposedProposal{proposedBlock, nil}
consensus.logger.Debugf("len of proposedBlockC: %d", len(consensus.proposedBlockC))
} else {
consensus.logger.Warnf("assert ProposalBlock failed, get type:{%s}", reflect.TypeOf(message.Payload))
}
case msgbus.VerifyResult:
if verifyResult, ok := message.Payload.(*consensuspb.VerifyResult); ok {
consensus.logger.Debugf("[%s] verify result: %s", consensus.Id, verifyResult.Code)
consensus.verifyResultC <- verifyResult
} else {
consensus.logger.Warnf("assert VerifyResult failed, get type:{%s}", reflect.TypeOf(message.Payload))
}
case msgbus.RecvConsensusMsg:
if msg, ok := message.Payload.(*netpb.NetMsg); ok {
if consensusMsg := consensus.createConsensusMsgFromTBFTMsgBz(msg.Payload); consensusMsg != nil {
consensus.externalMsgC <- consensusMsg
} else {
consensus.logger.Warnf("assert Consensus Msg failed")
}
} else {
consensus.logger.Warnf("assert NetMsg failed, get type:{%s}", reflect.TypeOf(message.Payload))
}
case msgbus.RecvConsistentMsg:
if msg, ok := message.Payload.(*netpb.NetMsg); ok {
if consensusMsg := consensus.createConsensusMsgFromTBFTMsgBz(msg.Payload); consensusMsg != nil {
consensus.externalMsgC <- consensusMsg
} else {
consensus.logger.Warnf("assert Consensus Msg failed")
}
} else {
consensus.logger.Warnf("assert NetMsg failed, get type:{%s}", reflect.TypeOf(message.Payload))
}
case msgbus.BlockInfo:
if blockInfo, ok := message.Payload.(*common.BlockInfo); ok {
if blockInfo == nil || blockInfo.Block == nil {
consensus.logger.Errorf("receive message failed, error message BlockInfo = nil")
return
}
consensus.blockHeightC <- blockInfo.Block.Header.BlockHeight
} else {
consensus.logger.Warnf("assert BlockInfo failed, get type:{%s}", reflect.TypeOf(message.Payload))
}
}
}
// OnQuit implements the OnQuit method of msgbus.
func (consensus *ConsensusTBFTImpl) OnQuit() {
consensus.logger.Infof("ConsensusTBFTImpl msgbus OnQuit")
// do nothing
//panic("implement me")
}
// Verify implements interface of struct Verifier,
// This interface is used to verify the validity of parameters,
// it executes before consensus.
func (consensus *ConsensusTBFTImpl) Verify(consensusType consensuspb.ConsensusType,
chainConfig *config.ChainConfig) error {
consensus.logger.Infof("[%s](%d/%d/%v) verify chain consensusConfig",
consensus.Id, consensus.Height, consensus.Round, consensus.Step)
if consensusType != consensuspb.ConsensusType_TBFT {
errMsg := fmt.Sprintf("consensus type is not TBFT: %s", consensusType)
return errors.New(errMsg)
}
consensusConfig := chainConfig.Consensus
_, _, _, _, _, _, err := consensus.extractConsensusConfig(consensusConfig)
return err
}
// updateChainConfig
// @Description: Update configuration, return validators to be added and removed
// @receiver consensus
// @return addedValidators
// @return removedValidators
// @return err
func (consensus *ConsensusTBFTImpl) updateChainConfig() (addedValidators []string, removedValidators []string,
err error) {
consensus.logger.Debugf("[%s](%d/%d/%v) update chain consensusConfig",
consensus.Id, consensus.Height, consensus.Round, consensus.Step)
consensusConfig := consensus.chainConf.ChainConfig().Consensus
validators, timeoutPropose, timeoutProposeDelta, tbftBlocksPerProposer, proposeOptimal,
timeoutProposeOptimal, err := consensus.extractConsensusConfig(consensusConfig)
if err != nil {
return nil, nil, err
}
consensus.ProposeOptimal = proposeOptimal
consensus.TimeoutProposeOptimal = timeoutProposeOptimal
consensus.TimeoutPropose = timeoutPropose
consensus.TimeoutProposeDelta = timeoutProposeDelta
consensus.logger.Debugf("[%s](%d/%d/%v) update chain consensusConfig, consensusConfig: %v,"+
" TimeoutPropose: %v, TimeoutProposeDelta: %v, ProposeOptimal:%v, TimeoutProposeOptimal:%v, validators: %v",
consensus.Id, consensus.Height, consensus.Round, consensus.Step, consensusConfig,
consensus.TimeoutPropose, consensus.TimeoutProposeDelta, consensus.TimeoutProposeOptimal, consensus.ProposeOptimal,
validators)
if consensus.extendHandler != nil {
consensus.logger.Debugf("enter extend handle to get proposers ...")
if validators, err = consensus.extendHandler.GetValidators(); err != nil {
return nil, nil, err
}
} else {
consensus.logger.Debugf("enter default tbft to get proposers ...")
err := consensus.validatorSet.updateBlocksPerProposer(tbftBlocksPerProposer)
if err != nil {
consensus.logger.Errorf("update Proposer per Blocks failed err: %s", err)
}
}
return consensus.validatorSet.updateValidators(validators)
}
// extractConsensusConfig
// @Description: return config from extractConsensusConfig
// @receiver consensus
// @param config
// @return validators
// @return timeoutPropose
// @return timeoutProposeDelta
// @return tbftBlocksPerProposer
// @return err
func (consensus *ConsensusTBFTImpl) extractConsensusConfig(config *config.ConsensusConfig) (validators []string,
timeoutPropose time.Duration, timeoutProposeDelta time.Duration, tbftBlocksPerProposer uint64,
proposeOptimal bool, timeoutProposeOptimal time.Duration, err error) {
timeoutPropose = DefaultTimeoutPropose
timeoutProposeDelta = DefaultTimeoutProposeDelta
timeoutProposeOptimal = DefaultTimeoutProposeOptimal
tbftBlocksPerProposer = uint64(1)
proposeOptimal = false
validators, err = GetValidatorListFromConfig(consensus.chainConf.ChainConfig())
if err != nil {
consensus.logger.Errorf("[%s](%d/%d/%v) get validator list from config failed: %v",
consensus.Id, consensus.Height, consensus.Round, consensus.Step, validators)
return
}
for _, v := range config.ExtConfig {
switch v.Key {
case TBFT_propose_timeout_key:
timeoutPropose, err = consensus.extractProposeTimeout(v.Value)
case TBFT_propose_delta_timeout_key:
timeoutProposeDelta, err = consensus.extractProposeTimeoutDelta(v.Value)
case TBFT_blocks_per_proposer:
tbftBlocksPerProposer, err = consensus.extractBlocksPerProposer(v.Value)
case TBFT_propose_optimal_key:
proposeOptimal, err = consensus.extractProposeOptimal(v.Value)
case TBFT_propose_timeout_optimal_key:
timeoutProposeOptimal, err = consensus.extractTimeoutProposeOptimal(v.Value)
}
if err != nil {
return
}
}
return
}
// extractProposeTimeout
// @Description: extract the timeout based on value
// @receiver consensus
// @param value
// @return timeoutPropose
// @return err
func (consensus *ConsensusTBFTImpl) extractProposeTimeout(value string) (timeoutPropose time.Duration, err error) {
if timeoutPropose, err = time.ParseDuration(value); err != nil {
consensus.logger.Infof("[%s](%d/%d/%v) update chain config, TimeoutPropose: %v,"+
" TimeoutProposeDelta: %v,"+" parse TimeoutPropose error: %v",
consensus.Id, consensus.Height, consensus.Round, consensus.Step,
consensus.TimeoutPropose, consensus.TimeoutProposeDelta, err)
}
return
}
// extractProposeTimeoutDelta
// @Description: extract the delta timeout based on value
// @receiver consensus
// @param value
// @return timeoutProposeDelta
// @return err
func (consensus *ConsensusTBFTImpl) extractProposeTimeoutDelta(value string) (timeoutProposeDelta time.Duration,
err error) {
if timeoutProposeDelta, err = time.ParseDuration(value); err != nil {
consensus.logger.Infof("[%s](%d/%d/%v) update chain config, TimeoutPropose: %v,"+
" TimeoutProposeDelta: %v,"+" parse TimeoutProposeDelta error: %v",
consensus.Id, consensus.Height, consensus.Round, consensus.Step,
consensus.TimeoutPropose, consensus.TimeoutProposeDelta, err)
}
return
}
// extractBlocksPerProposer
// @Description: Calculate the number of extracted blocks for each proposer
// @receiver consensus
// @param value
// @return tbftBlocksPerProposer
// @return err
func (consensus *ConsensusTBFTImpl) extractBlocksPerProposer(value string) (tbftBlocksPerProposer uint64, err error) {
if tbftBlocksPerProposer, err = strconv.ParseUint(value, 10, 32); err != nil {
consensus.logger.Infof("[%s](%d/%d/%v) update chain config, parse BlocksPerProposer error: %v",
consensus.Id, consensus.Height, consensus.Round, consensus.Step, err)
return
}
if tbftBlocksPerProposer <= 0 {
err = fmt.Errorf("invalid TBFT_blocks_per_proposer: %d", tbftBlocksPerProposer)
return
}
return
}
// extract the timeout optimal based on value
func (consensus *ConsensusTBFTImpl) extractTimeoutProposeOptimal(value string) (timeoutProposeOptimal time.Duration,
err error) {
if timeoutProposeOptimal, err = time.ParseDuration(value); err != nil {
consensus.logger.Infof("[%s](%d/%d/%v) update chain config, timeoutProposeOptimal: %v,"+
" parse timeoutProposeOptimal error: %v",
consensus.Id, consensus.Height, consensus.Round, consensus.Step,
consensus.TimeoutProposeOptimal, err)
}
return
}
// extract the propose optimal based on value
func (consensus *ConsensusTBFTImpl) extractProposeOptimal(value string) (proposeOptimal bool, err error) {
if proposeOptimal, err = strconv.ParseBool(value); err != nil {
consensus.logger.Infof("[%s](%d/%d/%v) update chain config, parse ProposeOptimal error: %v",
consensus.Id, consensus.Height, consensus.Round, consensus.Step, err)
return
}
return
}
// handle
// @Description: Main methods of consensus process
// @receiver consensus
func (consensus *ConsensusTBFTImpl) handle() {
consensus.logger.Infof("[%s] handle start", consensus.Id)
defer consensus.logger.Infof("[%s] handle end", consensus.Id)
loop := true
for loop {
// fmt.Println("State_test:", consensus.ConsensusState.Step)
select {
case proposedBlock := <-consensus.proposedBlockC:
consensus.handleProposedBlock(proposedBlock)
case result := <-consensus.verifyResultC:
consensus.handleVerifyResult(result)
case height := <-consensus.blockHeightC:
consensus.handleBlockHeight(height)
case msg := <-consensus.externalMsgC:
// add consensus message to message pool
addMsgToPool(&consensus.messagePool, msg)
consensus.logger.Debugf("[%s] receive from externalMsgC %s", consensus.Id, msg.Type)
consensus.handleConsensusMsg(msg)
case msg := <-consensus.internalMsgC:
// add consensus message to message pool
addMsgToPool(&consensus.messagePool, msg)
consensus.logger.Debugf("[%s] receive from internalMsgC %s", consensus.Id, msg.Type)
consensus.handleConsensusMsg(msg)
case ti := <-consensus.timeScheduler.GetTimeoutC():
consensus.handleTimeout(ti)
case <-consensus.ProposeOptimalTimer.C:
consensus.handleProposeOptimalTimeout()
case <-consensus.closeC:
loop = false
}
}
}
// handleProposedBlock
// @Description: Process the proposed block
// @receiver consensus
// @param proposedBlock
func (consensus *ConsensusTBFTImpl) handleProposedBlock(proposedProposal *proposedProposal) {
consensus.Lock()
defer consensus.Unlock()
receiveBlockTime := CurrentTime()
// consensus not using the same block pointer with core, but internal content using the same pointer
block := CopyBlock(proposedProposal.proposedBlock.Block)
consensus.logger.Infof("[%s](%d/%d/%s) receive block from core engine (%d/%x), isProposer: %v",
consensus.Id, consensus.Height, consensus.Round, consensus.Step,
block.Header.BlockHeight, block.Header.BlockHash, consensus.isProposer(consensus.Height,
consensus.Round),
)
// process only blocks of current height
if block.Header.BlockHeight != consensus.Height {
consensus.logger.Warnf("[%s](%d/%d/%v) handle proposed block failed,"+
" receive block from invalid height: %d",
consensus.Id, consensus.Height, consensus.Round, consensus.Step, block.Header.BlockHeight)
return
}
// only process blocks for which you are the proposer
if !consensus.isProposer(consensus.Height, consensus.Round) {
consensus.logger.Warnf("[%s](%d/%d/%s) receive proposal from core engine (%d/%x), but isProposer: %v",
consensus.Id, consensus.Height, consensus.Round, consensus.Step,
block.Header.BlockHeight, block.Header.BlockHash, consensus.isProposer(consensus.Height, consensus.Round),
)
return
}
// continue processing only if you are in the proposal stage(Step_PROPOSE)
if consensus.Step != tbftpb.Step_PROPOSE {
consensus.logger.Warnf("[%s](%d/%d/%s) receive proposal from core engine (%d/%x), step error",
consensus.Id, consensus.Height, consensus.Round, consensus.Step,
block.Header.BlockHeight, block.Header.BlockHash,
)
return
}
// Tell the core engine that it is no longer a proposal node and does not propose blocks anymore
consensus.sendProposeState(false)
// Add extend handle consensus args into the block of consensus[DPoS], actually also add them to the block of core
if consensus.extendHandler != nil {
if err := consensus.extendHandler.CreateRWSet(block.Header.PreBlockHash, NewProposalBlock(block,
proposedProposal.proposedBlock.TxsRwSet)); err != nil {
consensus.logger.Errorf("[%s](%d/%d/%s) Create RWSets failed, reason: %s",
consensus.Id, consensus.Height, consensus.Round, consensus.Step, err)
return
}
}
// Add proposal
proposal := NewProposal(consensus.Id, consensus.Height, consensus.Round, -1, block)
// this is not a locked proposal
if proposedProposal.qc == nil {
// Add hash and signature to the block of consensus, actually also add them to the block of core
hash, sig, err := utils.SignBlock(consensus.chainConf.ChainConfig().Crypto.Hash, consensus.signer, block)
if err != nil {
consensus.logger.Errorf("[%s]sign block failed, %s", consensus.Id, err)
return
}
block.Header.BlockHash = hash[:]
block.Header.Signature = sig
} else {
// the locked proposal need txrwset and qc to send other nodes
proposal.TxsRwSet = proposedProposal.proposedBlock.TxsRwSet
proposal.Qc = proposedProposal.qc
}
signBlockTime := CurrentTime()
// proposal for cut block
if proposedProposal.proposedBlock.CutBlock != nil {
oriBlock := proposedProposal.proposedBlock.Block
proposal.Block = proposedProposal.proposedBlock.CutBlock
err := consensus.signProposal(proposal)
if err != nil {
consensus.logger.Errorf("sign proposal err %s", err)
return
}
consensus.Proposal = NewTBFTProposal(proposal, true)
proposal.Block = oriBlock
} else {
err := consensus.signProposal(proposal)
if err != nil {
consensus.logger.Errorf("sign proposal err %s", err)
return
}
consensus.Proposal = NewTBFTProposal(proposal, true)
}
// need txsRWSet to saved in wal
consensus.Proposal.PbMsg.TxsRwSet = proposedProposal.proposedBlock.TxsRwSet
signProposalTime := CurrentTime()
consensus.logger.Infof("[%s](%d/%d/%s) generated proposal (%d/%d/%x), "+
"time:[signBlock:%dms,signProposal:%dms,total:%dms]",
consensus.Id, consensus.Height, consensus.Round, consensus.Step,
proposal.Height, proposal.Round, proposal.Block.Header.BlockHash,
signBlockTime.Sub(receiveBlockTime).Milliseconds(), signProposalTime.Sub(signBlockTime).Milliseconds(),
signProposalTime.Sub(receiveBlockTime).Milliseconds())
// Broadcast proposal
// we have done mutate in sendConsensusProposal
consensus.sendConsensusProposal(consensus.Proposal, "")
// Enter the prevote stage
consensus.enterPrevote(consensus.Height, consensus.Round)
}
// handleVerifyResult
// @Description: Process validation results
// @receiver consensus
// @param verifyResult
func (consensus *ConsensusTBFTImpl) handleVerifyResult(verifyResult *consensuspb.VerifyResult) {
consensus.Lock()
defer consensus.Unlock()
receiveResTime := CurrentTime()
height := verifyResult.VerifiedBlock.Header.BlockHeight
hash := verifyResult.VerifiedBlock.Header.BlockHash
consensus.logger.Infof("[%s](%d/%d/%s) receive verify result (%d/%x) %v",
consensus.Id, consensus.Height, consensus.Round, consensus.Step,
height, hash, verifyResult.Code)
if consensus.VerifingProposal == nil {
consensus.logger.Warnf("[%s](%d/%d/%s) receive verify result failed, (%d/%x) %v",
consensus.Id, consensus.Height, consensus.Round, consensus.Step,
height, hash, verifyResult.Code,
)
return
}
if consensus.Height == height &&
consensus.Round == consensus.VerifingProposal.PbMsg.Round &&
verifyResult.Code == consensuspb.VerifyResult_FAIL {
consensus.logger.Warnf("[%s](%d/%d/%s) %x receive verify result (%d/%x) %v failed",
consensus.Id, consensus.Height, consensus.Round, consensus.Step,
consensus.VerifingProposal.PbMsg.Block.Header.BlockHash,
height, hash, verifyResult.Code,
)
consensus.VerifingProposal = nil
// inconsistent RwSet
if verifyResult.RwSetVerifyFailTxs != nil && len(verifyResult.RwSetVerifyFailTxs.TxIds) > 0 {
consensus.logger.Infof("handleVerifyResult failed , invalidTx = %v", verifyResult.RwSetVerifyFailTxs.TxIds)
consensus.invalidTxs = verifyResult.RwSetVerifyFailTxs.TxIds
// inconsistent RWSets enter prevote immediately
consensus.enterPrevote(consensus.Height, consensus.Round)
}
return
}
// if there are quorum pre_commit vote, then commit block
if bytes.Equal(consensus.VerifingProposal.PbMsg.Block.Header.BlockHash, hash) {
if consensus.heightRoundVoteSet != nil && consensus.heightRoundVoteSet.precommits(consensus.Round) != nil {
voteSet := consensus.heightRoundVoteSet.precommits(consensus.Round)
quorumHash, ok := voteSet.twoThirdsMajority()
//if ok && bytes.Compare(quorumHash, consensus.VerifingProposal.Block.Header.BlockHash) == 0 {
if ok && bytes.Equal(quorumHash, consensus.VerifingProposal.PbMsg.Block.Header.BlockHash) {
consensus.Proposal = consensus.VerifingProposal
// Commit block to core engine
consensus.commitBlock(consensus.Proposal.PbMsg.Block, voteSet.ToProto())
return
}
}
}
// maybe received multiple proposal, the last proposal verify succeed
// the previous invalid txs is no longer needed
consensus.invalidTxs = nil
if consensus.Step != tbftpb.Step_PROPOSE ||
!bytes.Equal(consensus.VerifingProposal.PbMsg.Block.Header.BlockHash, hash) {
consensus.logger.Warnf("[%s](%d/%d/%s) %x receive verify result (%d/%x) error",
consensus.Id, consensus.Height, consensus.Round, consensus.Step,
consensus.VerifingProposal.PbMsg.Block.Header.BlockHash,
height, hash,
)
consensus.VerifingProposal = nil
return
}
// [DPos]
if consensus.extendHandler != nil {
consensus.logger.Debugf("enter extend handle to verify consensus args ...")
if err := consensus.extendHandler.VerifyConsensusArgs(verifyResult.VerifiedBlock, verifyResult.TxsRwSet); err != nil {
consensus.logger.Warnf("verify block failed, reason: %s", err)
return
}
}
consensus.Proposal = consensus.VerifingProposal
consensus.Proposal.PbMsg.Block = verifyResult.VerifiedBlock
consensus.Proposal.PbMsg.TxsRwSet = verifyResult.TxsRwSet
endTime := CurrentTime()
consensus.logger.Infof("[%s](%d/%d/%s) processed verify result (%d/%x), time[verify:%dms]",
consensus.Id, consensus.Height, consensus.Round, consensus.Step, height, hash,
endTime.Sub(receiveResTime).Milliseconds())
// Prevote
consensus.enterPrevote(consensus.Height, consensus.Round)
}
// handleBlockHeight
// @Description: Process block height messages and enter new heights
// @receiver consensus
// @param height
func (consensus *ConsensusTBFTImpl) handleBlockHeight(height uint64) {
consensus.Lock()
defer consensus.Unlock()
consensus.logger.Infof("[%s](%d/%d/%s) receive block height %d",
consensus.Id, consensus.Height, consensus.Round, consensus.Step, height)
// Outdated block height event
if consensus.Height > height {
return
}
consensus.logger.Infof("[%s](%d/%d/%s) enterNewHeight because receiving block height %d",
consensus.Id, consensus.Height, consensus.Round, consensus.Step, height)
consensus.enterNewHeight(height + 1)
}
// procPropose
// @Description: Process proposal
// @receiver consensus
// @param proposal
func (consensus *ConsensusTBFTImpl) procPropose(proposal *tbftpb.Proposal) {
receiveProposalTime := CurrentTime()
if proposal == nil || proposal.Block == nil {
consensus.logger.Warnf("[%s](%d/%d/%s) receive invalid proposal because nil proposal",
consensus.Id, consensus.Height, consensus.Round, consensus.Step)
return
}
consensus.logger.Infof("[%s](%d/%d/%s) receive proposal from [%s], proposal(%d/%d/%x/%d)",
consensus.Id, consensus.Height, consensus.Round, consensus.Step,
proposal.Voter,
proposal.Height, proposal.Round, proposal.Block.Header.BlockHash, proto.Size(proposal.Block),
)
// add future proposal in cache
if consensus.Height < proposal.Height ||
(consensus.Height == proposal.Height && consensus.Round < proposal.Round) {
consensus.logger.Infof("[%s](%d/%d/%s) receive future proposal %s(%d/%d/%x)",
consensus.Id, consensus.Height, consensus.Round, consensus.Step,
proposal.Voter, proposal.Height, proposal.Round, proposal.Block.Header.BlockHash)
consensus.consensusFutureMsgCache.addFutureProposal(consensus.validatorSet, proposal)
return
}
height := proposal.Block.Header.BlockHeight