7 "github.com/golang/groupcache/lru"
8 log "github.com/sirupsen/logrus"
10 "github.com/vapor/crypto/ed25519"
11 "github.com/vapor/crypto/ed25519/chainkd"
12 "github.com/vapor/errors"
13 "github.com/vapor/event"
14 "github.com/vapor/protocol/bc"
15 "github.com/vapor/protocol/bc/types"
16 "github.com/vapor/protocol/state"
20 maxSignatureCacheSize = 10000
24 errVotingOperationOverFlow = errors.New("voting operation result overflow")
25 errDoubleSignBlock = errors.New("the consensus is double sign in same height of different block")
26 errInvalidSignature = errors.New("the signature of block is invalid")
30 consensusNodeManager *consensusNodeManager
31 orphanManage *OrphanManage
32 signatureCache *lru.Cache
33 eventDispatcher *event.Dispatcher
36 func newBbft(store Store, blockIndex *state.BlockIndex, orphanManage *OrphanManage, eventDispatcher *event.Dispatcher) *bbft {
38 orphanManage: orphanManage,
39 consensusNodeManager: newConsensusNodeManager(store, blockIndex),
40 signatureCache: lru.New(maxSignatureCacheSize),
41 eventDispatcher: eventDispatcher,
45 // IsConsensusPubkey determine whether a public key is a consensus node at a specified height
46 func (b *bbft) IsConsensusPubkey(blockHash *bc.Hash, pubkey []byte) (bool, error) {
47 node, err := b.consensusNodeManager.getConsensusNode(blockHash, hex.EncodeToString(pubkey))
48 if err != nil && err != errNotFoundConsensusNode {
51 return node != nil, nil
54 func (b *bbft) isIrreversible(block *types.Block) bool {
55 signNum, err := b.validateSign(block)
60 return signNum > (numOfConsensusNode * 2 / 3)
63 // NextLeaderTime returns the start time of the specified public key as the next leader node
64 func (b *bbft) NextLeaderTimeRange(pubkey []byte, bestBlockHash *bc.Hash) (uint64, uint64, error) {
65 return b.consensusNodeManager.nextLeaderTimeRange(pubkey, bestBlockHash)
68 func (b *bbft) ApplyBlock(voteResultMap map[uint64]*state.VoteResult, block *types.Block) (err error) {
69 return b.consensusNodeManager.applyBlock(voteResultMap, block)
72 func (b *bbft) DetachBlock(voteResultMap map[uint64]*state.VoteResult, block *types.Block) error {
73 return b.consensusNodeManager.detachBlock(voteResultMap, block)
76 // ProcessBlockSignature process the received block signature messages
77 // return once a block become irreversible, whether it's height greater than best block height
78 // if so, the chain module must update status
79 func (b *bbft) ProcessBlockSignature(signature, pubkey []byte, blockHeight uint64, blockHash *bc.Hash) (bool, error) {
80 consensusNode, err := b.consensusNodeManager.getConsensusNode(blockHash, hex.EncodeToString(pubkey))
85 if !ed25519.Verify(ed25519.PublicKey(pubkey), blockHash.Bytes(), signature) {
86 return false, errInvalidSignature
89 isDoubleSign, err := b.checkDoubleSign(consensusNode.order, blockHeight, *blockHash)
95 log.WithFields(log.Fields{"module": logModule, "blockHash": blockHash.String(), "pubkey": pubkey}).Warn("the consensus node double sign the same height of different block")
96 return false, errDoubleSignBlock
99 orphanBlock, ok := b.orphanManage.Get(blockHash)
101 orphanBlock.Witness[consensusNode.order] = signature
105 block, err := b.consensusNodeManager.store.GetBlock(blockHash)
107 // block is not exist, save the signature
108 key := fmt.Sprintf("%s:%s", blockHash.String(), hex.EncodeToString(pubkey))
109 b.signatureCache.Add(key, signature)
113 if err := b.updateBlockSignature(block, consensusNode.order, signature); err != nil {
117 return b.isIrreversible(block) && blockHeight > b.consensusNodeManager.blockIndex.BestNode().Height, nil
120 // ValidateBlock verify whether the block is valid
121 func (b *bbft) ValidateBlock(block *types.Block) error {
122 signNum, err := b.validateSign(block)
128 return errors.New("no valid signature")
133 // validateSign verify the signatures of block, and return the number of correct signature
134 // if some signature is invalid, they will be reset to nil
135 // if the block has not the signature of blocker, it will return error
136 func (b *bbft) validateSign(block *types.Block) (uint64, error) {
137 var correctSignNum uint64
138 blockHash := block.Hash()
139 consensusNodeMap, err := b.consensusNodeManager.getConsensusNodesByVoteResult(&blockHash)
144 hasBlockerSign := false
145 for pubkey, node := range consensusNodeMap {
146 if len(block.Witness) <= int(node.order) {
150 blockHash := block.Hash()
151 if block.Witness[node.order] == nil {
152 key := fmt.Sprintf("%s:%s", blockHash.String(), pubkey)
153 signature, ok := b.signatureCache.Get(key)
155 block.Witness[node.order] = signature.([]byte)
159 if ed25519.Verify(ed25519.PublicKey(pubkey), blockHash.Bytes(), block.Witness[node.order]) {
160 isDoubleSign, err := b.checkDoubleSign(node.order, block.Height, block.Hash())
166 log.WithFields(log.Fields{"module": logModule, "blockHash": blockHash.String(), "pubkey": pubkey}).Warn("the consensus node double sign the same height of different block")
167 // Consensus node is signed twice with the same block height, discard the signature
168 block.Witness[node.order] = nil
171 isBlocker, err := b.consensusNodeManager.isBlocker(&blockHash, pubkey)
176 hasBlockerSign = true
180 // discard the invalid signature
181 block.Witness[node.order] = nil
185 return 0, errors.New("the block has no signature of the blocker")
187 return correctSignNum, nil
190 func (b *bbft) checkDoubleSign(nodeOrder, blockHeight uint64, blockHash bc.Hash) (bool, error) {
191 blockNodes := b.consensusNodeManager.blockIndex.NodesByHeight(blockHeight)
192 for _, blockNode := range blockNodes {
193 if blockNode.Hash == blockHash {
196 if ok, err := blockNode.BlockWitness.Test(uint32(nodeOrder)); err != nil && ok {
197 block, err := b.consensusNodeManager.store.GetBlock(&blockHash)
202 // reset nil to discard signature
203 if err := b.updateBlockSignature(block, nodeOrder, nil); err != nil {
213 // SignBlock signing the block if current node is consensus node
214 func (b *bbft) SignBlock(block *types.Block) ([]byte, error) {
215 var xprv chainkd.XPrv
216 xpub := [64]byte(xprv.XPub())
217 blockHash := block.Hash()
218 node, err := b.consensusNodeManager.getConsensusNode(&blockHash, hex.EncodeToString(xpub[:]))
219 if err != nil && err != errNotFoundConsensusNode {
227 signature := xprv.Sign(block.Hash().Bytes())
228 block.Witness[node.order] = signature
229 return signature, nil
232 func (b *bbft) updateBlockSignature(block *types.Block, nodeOrder uint64, signature []byte) error {
233 blockHash := block.Hash()
234 blockNode := b.consensusNodeManager.blockIndex.GetNode(&blockHash)
236 if len(signature) != 0 {
237 if err := blockNode.BlockWitness.Set(uint32(nodeOrder)); err != nil {
241 if err := blockNode.BlockWitness.Clean(uint32(nodeOrder)); err != nil {
246 block.Witness[nodeOrder] = signature
247 txStatus, err := b.consensusNodeManager.store.GetTransactionStatus(&blockHash)
252 return b.consensusNodeManager.store.SaveBlock(block, txStatus)