X-Git-Url: http://git.osdn.net/view?a=blobdiff_plain;f=protocol%2Fbbft.go;h=0d0073779eeba13bb6d622a92ce95322e3d8e1ce;hb=f1a7f2fc9d0b7de097a230f89c131685b6a7dc1d;hp=107334af38ad2e7683697cbb08c6b950895c5081;hpb=43ab81415dcf198597880dbabf7a21ab911763c0;p=bytom%2Fvapor.git diff --git a/protocol/bbft.go b/protocol/bbft.go index 107334af..0d007377 100644 --- a/protocol/bbft.go +++ b/protocol/bbft.go @@ -4,12 +4,9 @@ import ( "encoding/hex" "fmt" - "github.com/golang/groupcache/lru" log "github.com/sirupsen/logrus" "github.com/vapor/config" - "github.com/vapor/crypto/ed25519" - "github.com/vapor/crypto/ed25519/chainkd" "github.com/vapor/errors" "github.com/vapor/event" "github.com/vapor/protocol/bc" @@ -25,236 +22,215 @@ var ( errVotingOperationOverFlow = errors.New("voting operation result overflow") errDoubleSignBlock = errors.New("the consensus is double sign in same height of different block") errInvalidSignature = errors.New("the signature of block is invalid") + errSignForkChain = errors.New("can not sign fork before the irreversible block") ) -type bbft struct { - consensusNodeManager *consensusNodeManager - orphanManage *OrphanManage - signatureCache *lru.Cache - eventDispatcher *event.Dispatcher +func signCacheKey(blockHash, pubkey string) string { + return fmt.Sprintf("%s:%s", blockHash, pubkey) } -func newBbft(store Store, blockIndex *state.BlockIndex, orphanManage *OrphanManage, eventDispatcher *event.Dispatcher) *bbft { - return &bbft{ - orphanManage: orphanManage, - consensusNodeManager: newConsensusNodeManager(store, blockIndex), - signatureCache: lru.New(maxSignatureCacheSize), - eventDispatcher: eventDispatcher, - } -} - -func (b *bbft) isIrreversible(block *types.Block) bool { - consensusNodes, err := b.consensusNodeManager.getConsensusNodesByVoteResult(&block.PreviousBlockHash) +func (c *Chain) isIrreversible(blockHeader *types.BlockHeader) bool { + consensusNodes, err := c.getConsensusNodes(&blockHeader.PreviousBlockHash) if err != nil { return false } - signNum, err := b.validateSign(block) - if err != nil { - return false + signCount := 0 + for i := 0; i < len(consensusNodes); i++ { + if blockHeader.BlockWitness.Get(uint64(i)) != nil { + signCount++ + } } - return signNum > (uint64(len(consensusNodes)) * 2 / 3) -} - -// NextLeaderTime returns the start time of the specified public key as the next leader node -func (b *bbft) NextLeaderTimeRange(pubkey []byte, prevBlockHash *bc.Hash) (uint64, uint64, error) { - return b.consensusNodeManager.nextLeaderTimeRange(pubkey, prevBlockHash) -} - -func (b *bbft) ApplyBlock(voteResultMap map[uint64]*state.VoteResult, block *types.Block) (err error) { - return b.consensusNodeManager.applyBlock(voteResultMap, block) -} - -func (b *bbft) DetachBlock(voteResultMap map[uint64]*state.VoteResult, block *types.Block) error { - return b.consensusNodeManager.detachBlock(voteResultMap, block) + return signCount > len(consensusNodes)*2/3 } -// ProcessBlockSignature process the received block signature messages -// return whether a block become irreversible, if so, the chain module must update status -func (b *bbft) ProcessBlockSignature(signature []byte, xPub [64]byte, blockHeight uint64, blockHash *bc.Hash) (bool, error) { - block, err := b.consensusNodeManager.store.GetBlock(blockHash) +// GetVoteResultByHash return vote result by block hash +func (c *Chain) GetVoteResultByHash(blockHash *bc.Hash) (*state.VoteResult, error) { + blockHeader, err := c.store.GetBlockHeader(blockHash) if err != nil { - // block is not exist, save the signature - key := fmt.Sprintf("%s:%s", blockHash.String(), hex.EncodeToString(xPub[:])) - b.signatureCache.Add(key, signature) - return false, err + return nil, err } + return c.getVoteResult(state.CalcVoteSeq(blockHeader.Height), blockHeader) +} - consensusNode, err := b.consensusNodeManager.getConsensusNode(&block.PreviousBlockHash, hex.EncodeToString(xPub[:])) +// IsBlocker returns whether the consensus node is a blocker at the specified time +func (c *Chain) IsBlocker(prevBlockHash *bc.Hash, pubKey string, timeStamp uint64) (bool, error) { + xPub, err := c.GetBlocker(prevBlockHash, timeStamp) if err != nil { return false, err } + return xPub == pubKey, nil +} - if chainkd.XPub(xPub).Verify(blockHash.Bytes(), signature) { - return false, errInvalidSignature - } - - isDoubleSign, err := b.checkDoubleSign(consensusNode.order, blockHeight, *blockHash) - if err != nil { - return false, err - } +// ProcessBlockSignature process the received block signature messages +// return whether a block become irreversible, if so, the chain module must update status +func (c *Chain) ProcessBlockSignature(signature, xPub []byte, blockHash *bc.Hash) error { + xpubStr := hex.EncodeToString(xPub[:]) + blockHeader, _ := c.store.GetBlockHeader(blockHash) - if isDoubleSign { - 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") - return false, errDoubleSignBlock + // save the signature if the block is not exist + if blockHeader == nil { + cacheKey := signCacheKey(blockHash.String(), xpubStr) + c.signatureCache.Add(cacheKey, signature) + return nil } - orphanBlock, ok := b.orphanManage.Get(blockHash) - if ok { - orphanBlock.Witness[consensusNode.order] = signature - return false, nil + consensusNode, err := c.getConsensusNode(&blockHeader.PreviousBlockHash, xpubStr) + if err != nil { + return err } - if err := b.updateBlockSignature(block, consensusNode.order, signature); err != nil { - return false, err + if blockHeader.BlockWitness.Get(consensusNode.Order) != nil { + return nil } - return b.isIrreversible(block), nil -} - -// ValidateBlock verify whether the block is valid -func (b *bbft) ValidateBlock(block *types.Block) error { - signNum, err := b.validateSign(block) - if err != nil { + c.cond.L.Lock() + defer c.cond.L.Unlock() + if err := c.checkNodeSign(blockHeader, consensusNode, signature); err != nil { return err } - if signNum == 0 { - return errors.New("no valid signature") + if err := c.updateBlockSignature(blockHeader, consensusNode.Order, signature); err != nil { + return err } - return nil + return c.eventDispatcher.Post(event.BlockSignatureEvent{BlockHash: *blockHash, Signature: signature, XPub: xPub}) } // validateSign verify the signatures of block, and return the number of correct signature // if some signature is invalid, they will be reset to nil // if the block has not the signature of blocker, it will return error -func (b *bbft) validateSign(block *types.Block) (uint64, error) { - var correctSignNum uint64 - consensusNodeMap, err := b.consensusNodeManager.getConsensusNodesByVoteResult(&block.PreviousBlockHash) +func (c *Chain) validateSign(block *types.Block) error { + consensusNodeMap, err := c.getConsensusNodes(&block.PreviousBlockHash) if err != nil { - return 0, err + return err } hasBlockerSign := false + blockHash := block.Hash() for pubKey, node := range consensusNodeMap { - if len(block.Witness) <= int(node.order) { + if len(block.Witness) <= int(node.Order) { continue } - blockHash := block.Hash() - if block.Witness[node.order] == nil { - key := fmt.Sprintf("%s:%s", blockHash.String(), pubKey) - signature, ok := b.signatureCache.Get(key) - if ok { - block.Witness[node.order] = signature.([]byte) + if block.Get(node.Order) == nil { + cachekey := signCacheKey(blockHash.String(), pubKey) + if signature, ok := c.signatureCache.Get(cachekey); ok { + block.Set(node.Order, signature.([]byte)) + } else { + continue } } - pubKeyBytes, err := hex.DecodeString(pubKey) - if err != nil { - return 0, err + if err := c.checkNodeSign(&block.BlockHeader, node, block.Get(node.Order)); err == errDoubleSignBlock { + log.WithFields(log.Fields{"module": logModule, "blockHash": blockHash.String(), "pubKey": pubKey}).Warn("the consensus node double sign the same height of different block") + block.Delete(node.Order) + continue + } else if err != nil { + return err } - if ed25519.Verify(ed25519.PublicKey(pubKeyBytes[:32]), blockHash.Bytes(), block.Witness[node.order]) { - isDoubleSign, err := b.checkDoubleSign(node.order, block.Height, block.Hash()) - if err != nil { - return 0, err - } + isBlocker, err := c.IsBlocker(&block.PreviousBlockHash, pubKey, block.Timestamp) + if err != nil { + return err + } - if isDoubleSign { - log.WithFields(log.Fields{"module": logModule, "blockHash": blockHash.String(), "pubKey": pubKey}).Warn("the consensus node double sign the same height of different block") - // Consensus node is signed twice with the same block height, discard the signature - block.Witness[node.order] = nil - } else { - correctSignNum++ - isBlocker, err := b.consensusNodeManager.isBlocker(block, pubKey) - if err != nil { - return 0, err - } - if isBlocker { - hasBlockerSign = true - } - } - } else { - // discard the invalid signature - block.Witness[node.order] = nil + if isBlocker { + hasBlockerSign = true } + } + if !hasBlockerSign { - return 0, errors.New("the block has no signature of the blocker") + return errors.New("the block has no signature of the blocker") } - return correctSignNum, nil + return nil } -func (b *bbft) checkDoubleSign(nodeOrder, blockHeight uint64, blockHash bc.Hash) (bool, error) { - blockNodes := b.consensusNodeManager.blockIndex.NodesByHeight(blockHeight) - for _, blockNode := range blockNodes { - if blockNode.Hash == blockHash { +func (c *Chain) checkNodeSign(bh *types.BlockHeader, consensusNode *state.ConsensusNode, signature []byte) error { + if !consensusNode.XPub.Verify(bh.Hash().Bytes(), signature) { + return errInvalidSignature + } + + blockHashes, err := c.store.GetBlockHashesByHeight(bh.Height) + if err != nil { + return err + } + + for _, blockHash := range blockHashes { + if *blockHash == bh.Hash() { continue } - if ok, err := blockNode.BlockWitness.Test(uint32(nodeOrder)); err != nil && ok { - block, err := b.consensusNodeManager.store.GetBlock(&blockHash) - if err != nil { - return false, err - } - // reset nil to discard signature - if err := b.updateBlockSignature(block, nodeOrder, nil); err != nil { - return false, err - } + blockHeader, err := c.store.GetBlockHeader(blockHash) + if err != nil { + return err + } - return true, nil + consensusNode, err := c.getConsensusNode(&blockHeader.PreviousBlockHash, consensusNode.XPub.String()) + if err != nil && err != errNotFoundConsensusNode { + return err + } + + if err == errNotFoundConsensusNode { + continue + } + + if blockHeader.BlockWitness.Get(consensusNode.Order) != nil { + return errDoubleSignBlock } } - return false, nil + return nil } // SignBlock signing the block if current node is consensus node -func (b *bbft) SignBlock(block *types.Block) ([]byte, error) { +func (c *Chain) SignBlock(block *types.Block) ([]byte, error) { xprv := config.CommonConfig.PrivateKey() - xpub := [64]byte(xprv.XPub()) - node, err := b.consensusNodeManager.getConsensusNode(&block.PreviousBlockHash, hex.EncodeToString(xpub[:])) - if err != nil && err != errNotFoundConsensusNode { + xpubStr := xprv.XPub().String() + node, err := c.getConsensusNode(&block.PreviousBlockHash, xpubStr) + if err == errNotFoundConsensusNode { + return nil, nil + } else if err != nil { return nil, err } - if node == nil { - return nil, nil + //check double sign in same block height + blockHashes, err := c.store.GetBlockHashesByHeight(block.Height) + if err != nil { + return nil, err } - signature := block.Witness[node.order] + for _, hash := range blockHashes { + blockHeader, err := c.store.GetBlockHeader(hash) + if err != nil { + return nil, err + } + + // Has already signed the same height block + if blockHeader.BlockWitness.Get(node.Order) != nil { + return nil, nil + } + } + + signature := block.Get(node.Order) if len(signature) == 0 { signature = xprv.Sign(block.Hash().Bytes()) - block.Witness[node.order] = signature + block.Set(node.Order, signature) } return signature, nil } -func (b *bbft) updateBlockSignature(block *types.Block, nodeOrder uint64, signature []byte) error { - blockHash := block.Hash() - blockNode := b.consensusNodeManager.blockIndex.GetNode(&blockHash) +func (c *Chain) updateBlockSignature(blockHeader *types.BlockHeader, nodeOrder uint64, signature []byte) error { + blockHeader.Set(nodeOrder, signature) + if err := c.store.SaveBlockHeader(blockHeader); err != nil { + return err + } - if len(signature) != 0 { - if err := blockNode.BlockWitness.Set(uint32(nodeOrder)); err != nil { - return err - } - } else { - if err := blockNode.BlockWitness.Clean(uint32(nodeOrder)); err != nil { + if c.isIrreversible(blockHeader) && blockHeader.Height > c.bestIrrBlockHeader.Height { + if err := c.store.SaveChainStatus(c.bestBlockHeader, blockHeader, []*types.BlockHeader{}, state.NewUtxoViewpoint(), []*state.VoteResult{}); err != nil { return err } + c.bestIrrBlockHeader = blockHeader } - - block.Witness[nodeOrder] = signature - txStatus, err := b.consensusNodeManager.store.GetTransactionStatus(&blockHash) - if err != nil { - return err - } - - return b.consensusNodeManager.store.SaveBlock(block, txStatus) -} - -// SetBlockIndex set the block index field -func (b *bbft) SetBlockIndex(blockIndex *state.BlockIndex) { - b.consensusNodeManager.blockIndex = blockIndex + return nil }