8 "github.com/golang/groupcache/lru"
9 log "github.com/sirupsen/logrus"
11 "github.com/vapor/crypto/ed25519"
12 "github.com/vapor/crypto/ed25519/chainkd"
13 "github.com/vapor/errors"
14 "github.com/vapor/math/checked"
15 "github.com/vapor/protocol/bc"
16 "github.com/vapor/protocol/bc/types"
17 "github.com/vapor/protocol/state"
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
36 func newBbft(store Store, blockIndex *state.BlockIndex, orphanManage *OrphanManage) *bbft {
38 orphanManage: orphanManage,
39 consensusNodeManager: newConsensusNodeManager(store, blockIndex),
40 signatureCache: lru.New(maxSignatureCacheSize),
44 // IsConsensusPubkey determine whether a public key is a consensus node at a specified height
45 func (b *bbft) IsConsensusPubkey(height uint64, pubkey []byte) (bool, error) {
46 node, err := b.consensusNodeManager.getConsensusNode(height, hex.EncodeToString(pubkey))
47 if err != nil && err != errNotFoundConsensusNode {
50 return node != nil, nil
53 func (b *bbft) isIrreversible(block *types.Block) bool {
54 signNum, err := b.validateSign(block)
59 return signNum > (numOfConsensusNode * 2 / 3)
62 // NextLeaderTime returns the start time of the specified public key as the next leader node
63 func (b *bbft) NextLeaderTime(pubkey []byte, bestBlockTimestamp, bestBlockHeight uint64) (*time.Time, error) {
64 return b.consensusNodeManager.nextLeaderTime(pubkey, bestBlockTimestamp, bestBlockHeight)
67 func (b *bbft) ApplyBlock(voteResultMap map[uint64]*state.VoteResult, block *types.Block) (err error) {
68 voteSeq := block.Height / roundVoteBlockNums
69 voteResult := voteResultMap[voteSeq]
71 if voteResult == nil {
72 store := b.consensusNodeManager.store
73 voteResult, err = store.GetVoteResult(voteSeq)
74 if err != nil && err != ErrNotFoundVoteResult {
79 if voteResult == nil {
80 voteResult = &state.VoteResult{
82 NumOfVote: make(map[string]uint64),
83 LastBlockHeight: block.Height,
87 voteResultMap[voteSeq] = voteResult
89 if voteResult.LastBlockHeight+1 != block.Height {
90 return errors.New("bbft append block error, the block height is not equals last block height plus 1 of vote result")
93 for _, tx := range block.Transactions {
94 for _, input := range tx.Inputs {
95 unVoteInput, ok := input.TypedInput.(*types.UnvoteInput)
100 pubkey := hex.EncodeToString(unVoteInput.Vote)
101 voteResult.NumOfVote[pubkey], ok = checked.SubUint64(voteResult.NumOfVote[pubkey], unVoteInput.Amount)
103 return errVotingOperationOverFlow
106 for _, output := range tx.Outputs {
107 voteOutput, ok := output.TypedOutput.(*types.VoteTxOutput)
112 pubkey := hex.EncodeToString(voteOutput.Vote)
113 voteResult.NumOfVote[pubkey], ok = checked.AddUint64(voteResult.NumOfVote[pubkey], voteOutput.Amount)
115 return errVotingOperationOverFlow
120 voteResult.LastBlockHeight++
121 voteResult.Finalized = (block.Height+1)%roundVoteBlockNums == 0
125 func (b *bbft) DetachBlock(voteResultMap map[uint64]*state.VoteResult, block *types.Block) error {
126 voteSeq := block.Height / roundVoteBlockNums
127 voteResult := voteResultMap[voteSeq]
129 if voteResult == nil {
130 store := b.consensusNodeManager.store
131 voteResult, err := store.GetVoteResult(voteSeq)
135 voteResultMap[voteSeq] = voteResult
138 if voteResult.LastBlockHeight != block.Height {
139 return errors.New("bbft detach block error, the block height is not equals last block height of vote result")
142 for _, tx := range block.Transactions {
143 for _, input := range tx.Inputs {
144 unVoteInput, ok := input.TypedInput.(*types.UnvoteInput)
149 pubkey := hex.EncodeToString(unVoteInput.Vote)
150 voteResult.NumOfVote[pubkey], ok = checked.AddUint64(voteResult.NumOfVote[pubkey], unVoteInput.Amount)
152 return errVotingOperationOverFlow
155 for _, output := range tx.Outputs {
156 voteOutput, ok := output.TypedOutput.(*types.VoteTxOutput)
161 pubkey := hex.EncodeToString(voteOutput.Vote)
162 voteResult.NumOfVote[pubkey], ok = checked.SubUint64(voteResult.NumOfVote[pubkey], voteOutput.Amount)
164 return errVotingOperationOverFlow
169 voteResult.LastBlockHeight--
170 voteResult.Finalized = false
174 // ProcessBlockSignature process the received block signature messages
175 // return once a block become irreversible, whether it's height greater than best block height
176 // if so, the chain module must update status
177 func (b *bbft) ProcessBlockSignature(signature, pubkey []byte, blockHeight uint64, blockHash *bc.Hash) (bool, error) {
178 consensusNode, err := b.consensusNodeManager.getConsensusNode(blockHeight, hex.EncodeToString(pubkey))
183 if !ed25519.Verify(ed25519.PublicKey(pubkey), blockHash.Bytes(), signature) {
184 return false, errInvalidSignature
187 isDoubleSign, err := b.checkDoubleSign(consensusNode.order, blockHeight, *blockHash)
193 log.WithFields(log.Fields{"module": logModule, "blockHash": blockHash.String(), "pubkey": pubkey}).Warn("the consensus node double sign the same height of different block")
194 return false, errDoubleSignBlock
197 orphanBlock, ok := b.orphanManage.Get(blockHash)
199 orphanBlock.Witness[consensusNode.order] = signature
203 block, err := b.consensusNodeManager.store.GetBlock(blockHash)
205 // block is not exist, save the signature
206 key := fmt.Sprintf("%s:%s", blockHash.String(), hex.EncodeToString(pubkey))
207 b.signatureCache.Add(key, signature)
211 if err := b.updateBlockSignature(block, consensusNode.order, signature); err != nil {
215 return b.isIrreversible(block) && blockHeight > b.consensusNodeManager.blockIndex.BestNode().Height, nil
218 // ValidateBlock verify whether the block is valid
219 func (b *bbft) ValidateBlock(block *types.Block) error {
220 signNum, err := b.validateSign(block)
226 return errors.New("no valid signature")
231 // validateSign verify the signatures of block, and return the number of correct signature
232 // if some signature is invalid, they will be reset to nil
233 // if the block has not the signature of blocker, it will return error
234 func (b *bbft) validateSign(block *types.Block) (uint64, error) {
235 var correctSignNum uint64
236 consensusNodeMap, err := b.consensusNodeManager.getConsensusNodesByVoteResult(block.Height)
241 hasBlockerSign := false
242 for pubkey, node := range consensusNodeMap {
243 if len(block.Witness) <= int(node.order) {
247 blockHash := block.Hash()
248 if block.Witness[node.order] == nil {
249 key := fmt.Sprintf("%s:%s", blockHash.String(), pubkey)
250 signature, ok := b.signatureCache.Get(key)
252 block.Witness[node.order] = signature.([]byte)
256 if ed25519.Verify(ed25519.PublicKey(pubkey), blockHash.Bytes(), block.Witness[node.order]) {
257 isDoubleSign, err := b.checkDoubleSign(node.order, block.Height, block.Hash())
263 log.WithFields(log.Fields{"module": logModule, "blockHash": blockHash.String(), "pubkey": pubkey}).Warn("the consensus node double sign the same height of different block")
264 // Consensus node is signed twice with the same block height, discard the signature
265 block.Witness[node.order] = nil
268 isBlocker, err := b.consensusNodeManager.isBlocker(block.Height, block.Timestamp, pubkey)
273 hasBlockerSign = true
277 // discard the invalid signature
278 block.Witness[node.order] = nil
282 return 0, errors.New("the block has no signature of the blocker")
284 return correctSignNum, nil
287 func (b *bbft) checkDoubleSign(nodeOrder, blockHeight uint64, blockHash bc.Hash) (bool, error) {
288 blockNodes := b.consensusNodeManager.blockIndex.NodesByHeight(blockHeight)
289 for _, blockNode := range blockNodes {
290 if blockNode.Hash == blockHash {
293 if ok, err := blockNode.BlockWitness.Test(uint32(nodeOrder)); err != nil && ok {
294 block, err := b.consensusNodeManager.store.GetBlock(&blockHash)
299 // reset nil to discard signature
300 if err := b.updateBlockSignature(block, nodeOrder, nil); err != nil {
308 // SignBlock signing the block if current node is consensus node
309 func (b *bbft) SignBlock(block *types.Block) error {
310 var xprv chainkd.XPrv
311 xpub := [64]byte(xprv.XPub())
312 node, err := b.consensusNodeManager.getConsensusNode(block.Height, hex.EncodeToString(xpub[:]))
313 if err != nil && err != errNotFoundConsensusNode {
321 block.Witness[node.order] = xprv.Sign(block.Hash().Bytes())
325 // UpdateConsensusNodes used to update consensus node after each round of voting
326 func (b *bbft) UpdateConsensusNodes(blockHeight uint64) error {
327 return b.consensusNodeManager.updateConsensusNodes(blockHeight)
330 func (b *bbft) updateBlockSignature(block *types.Block, nodeOrder uint64, signature []byte) error {
331 blockHash := block.Hash()
332 blockNode := b.consensusNodeManager.blockIndex.GetNode(&blockHash)
334 if len(signature) != 0 {
335 if err := blockNode.BlockWitness.Set(uint32(nodeOrder)); err != nil {
339 if err := blockNode.BlockWitness.Clean(uint32(nodeOrder)); err != nil {
344 block.Witness[nodeOrder] = signature
345 txStatus, err := b.consensusNodeManager.store.GetTransactionStatus(&blockHash)
350 return b.consensusNodeManager.store.SaveBlock(block, txStatus)