7 "github.com/golang/groupcache/lru"
8 log "github.com/sirupsen/logrus"
10 "github.com/vapor/config"
11 "github.com/vapor/crypto/ed25519"
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"
17 "github.com/vapor/crypto/ed25519/chainkd"
21 maxSignatureCacheSize = 10000
25 errVotingOperationOverFlow = errors.New("voting operation result overflow")
26 errDoubleSignBlock = errors.New("the consensus is double sign in same height of different block")
27 errInvalidSignature = errors.New("the signature of block is invalid")
31 consensusNodeManager *consensusNodeManager
32 orphanManage *OrphanManage
33 signatureCache *lru.Cache
34 eventDispatcher *event.Dispatcher
37 func newBbft(store Store, blockIndex *state.BlockIndex, orphanManage *OrphanManage, eventDispatcher *event.Dispatcher) *bbft {
39 orphanManage: orphanManage,
40 consensusNodeManager: newConsensusNodeManager(store, blockIndex),
41 signatureCache: lru.New(maxSignatureCacheSize),
42 eventDispatcher: eventDispatcher,
46 func (b *bbft) isIrreversible(block *types.Block) bool {
47 signNum, err := b.validateSign(block)
52 return signNum > (NumOfConsensusNode * 2 / 3)
55 // NextLeaderTime returns the start time of the specified public key as the next leader node
56 func (b *bbft) NextLeaderTimeRange(pubkey []byte, bestBlockHash *bc.Hash) (uint64, uint64, error) {
57 return b.consensusNodeManager.nextLeaderTimeRange(pubkey, bestBlockHash)
60 func (b *bbft) ApplyBlock(voteResultMap map[uint64]*state.VoteResult, block *types.Block) (err error) {
61 return b.consensusNodeManager.applyBlock(voteResultMap, block)
64 func (b *bbft) DetachBlock(voteResultMap map[uint64]*state.VoteResult, block *types.Block) error {
65 return b.consensusNodeManager.detachBlock(voteResultMap, block)
68 // ProcessBlockSignature process the received block signature messages
69 // return whether a block become irreversible, if so, the chain module must update status
70 func (b *bbft) ProcessBlockSignature(signature []byte, xPub [64]byte, blockHeight uint64, blockHash *bc.Hash) (bool, error) {
71 block, err := b.consensusNodeManager.store.GetBlock(blockHash)
73 // block is not exist, save the signature
74 key := fmt.Sprintf("%s:%s", blockHash.String(), hex.EncodeToString(xPub[:]))
75 b.signatureCache.Add(key, signature)
79 consensusNode, err := b.consensusNodeManager.getConsensusNode(&block.PreviousBlockHash, hex.EncodeToString(xPub[:]))
85 if chainkd.XPub(xPub).Verify(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(), "xPub": hex.EncodeToString(xPub[:])}).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 if err := b.updateBlockSignature(block, consensusNode.order, signature); err != nil {
109 return b.isIrreversible(block), nil
112 // ValidateBlock verify whether the block is valid
113 func (b *bbft) ValidateBlock(block *types.Block) error {
114 signNum, err := b.validateSign(block)
120 return errors.New("no valid signature")
125 // validateSign verify the signatures of block, and return the number of correct signature
126 // if some signature is invalid, they will be reset to nil
127 // if the block has not the signature of blocker, it will return error
128 func (b *bbft) validateSign(block *types.Block) (uint64, error) {
129 var correctSignNum uint64
130 consensusNodeMap, err := b.consensusNodeManager.getConsensusNodesByVoteResult(&block.PreviousBlockHash)
135 hasBlockerSign := false
136 for pubKey, node := range consensusNodeMap {
137 if len(block.Witness) <= int(node.order) {
141 blockHash := block.Hash()
142 if block.Witness[node.order] == nil {
143 key := fmt.Sprintf("%s:%s", blockHash.String(), pubKey)
144 signature, ok := b.signatureCache.Get(key)
146 block.Witness[node.order] = signature.([]byte)
150 pubKeyBytes, err := hex.DecodeString(pubKey)
155 if ed25519.Verify(ed25519.PublicKey(pubKeyBytes[:32]), blockHash.Bytes(), block.Witness[node.order]) {
156 isDoubleSign, err := b.checkDoubleSign(node.order, block.Height, block.Hash())
162 log.WithFields(log.Fields{"module": logModule, "blockHash": blockHash.String(), "pubKey": pubKey}).Warn("the consensus node double sign the same height of different block")
163 // Consensus node is signed twice with the same block height, discard the signature
164 block.Witness[node.order] = nil
167 isBlocker, err := b.consensusNodeManager.isBlocker(block, pubKey)
172 hasBlockerSign = true
176 // discard the invalid signature
177 block.Witness[node.order] = nil
181 return 0, errors.New("the block has no signature of the blocker")
183 return correctSignNum, nil
186 func (b *bbft) checkDoubleSign(nodeOrder, blockHeight uint64, blockHash bc.Hash) (bool, error) {
187 blockNodes := b.consensusNodeManager.blockIndex.NodesByHeight(blockHeight)
188 for _, blockNode := range blockNodes {
189 if blockNode.Hash == blockHash {
192 if ok, err := blockNode.BlockWitness.Test(uint32(nodeOrder)); err != nil && ok {
193 block, err := b.consensusNodeManager.store.GetBlock(&blockHash)
198 // reset nil to discard signature
199 if err := b.updateBlockSignature(block, nodeOrder, nil); err != nil {
209 // SignBlock signing the block if current node is consensus node
210 func (b *bbft) SignBlock(block *types.Block) ([]byte, error) {
211 xprv := config.CommonConfig.PrivateKey()
212 xpub := [64]byte(xprv.XPub())
213 node, err := b.consensusNodeManager.getConsensusNode(&block.PreviousBlockHash, hex.EncodeToString(xpub[:]))
214 if err != nil && err != errNotFoundConsensusNode {
222 signature := block.Witness[node.order]
223 if len(signature) == 0 {
224 signature = xprv.Sign(block.Hash().Bytes())
225 block.Witness[node.order] = signature
227 return signature, nil
230 func (b *bbft) updateBlockSignature(block *types.Block, nodeOrder uint64, signature []byte) error {
231 blockHash := block.Hash()
232 blockNode := b.consensusNodeManager.blockIndex.GetNode(&blockHash)
234 if len(signature) != 0 {
235 if err := blockNode.BlockWitness.Set(uint32(nodeOrder)); err != nil {
239 if err := blockNode.BlockWitness.Clean(uint32(nodeOrder)); err != nil {
244 block.Witness[nodeOrder] = signature
245 txStatus, err := b.consensusNodeManager.store.GetTransactionStatus(&blockHash)
250 return b.consensusNodeManager.store.SaveBlock(block, txStatus)