forked from PlatONnetwork/PlatON-Go
/
cbft.go
2156 lines (1833 loc) · 73.2 KB
/
cbft.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
// Package bft implements the BFT consensus engine.
package cbft
import (
"bytes"
"container/list"
"crypto/ecdsa"
"encoding/hex"
"encoding/json"
"errors"
"github.com/PlatONnetwork/PlatON-Go/common"
"github.com/PlatONnetwork/PlatON-Go/common/hexutil"
math2 "github.com/PlatONnetwork/PlatON-Go/common/math"
"github.com/PlatONnetwork/PlatON-Go/consensus"
"github.com/PlatONnetwork/PlatON-Go/core"
"github.com/PlatONnetwork/PlatON-Go/core/cbfttypes"
"github.com/PlatONnetwork/PlatON-Go/core/state"
"github.com/PlatONnetwork/PlatON-Go/core/types"
"github.com/PlatONnetwork/PlatON-Go/core/vm"
"github.com/PlatONnetwork/PlatON-Go/crypto"
"github.com/PlatONnetwork/PlatON-Go/log"
"github.com/PlatONnetwork/PlatON-Go/p2p/discover"
"github.com/PlatONnetwork/PlatON-Go/params"
"github.com/PlatONnetwork/PlatON-Go/rpc"
"math"
"math/big"
"sync"
"sync/atomic"
"time"
)
const (
former int32 = iota
current
next
all
)
var (
errSign = errors.New("sign error")
errUnauthorizedSigner = errors.New("unauthorized signer")
errIllegalBlock = errors.New("illegal block")
lateBlock = errors.New("block is late")
errDuplicatedBlock = errors.New("duplicated block")
errBlockNumber = errors.New("error block number")
errUnknownBlock = errors.New("unknown block")
errFutileBlock = errors.New("futile block")
errGenesisBlock = errors.New("cannot handle genesis block")
errHighestLogicalBlock = errors.New("cannot find a logical block")
errListConfirmedBlocks = errors.New("list confirmed blocks error")
errMissingSignature = errors.New("extra-data 65 byte signature suffix missing")
extraSeal = 65
windowSize = 10
//periodMargin is a percentum for period margin
periodMargin = uint64(20)
//maxPingLatency is the time in milliseconds between Ping and Pong
maxPingLatency = int64(5000)
//maxAvgLatency is the time in milliseconds between two peers
maxAvgLatency = int64(2000)
)
type Cbft struct {
config *params.CbftConfig
ppos *ppos
rotating *rotating
blockSignOutCh chan *cbfttypes.BlockSignature //a channel to send block signature
cbftResultOutCh chan *cbfttypes.CbftResult //a channel to send consensus result
highestLogicalBlockCh chan *types.Block
closeOnce sync.Once
exitCh chan struct{}
txPool *core.TxPool
blockExtMap sync.Map //map[common.Hash]*BlockExt //store all received blocks and signs
dataReceiveCh chan interface{} //a channel to receive data from miner
blockChain *core.BlockChain //the block chain
highestLogical atomic.Value //highest block in logical path, local packages new block will base on it
highestConfirmed atomic.Value //highest confirmed block in logical path
rootIrreversible atomic.Value //the latest block has stored in chain
//signedSet map[uint64]struct{} //all block numbers signed by local node
signedSet sync.Map
blockChainCache *core.BlockChainCache
netLatencyMap map[discover.NodeID]*list.List
netLatencyLock sync.RWMutex
}
func (cbft *Cbft) getRootIrreversible() *BlockExt {
v := cbft.rootIrreversible.Load()
if v == nil {
return nil
} else {
return v.(*BlockExt)
}
}
func (cbft *Cbft) getHighestConfirmed() *BlockExt {
v := cbft.highestConfirmed.Load()
if v == nil {
return nil
} else {
return v.(*BlockExt)
}
}
func (cbft *Cbft) getHighestLogical() *BlockExt {
v := cbft.highestLogical.Load()
if v == nil {
return nil
} else {
return v.(*BlockExt)
}
}
var cbft *Cbft
// New creates a concurrent BFT consensus engine
func New(config *params.CbftConfig, blockSignatureCh chan *cbfttypes.BlockSignature, cbftResultCh chan *cbfttypes.CbftResult, highestLogicalBlockCh chan *types.Block) *Cbft {
_ppos := newPpos(config)
cbft = &Cbft{
config: config,
ppos: _ppos,
rotating: newRotating(_ppos, config.Duration),
blockSignOutCh: blockSignatureCh,
cbftResultOutCh: cbftResultCh,
highestLogicalBlockCh: highestLogicalBlockCh,
exitCh: make(chan struct{}),
//blockExtMap: make(map[common.Hash]*BlockExt),
//signedSet: make(map[uint64]struct{}),
dataReceiveCh: make(chan interface{}, 256),
netLatencyMap: make(map[discover.NodeID]*list.List),
}
_ppos.ticketContext.SetChainInfo(cbft)
flowControl = NewFlowControl()
go cbft.dataReceiverLoop()
return cbft
}
// BlockExt is an extension from Block
type BlockExt struct {
block *types.Block `json:"-"`
inTree bool `json:"-"`
inTurn bool `json:"-"`
isExecuted bool `json:"-"`
isSigned bool `json:"-"`
isConfirmed bool `json:"-"`
Number uint64 `json:"number"`
Hash string `json:"hash"`
rcvTime int64
signs []*common.BlockConfirmSign `json:"-"`//all signs for block
parent *BlockExt
Children []*BlockExt `json:"children"`
}
func (ext *BlockExt) toJson() string {
jsons, errs := json.Marshal(ext)
if errs != nil {
log.Warn("can marshal BlockExt struct to json string", "number", ext.Number, "hash", ext.Hash)
return ""
}
return string(jsons)
}
// New creates a BlockExt object
func NewBlockExt(block *types.Block, blockNum uint64) *BlockExt {
return &BlockExt{
block: block,
Number: blockNum,
signs: make([]*common.BlockConfirmSign, 0),
Hash: block.Hash().TerminalString(),
}
}
func NewEmptyExt(blockNum uint64) *BlockExt {
return &BlockExt{
Number: blockNum,
signs: make([]*common.BlockConfirmSign, 0),
}
}
var flowControl *FlowControl
// FlowControl is a rectifier for sequential blocks
type FlowControl struct {
nodeID discover.NodeID
lastTime int64
maxInterval int64
minInterval int64
}
func NewFlowControl() *FlowControl {
return &FlowControl{
nodeID: discover.NodeID{},
maxInterval: int64(cbft.config.Period*1000 + cbft.config.Period*1000*periodMargin/100),
minInterval: int64(cbft.config.Period*1000 - cbft.config.Period*1000*periodMargin/100),
}
}
// control checks if the block is received at a proper rate
func (flowControl *FlowControl) control(nodeID discover.NodeID, rcvTime int64) bool {
passed := false
if flowControl.nodeID == nodeID {
differ := rcvTime - flowControl.lastTime
if differ >= flowControl.minInterval && differ <= flowControl.maxInterval {
passed = true
} else {
passed = false
}
} else {
passed = true
}
flowControl.nodeID = nodeID
flowControl.lastTime = rcvTime
return passed
}
// findBlockExt finds BlockExt in cbft.blockExtMap
func (cbft *Cbft) findBlockExt(hash common.Hash) *BlockExt {
if v, ok := cbft.blockExtMap.Load(hash); ok {
return v.(*BlockExt)
}
return nil
}
//collectSign collects all signs for a block
func (cbft *Cbft) collectSign(ext *BlockExt, sign *common.BlockConfirmSign) {
if sign != nil {
ext.signs = append(ext.signs, sign)
blockNumber := big.NewInt((int64(ext.Number)))
parentNumber := new(big.Int).Sub(blockNumber, common.Big1)
//if ext.isLinked && ext.block != nil {
if ext.inTree { // ext.block != nil is unnecessary
if len(ext.signs) >= cbft.getThreshold(parentNumber, ext.block.ParentHash(), blockNumber) {
ext.isConfirmed = true
}
}
}
}
// isParent checks if a block is another's parent
func (parent *BlockExt) isParent(child *types.Block) bool {
if parent.block != nil && parent.block.NumberU64()+1 == child.NumberU64() && parent.block.Hash() == child.ParentHash() {
return true
}
return false
}
// findParent finds ext's parent with non-nil block
func (cbft *Cbft) findParent(ext *BlockExt) *BlockExt {
if ext.block == nil {
return nil
}
parent := cbft.findBlockExt(ext.block.ParentHash())
if parent != nil {
if parent.block == nil {
log.Warn("parent block has not received")
} else if parent.block.NumberU64()+1 == ext.block.NumberU64() {
return parent
} else {
log.Warn("data error, parent block hash is not mapping to number")
}
}
return nil
}
// collectTxs collects exts's transactions
func (cbft *Cbft) collectTxs(exts []*BlockExt) types.Transactions {
txs := make([]*types.Transaction, 0)
for _, ext := range exts {
copy(txs, ext.block.Transactions())
}
return types.Transactions(txs)
}
// findChildren finds current blockExt's all children with non-nil block
func (cbft *Cbft) findChildren(parent *BlockExt) []*BlockExt {
if parent.block == nil {
return nil
}
children := make([]*BlockExt, 0)
f := func(k, v interface{}) bool {
// The input and input types of this function are fixed and cannot be modified.
// You can write your own code in the body of the function, call k, v in the map
child := v.(*BlockExt)
if child.block != nil && child.block.ParentHash() == parent.block.Hash() {
if child.block.NumberU64()-1 == parent.block.NumberU64() {
children = append(children, child)
} else {
log.Warn("data error, child block hash is not mapping to number")
}
}
return true
}
cbft.blockExtMap.Range(f)
if len(children) == 0 {
return nil
} else {
return children
}
}
// saveBlockExt saves block in memory
func (cbft *Cbft) saveBlockExt(hash common.Hash, ext *BlockExt) {
cbft.blockExtMap.Store(hash, ext)
length := 0
cbft.blockExtMap.Range(func(_, _ interface{}) bool {
length++
return true
})
log.Debug("save block in memory", "hash", hash, "number", ext.Number, "totalBlocks", length)
}
// isAncestor checks if a block is another's ancestor
func (lower *BlockExt) isAncestor(higher *BlockExt) bool {
if higher == nil || higher.block == nil || lower == nil || lower.block == nil {
return false
}
generations := higher.block.NumberU64() - lower.block.NumberU64()
if generations <= 0 {
return false
}
for i := uint64(0); i < generations; i++ {
parent := higher.parent
if parent != nil {
higher = parent
} else {
return false
}
}
if lower.block.Hash() == higher.block.Hash() && lower.block.NumberU64() == higher.block.NumberU64() {
return true
}
return false
}
// findHighest finds the highest block from current start; If there are multiple highest blockExts, returns the one that singed by self; if none of blocks signed by self, returns the one that has most signs
func (cbft *Cbft) findHighest(current *BlockExt) *BlockExt {
highest := current
for _, child := range current.Children {
current := cbft.findHighest(child)
if current.block.NumberU64() > highest.block.NumberU64() || (current.block.NumberU64() == highest.block.NumberU64() && (current.isSigned || len(current.signs) > len(highest.signs))) {
highest = current
}
}
return highest
}
// findHighestLogical finds a logical path and return the highest block.
// the precondition is cur is a logical block, so, findHighestLogical will return cur if the path only has one block.
func (cbft *Cbft) findHighestLogical(cur *BlockExt) *BlockExt {
lastClosestConfirmed := cbft.findLastClosestConfirmedIncludingSelf(cur)
if lastClosestConfirmed == nil {
return cbft.findHighest(cur)
} else {
return cbft.findHighest(lastClosestConfirmed)
}
}
// findLastClosestConfirmedIncludingSelf return the last found block by call findClosestConfirmedExcludingSelf in a circular manner
func (cbft *Cbft) findLastClosestConfirmedIncludingSelf(cur *BlockExt) *BlockExt {
log.Debug("findLastClosestConfirmedIncludingSelf", "cur.number", cur.Number, "cur.hash", cur.Hash, "cur.isConfirmed", cur.isConfirmed)
var lastClosestConfirmed *BlockExt
for {
lastClosestConfirmed = cbft.findClosestConfirmedExcludingSelf(cur)
if lastClosestConfirmed == nil || lastClosestConfirmed.block.Hash() == cur.block.Hash() {
break
} else {
//fmt.Printf("lastClosestConfirmed, number=%d, rcvTime=%d\r\n", lastClosestConfirmed.Number, lastClosestConfirmed.rcvTime)
cur = lastClosestConfirmed
}
}
if lastClosestConfirmed != nil {
return lastClosestConfirmed
} else if cur.isConfirmed {
return cur
} else {
log.Debug("findLastClosestConfirmedIncludingSelf return nil", "cur.number", cur.Number, "cur.hash", cur.Hash, "cur.isConfirmed", cur.isConfirmed)
return nil
}
}
// findClosestConfirmedIncludingSelf returns the closest confirmed block in current's descendant (including current itself).
// return nil if there's no confirmed in current's descendant.
func (cbft *Cbft) findClosestConfirmedIncludingSelf(current *BlockExt) *BlockExt {
closest := current
if current.inTree && current.isExecuted && !current.isConfirmed {
closest = nil
}
for _, child := range current.Children {
temp := cbft.findClosestConfirmedIncludingSelf(child)
if closest == nil || (temp != nil && temp.inTree && temp.isExecuted && temp.isConfirmed && temp.Number < closest.Number) {
closest = temp
}
}
return closest
}
// findClosestConfirmedExcludingSelf returns the closest confirmed block in current's descendant (excluding current itself).
// return nil if there's no confirmed in current's descendant.
func (cbft *Cbft) findClosestConfirmedExcludingSelf(current *BlockExt) *BlockExt {
var closest *BlockExt
for _, child := range current.Children {
if child != nil && child.inTree && child.isExecuted && child.isConfirmed {
return child
} else {
temp := cbft.findClosestConfirmedIncludingSelf(child)
if closest == nil || (temp != nil && temp.Number < closest.Number) {
closest = temp
}
}
}
return closest
}
// signLogicalAndDescendant signs logical block go along the logical path from current block, and will not sign the block if there's another same number block has been signed.
func (cbft *Cbft) signLogicalAndDescendant(current *BlockExt) {
log.Debug("sign logical block and its descendant", "hash", current.block.Hash(), "number", current.block.NumberU64())
highestLogical := cbft.findHighestLogical(current)
logicalBlocks := cbft.backTrackBlocks(highestLogical, current, true)
//var highestConfirmed *BlockExt
for _, logical := range logicalBlocks {
if logical.inTurn && !logical.isSigned {
//if _, signed := cbft.signedSet[logical.block.NumberU64()]; !signed {
if _, signed := cbft.signedSet.Load(logical.block.NumberU64()); !signed {
cbft.sign(logical)
log.Debug("reset TxPool after block signed", "hash", logical.block.Hash(), "number", logical.Number)
cbft.txPool.Reset(logical.block)
}
}
}
}
func (cbft *Cbft) signLogicalAndDescendantMock(current *BlockExt) {
highestLogical := cbft.findHighestLogical(current)
logicalBlocks := cbft.backTrackBlocks(highestLogical, current, true)
for _, logical := range logicalBlocks {
if logical.inTurn && !logical.isSigned {
if _, signed := cbft.signedSet.Load(logical.block.NumberU64()); !signed {
cbft.signMock(logical)
}
}
}
}
// executeBlockAndDescendant executes the block's transactions and its descendant
func (cbft *Cbft) executeBlockAndDescendant(current *BlockExt, parent *BlockExt) error {
if !current.isExecuted {
if err := cbft.execute(current, parent); err != nil {
current.inTree = false
current.isExecuted = false
//remove bad block from tree and map
cbft.removeBadBlock(current)
//log.Error("execute block error", "hash", current.block.Hash(), "number", current.block.NumberU64())
return err
} else {
current.inTree = true
current.isExecuted = true
}
}
for _, child := range current.Children {
if err := cbft.executeBlockAndDescendant(child, current); err != nil {
//remove bad block from tree and map
cbft.removeBadBlock(child)
return err
}
}
return nil
}
func (cbft *Cbft) executeBlockAndDescendantMock(current *BlockExt, parent *BlockExt) error {
if !current.isExecuted {
current.inTree = true
current.isExecuted = true
}
for _, child := range current.Children {
if err := cbft.executeBlockAndDescendantMock(child, current); err != nil {
//remove bad block from tree and map
cbft.removeBadBlock(child)
return err
}
}
return nil
}
// sign signs a block
func (cbft *Cbft) sign(ext *BlockExt) {
sealHash := ext.block.Header().SealHash()
if signature, err := cbft.signFn(sealHash.Bytes()); err == nil {
log.Debug("Sign block ", "hash", ext.block.Hash(), "number", ext.block.NumberU64(), "sealHash", sealHash, "signature", hexutil.Encode(signature[:8]))
sign := common.NewBlockConfirmSign(signature)
ext.isSigned = true
cbft.collectSign(ext, sign)
//save this block number
//cbft.signedSet[ext.block.NumberU64()] = struct{}{}
cbft.signedSet.Store(ext.block.NumberU64(), struct{}{})
blockHash := ext.block.Hash()
//send the BlockSignature to channel
blockSign := &cbfttypes.BlockSignature{
SignHash: sealHash,
Hash: blockHash,
Number: ext.block.Number(),
Signature: sign,
ParentHash: ext.block.ParentHash(),
}
cbft.blockSignOutCh <- blockSign
} else {
panic("sign block fatal error")
}
}
func (cbft *Cbft) signMock(ext *BlockExt) {
sealHash := ext.block.Header().SealHash()
if signature, err := cbft.signFn(sealHash.Bytes()); err == nil {
sign := common.NewBlockConfirmSign(signature)
ext.isSigned = true
cbft.collectSign(ext, sign)
//save this block number
//cbft.signedSet[ext.block.NumberU64()] = struct{}{}
cbft.signedSet.Store(ext.block.NumberU64(), struct{}{})
} else {
panic("sign block fatal error")
}
}
// execute executes the block's transactions based on its parent
// if success then save the receipts and state to consensusCache
func (cbft *Cbft) execute(ext *BlockExt, parent *BlockExt) error {
log.Debug("execute block", "hash", ext.block.Hash(), "number", ext.block.NumberU64(), "ParentHash", parent.block.Hash())
state, err := cbft.blockChainCache.MakeStateDB(parent.block)
if err != nil {
log.Error("execute block error, cannot make state based on parent", "hash", ext.block.Hash(), "Number", ext.block.NumberU64(), "ParentHash", parent.block.Hash(), "err", err)
return errors.New("execute block error")
}
//to execute
blockInterval := new(big.Int).Sub(ext.block.Number(), cbft.blockChain.CurrentBlock().Number())
receipts, err := cbft.blockChain.ProcessDirectly(ext.block, state, parent.block, blockInterval)
if err == nil {
//save the receipts and state to consensusCache
stateIsNil := state == nil
log.Debug("execute block success", "hash", ext.block.Hash(), "number", ext.block.NumberU64(), "ParentHash", parent.block.Hash(), "lenReceipts", len(receipts), "stateIsNil", stateIsNil, "root", ext.block.Root())
sealHash := ext.block.Header().SealHash()
cbft.blockChainCache.WriteReceipts(sealHash, receipts, ext.block.NumberU64())
cbft.blockChainCache.WriteStateDB(sealHash, state, ext.block.NumberU64())
//cbft.blockChainCache.MarkBlockHash(ext.block.Hash())
} else {
log.Error("execute block error", "hash", ext.block.Hash(), "number", ext.block.NumberU64(), "ParentHash", parent.block.Hash(), "err", err)
return errors.New("execute block error")
}
return nil
}
// backTrackBlocks return blocks from start to end, these blocks are in a same tree branch.
// The result is sorted by block number from lower to higher.
func (cbft *Cbft) backTrackBlocks(start *BlockExt, end *BlockExt, includeEnd bool) []*BlockExt {
log.Trace("back track blocks", "startHash", start.block.Hash(), "startParentHash", end.block.ParentHash(), "endHash", start.block.Hash())
result := make([]*BlockExt, 0)
if start.block.Hash() == end.block.Hash() && includeEnd {
result = append(result, start)
} else if start.block.NumberU64() > end.block.NumberU64() {
found := false
result = append(result, start)
for {
parent := start.parent
if parent == nil {
break
} else if parent.block.Hash() == end.block.Hash() && parent.block.NumberU64() == end.block.NumberU64() {
//log.Debug("ending of back track block ")
if includeEnd {
result = append(result, parent)
}
found = true
break
} else {
//log.Debug("found new block", "hash", parent.block.Hash(), "ParentHash", parent.block.ParentHash(), "number", parent.block.NumberU64())
result = append(result, parent)
start = parent
}
}
if found {
//sorted by block number from lower to higher
if len(result) > 1 {
reverse(result)
}
} else {
result = nil
}
}
return result
}
func reverse(s []*BlockExt) {
for i, j := 0, len(s)-1; i < j; i, j = i+1, j-1 {
s[i], s[j] = s[j], s[i]
}
}
// SetPrivateKey sets local's private key by the backend.go
func (cbft *Cbft) SetPrivateKey(privateKey *ecdsa.PrivateKey) {
cbft.config.PrivateKey = privateKey
cbft.config.NodeID = discover.PubkeyID(&privateKey.PublicKey)
}
func SetBlockChainCache(blockChainCache *core.BlockChainCache) {
cbft.blockChainCache = blockChainCache
}
// setHighestLogical sets highest logical block and send it to the highestLogicalBlockCh
func (cbft *Cbft) setHighestLogical(highestLogical *BlockExt) {
cbft.highestLogical.Store(highestLogical)
cbft.highestLogicalBlockCh <- highestLogical.block
}
// SetBackend sets blockChain and txPool into cbft
func SetBackend(blockChain *core.BlockChain, txPool *core.TxPool) {
log.Debug("call SetBackend()")
cbft.blockChain = blockChain
cbft.ppos.SetStartTimeOfEpoch(blockChain.Genesis().Time().Int64() / 1000)
cbft.ppos.ticketContext.SetChainConfig(blockChain.Config())
currentBlock := blockChain.CurrentBlock()
genesisParentHash := bytes.Repeat([]byte{0x00}, 32)
if bytes.Equal(currentBlock.ParentHash().Bytes(), genesisParentHash) && currentBlock.Number() == nil {
currentBlock.Header().Number = big.NewInt(0)
}
log.Debug("init cbft.highestLogicalBlock", "hash", currentBlock.Hash(), "number", currentBlock.NumberU64())
current := NewBlockExt(currentBlock, currentBlock.NumberU64())
current.inTree = true
current.isExecuted = true
current.isSigned = true
current.isConfirmed = true
current.Number = currentBlock.NumberU64()
cbft.saveBlockExt(currentBlock.Hash(), current)
cbft.highestConfirmed.Store(current)
//cbft.highestLogical = current
cbft.setHighestLogical(current)
cbft.rootIrreversible.Store(current)
cbft.txPool = txPool
}
func SetPposOption(blockChain *core.BlockChain) {
cbft.ppos.setPPOS_Temp()
cbft.ppos.SetCandidateContextOption(blockChain, cbft.config.InitialNodes)
}
// BlockSynchronisation reset the cbft env, such as cbft.highestLogical, cbft.highestConfirmed.
// This function is invoked after that local has synced new blocks from other node.
func (cbft *Cbft) OnBlockSynced() {
log.Debug("call OnBlockSynced()", "cbft.dataReceiveCh.len", len(cbft.dataReceiveCh))
cbft.dataReceiveCh <- &cbfttypes.BlockSynced{}
}
func (cbft *Cbft) blockSynced() {
currentBlock := cbft.blockChain.CurrentBlock()
log.Debug("=== call blockSynced() ===",
"highestLogicalHash", cbft.getHighestLogical().block.Hash(),
"highestLogicalNumber", cbft.getHighestLogical().Number,
"highestConfirmedHash", cbft.getHighestConfirmed().block.Hash(),
"highestConfirmedNumber", cbft.getHighestConfirmed().Number,
"rootIrreversibleHash", cbft.getRootIrreversible().block.Hash(),
"rootIrreversibleNumber", cbft.getRootIrreversible().Number,
"number", currentBlock.Number(),
"hash", currentBlock.Hash())
if currentBlock.NumberU64() > cbft.getRootIrreversible().Number {
log.Debug("chain has a higher irreversible block", "hash", currentBlock.Hash(), "number", currentBlock.NumberU64())
newRoot := cbft.findBlockExt(currentBlock.Hash())
if newRoot == nil || newRoot.block == nil {
log.Debug("higher irreversible block is not existing in memory", "newTree", newRoot.toJson())
//the block synced from other peer is a new block in local peer
//remove all blocks referenced in old tree after being cut off
cbft.cleanByTailoredTree(cbft.getRootIrreversible())
newRoot = NewBlockExt(currentBlock, currentBlock.NumberU64())
newRoot.inTree = true
newRoot.isExecuted = true
newRoot.isSigned = true
newRoot.isConfirmed = true
newRoot.Number = currentBlock.NumberU64()
newRoot.parent = nil
cbft.saveBlockExt(newRoot.block.Hash(), newRoot)
//only need to build up child
cbft.buildChildNode(newRoot)
if len(newRoot.Children) > 0{
//the new root's children should re-execute base on new state
for _, child := range newRoot.Children {
if err := cbft.executeBlockAndDescendant(child, newRoot); err != nil {
log.Error("execute the block error", "err", err)
break
}
}
//there are some redundancy code for newRoot, but these codes are necessary for other logical blocks
cbft.signLogicalAndDescendant(newRoot)
}
} else if newRoot.block != nil {
log.Debug("higher irreversible block is existing in memory","newTree", newRoot.toJson())
//the block synced from other peer exists in local peer
newRoot.isExecuted = true
newRoot.isSigned = true
newRoot.isConfirmed = true
newRoot.Number = currentBlock.NumberU64()
if newRoot.inTree == false {
newRoot.inTree = true
cbft.setDescendantInTree(newRoot)
if len(newRoot.Children) > 0{
//the new root's children should re-execute base on new state
for _, child := range newRoot.Children {
if err := cbft.executeBlockAndDescendant(child, newRoot); err != nil {
log.Error("execute the block error", "err", err)
break
}
}
//there are some redundancy code for newRoot, but these codes are necessary for other logical blocks
cbft.signLogicalAndDescendant(newRoot)
}
}else{
//cut off old tree from new root,
tailorTree(newRoot)
}
//remove all blocks referenced in old tree after been cut off
cbft.cleanByTailoredTree(cbft.getRootIrreversible())
}
//remove all other blocks those their numbers are too low
cbft.cleanByNumber(newRoot.Number)
log.Debug("the cleared new tree in memory", "json", newRoot.toJson())
//reset the new root irreversible
cbft.rootIrreversible.Store(newRoot)
log.Debug("reset the new root irreversible by synced", "hash", newRoot.block.Hash(), "number", newRoot.block.NumberU64())
//reset highest confirmed block
highestConfirmed :=cbft.findLastClosestConfirmedIncludingSelf(newRoot)
cbft.highestConfirmed.Store(highestConfirmed)
if cbft.getHighestConfirmed() != nil {
log.Debug("reset the highestConfirmed by synced successful", "hash", highestConfirmed.block.Hash(), "number", highestConfirmed.block.NumberU64())
//reset logical path
highestLogical := cbft.findHighest(highestConfirmed)
cbft.setHighestLogical(highestLogical)
log.Debug("reset the highestLogical by synced", "hash", highestLogical.block.Hash(), "number", highestLogical.block.NumberU64(), "newRoot.hash", newRoot.block.Hash(), "newRoot.number", newRoot.block.NumberU64() )
if !cbft.flushReadyBlock() {
//remove all other blocks those their numbers are too low
cbft.cleanByNumber(cbft.getRootIrreversible().Number)
}
log.Debug("reset TxPool after block synced", "hash", currentBlock.Hash(), "number", currentBlock.NumberU64())
cbft.txPool.Reset(currentBlock)
} else {
log.Debug("reset the highestConfirmed by synced failure because findLastClosestConfirmedIncludingSelf() returned nil", "newRoot.hash", newRoot.block.Hash(), "newRoot.number", newRoot.block.NumberU64())
//cbft.highestConfirmed.Store(newRoot)
}
}
log.Debug("=== end of blockSynced() ===",
"highestLogicalHash", cbft.getHighestLogical().block.Hash(),
"highestLogicalNumber", cbft.getHighestLogical().Number,
"highestConfirmedHash", cbft.getHighestConfirmed().block.Hash(),
"highestConfirmedNumber", cbft.getHighestConfirmed().Number,
"rootIrreversibleHash", cbft.getRootIrreversible().block.Hash(),
"rootIrreversibleNumber", cbft.getRootIrreversible().Number,
"number", currentBlock.Number(),
"hash", currentBlock.Hash())
}
// dataReceiverLoop is the main loop that handle the data from worker, or eth protocol's handler
// the new blocks packed by local in worker will be handled here; the other blocks and signs received by P2P will be handled here.
func (cbft *Cbft) dataReceiverLoop() {
for {
select {
case v := <-cbft.dataReceiveCh:
sign, ok := v.(*cbfttypes.BlockSignature)
if ok {
err := cbft.signReceiver(sign)
if err != nil {
log.Error("Error", "msg", err)
}
} else {
blockExt, ok := v.(*BlockExt)
if ok {
err := cbft.blockReceiver(blockExt)
if err != nil {
log.Error("Error", "msg", err)
}
} else {
_, ok := v.(*cbfttypes.BlockSynced)
if ok {
cbft.blockSynced()
} else {
log.Error("Received wrong data type")
}
}
}
case <-cbft.exitCh:
log.Debug("consensus engine exit")
return
}
}
}
// buildIntoTree inserts current BlockExt to the tree structure
func (cbft *Cbft) buildIntoTree(current *BlockExt) {
parent := cbft.findParent(current)
if parent != nil {
//catch up with parent
parent.Children = append(parent.Children, current)
current.parent = parent
current.inTree = parent.inTree
} else {
log.Warn("cannot find parent block", "hash", current.block.Hash(), "number", current.block.NumberU64())
}
cbft.buildChildNode(current)
}
func (cbft *Cbft) buildChildNode(current *BlockExt) {
children := cbft.findChildren(current)
if len(children) > 0 {
current.Children = children
for _, child := range children {
//child should catch up with current
child.parent = current
}
cbft.setDescendantInTree(current)
}
}
func (cbft *Cbft) setDescendantInTree(child *BlockExt) {
log.Debug("set descendant inTree attribute", "hash", child.block.Hash(), "number", child.Number)
for _, grandchild := range child.Children {
grandchild.inTree = child.inTree
cbft.setDescendantInTree(grandchild)
}
}
// removeBadBlock removes bad block executed error from the tree structure and cbft.blockExtMap.
func (cbft *Cbft) removeBadBlock(badBlock *BlockExt) {
tailorTree(badBlock)
cbft.removeByTailored(badBlock)
/*for _, child := range badBlock.children {
child.parent = nil
}
cbft.blockExtMap.Delete(badBlock.block.Hash())*/
//delete(cbft.blockExtMap, badBlock.block.Hash())
}
func (cbft *Cbft) removeByTailored(badBlock *BlockExt) {
if len(badBlock.Children) > 0 {
for _, child := range badBlock.Children {
cbft.removeByTailored(child)
cbft.blockExtMap.Delete(child.block.Hash())
}
} else {
cbft.blockExtMap.Delete(badBlock.block.Hash())
}
}
// signReceiver handles the received block signature
func (cbft *Cbft) signReceiver(sig *cbfttypes.BlockSignature) error {
log.Debug("=== call signReceiver() ===",
"hash", sig.Hash,
"number", sig.Number.Uint64(),
"highestLogicalHash", cbft.getHighestLogical().block.Hash(),
"highestLogicalNumber", cbft.getHighestLogical().Number,
"highestConfirmedHash", cbft.getHighestConfirmed().block.Hash(),
"highestConfirmedNumber", cbft.getHighestConfirmed().Number,
"rootIrreversibleHash", cbft.getRootIrreversible().block.Hash(),
"rootIrreversibleNumber", cbft.getRootIrreversible().Number)
if sig.Number.Uint64() <= cbft.getRootIrreversible().Number {
log.Warn("block sign is too late")
return nil
}
current := cbft.findBlockExt(sig.Hash)
if current == nil {
log.Warn("have not received the corresponding block")
//the block is nil
current = NewEmptyExt(sig.Number.Uint64())
current.inTree = false
current.isExecuted = false
current.isSigned = false
current.isConfirmed = false
cbft.saveBlockExt(sig.Hash, current)
}
cbft.collectSign(current, sig.Signature)
var hashLog interface{}
if current.block != nil {
hashLog = current.block.Hash()
} else {
hashLog = "sign received before block,"
}
log.Debug("count signatures",
"hash", hashLog,
"number", current.Number,
"signCount", len(current.signs),
"inTree", current.inTree,
"isExecuted", current.isExecuted,
"isConfirmed", current.isConfirmed,
"isSigned", current.isSigned)
if current.inTree && current.isConfirmed && cbft.getRootIrreversible().isAncestor(current){
//the current is new highestConfirmed on the same logical path
if current.Number > cbft.getHighestConfirmed().Number && cbft.getHighestConfirmed().isAncestor(current) {
cbft.highestConfirmed.Store(current)
newHighestLogical := cbft.findHighestLogical(current)
cbft.setHighestLogical(newHighestLogical)
} else if current.Number < cbft.getHighestConfirmed().Number && !current.isAncestor(cbft.getHighestConfirmed()) {
//only this case may cause a new fork
cbft.checkFork(current)
}
cbft.flushReadyBlock()
}
log.Debug("=== end of signReceiver() ===",
"hash", hashLog,
"number", current.Number,
"highestLogicalHash", cbft.getHighestLogical().block.Hash(),
"highestLogicalNumber", cbft.getHighestLogical().Number,
"highestConfirmedHash", cbft.getHighestConfirmed().block.Hash(),
"highestConfirmedNumber", cbft.getHighestConfirmed().Number,
"rootIrreversibleHash", cbft.getRootIrreversible().block.Hash(),
"rootIrreversibleNumber", cbft.getRootIrreversible().Number)
return nil
}
//blockReceiver handles the new block
func (cbft *Cbft) blockReceiver(tmp *BlockExt) error {
block := tmp.block
rcvTime := tmp.rcvTime
log.Debug("=== call blockReceiver() ===",
"hash", block.Hash(),
"number", block.NumberU64(),
"parentHash", block.ParentHash(),
"ReceiptHash", block.ReceiptHash(),
"highestLogicalHash", cbft.getHighestLogical().block.Hash(),
"highestLogicalNumber", cbft.getHighestLogical().Number,
"highestConfirmedHash", cbft.getHighestConfirmed().block.Hash(),
"highestConfirmedNumber", cbft.getHighestConfirmed().Number,
"rootIrreversibleHash", cbft.getRootIrreversible().block.Hash(),
"rootIrreversibleNumber", cbft.getRootIrreversible().Number)