X-Git-Url: http://git.osdn.net/view?p=bytom%2Fvapor.git;a=blobdiff_plain;f=protocol%2Fbbft.go;h=d62b3ed6612855a641815e695cb2ffe3ecc6902c;hp=ee38f682a6994fb874cd8b0b501bff9e603bbc24;hb=1337be95f74a1d2a1a7316737efde413f29bcb2f;hpb=b9175a5cd6c0fe90429c65cb5f7112e6845cb6c0 diff --git a/protocol/bbft.go b/protocol/bbft.go index ee38f682..d62b3ed6 100644 --- a/protocol/bbft.go +++ b/protocol/bbft.go @@ -4,16 +4,15 @@ 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/errors" - "github.com/vapor/event" - "github.com/vapor/protocol/bc" - "github.com/vapor/protocol/bc/types" - "github.com/vapor/protocol/state" + "github.com/bytom/vapor/config" + "github.com/bytom/vapor/crypto/ed25519/chainkd" + "github.com/bytom/vapor/errors" + "github.com/bytom/vapor/event" + "github.com/bytom/vapor/protocol/bc" + "github.com/bytom/vapor/protocol/bc/types" + "github.com/bytom/vapor/protocol/state" ) const ( @@ -21,233 +20,206 @@ const ( ) 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") + 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, - } -} - -// IsConsensusPubkey determine whether a public key is a consensus node at a specified height -func (b *bbft) IsConsensusPubkey(blockHash *bc.Hash, pubkey []byte) (bool, error) { - node, err := b.consensusNodeManager.getConsensusNode(blockHash, hex.EncodeToString(pubkey)) - if err != nil && err != errNotFoundConsensusNode { - return false, err - } - return node != nil, nil -} - -func (b *bbft) isIrreversible(block *types.Block) bool { - signNum, err := b.validateSign(block) +func (c *Chain) checkDoubleSign(bh *types.BlockHeader, xPub string) error { + blockHashes, err := c.store.GetBlockHashesByHeight(bh.Height) if err != nil { - return false + return err } - return signNum > (numOfConsensusNode * 2 / 3) -} + for _, blockHash := range blockHashes { + if *blockHash == bh.Hash() { + continue + } -// NextLeaderTime returns the start time of the specified public key as the next leader node -func (b *bbft) NextLeaderTimeRange(pubkey []byte, bestBlockHash *bc.Hash) (uint64, uint64, error) { - return b.consensusNodeManager.nextLeaderTimeRange(pubkey, bestBlockHash) -} + blockHeader, err := c.store.GetBlockHeader(blockHash) + if err != nil { + return err + } -func (b *bbft) ApplyBlock(voteResultMap map[uint64]*state.VoteResult, block *types.Block) (err error) { - return b.consensusNodeManager.applyBlock(voteResultMap, block) -} + consensusNode, err := c.getConsensusNode(&blockHeader.PreviousBlockHash, xPub) + if err == errNotFoundConsensusNode { + continue + } else if err != nil { + return err + } -func (b *bbft) DetachBlock(voteResultMap map[uint64]*state.VoteResult, block *types.Block) error { - return b.consensusNodeManager.detachBlock(voteResultMap, block) + if blockHeader.BlockWitness.Get(consensusNode.Order) != nil { + return errDoubleSignBlock + } + } + return nil } -// ProcessBlockSignature process the received block signature messages -// return once a block become irreversible, whether it's height greater than best block height -// if so, the chain module must update status -func (b *bbft) ProcessBlockSignature(signature, pubkey []byte, blockHeight uint64, blockHash *bc.Hash) (bool, error) { - consensusNode, err := b.consensusNodeManager.getConsensusNode(blockHash, hex.EncodeToString(pubkey)) - if err != nil { - return false, err +func (c *Chain) checkNodeSign(bh *types.BlockHeader, consensusNode *state.ConsensusNode, signature []byte) error { + if !consensusNode.XPub.Verify(bh.Hash().Bytes(), signature) { + return errInvalidSignature } - if !ed25519.Verify(ed25519.PublicKey(pubkey), blockHash.Bytes(), signature) { - return false, errInvalidSignature - } + return c.checkDoubleSign(bh, consensusNode.XPub.String()) +} - isDoubleSign, err := b.checkDoubleSign(consensusNode.order, blockHeight, *blockHash) +func (c *Chain) isIrreversible(blockHeader *types.BlockHeader) bool { + consensusNodes, err := c.getConsensusNodes(&blockHeader.PreviousBlockHash) if err != nil { - return false, err + return false } - 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") - return false, errDoubleSignBlock + signCount := 0 + for i := 0; i < len(consensusNodes); i++ { + if blockHeader.BlockWitness.Get(uint64(i)) != nil { + signCount++ + } } - orphanBlock, ok := b.orphanManage.Get(blockHash) - if ok { - orphanBlock.Witness[consensusNode.order] = signature - return false, nil - } + return signCount > len(consensusNodes)*2/3 +} - block, err := b.consensusNodeManager.store.GetBlock(blockHash) - if err != nil { - // block is not exist, save the signature - key := fmt.Sprintf("%s:%s", blockHash.String(), hex.EncodeToString(pubkey)) - b.signatureCache.Add(key, signature) - return false, err +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 err := b.updateBlockSignature(block, consensusNode.order, signature); err != nil { - return false, err + if !c.isIrreversible(blockHeader) || blockHeader.Height <= c.lastIrrBlockHeader.Height { + return nil } - return b.isIrreversible(block) && blockHeight > b.consensusNodeManager.blockIndex.BestNode().Height, nil -} + if c.InMainChain(blockHeader.Hash()) { + if err := c.store.SaveChainStatus(c.bestBlockHeader, blockHeader, []*types.BlockHeader{}, state.NewUtxoViewpoint(), []*state.ConsensusResult{}); err != nil { + return err + } -// ValidateBlock verify whether the block is valid -func (b *bbft) ValidateBlock(block *types.Block) error { - signNum, err := b.validateSign(block) - if err != nil { - return err - } + c.lastIrrBlockHeader = blockHeader + } else { + // block is on a forked chain + log.WithFields(log.Fields{"module": logModule}).Info("majority votes received on forked chain") + tail, err := c.traceLongestChainTail(blockHeader) + if err != nil { + return err + } - if signNum == 0 { - return errors.New("no valid signature") + return c.reorganizeChain(tail) } return nil } // 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 - blockHash := block.Hash() - consensusNodeMap, err := b.consensusNodeManager.getConsensusNodesByVoteResult(&blockHash) +// if the block does not have the signature of blocker, it will return error +func (c *Chain) validateSign(block *types.Block) error { + consensusNodeMap, err := c.getConsensusNodes(&block.PreviousBlockHash) if err != nil { - return 0, err + return err } - hasBlockerSign := false - for pubkey, node := range consensusNodeMap { - if len(block.Witness) <= int(node.order) { - continue - } + blocker, err := c.GetBlocker(&block.PreviousBlockHash, block.Timestamp) + if err != nil { + return err + } - 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) + hasBlockerSign := false + blockHash := block.Hash() + for pubKey, node := range consensusNodeMap { + if block.BlockWitness.Get(node.Order) == nil { + cachekey := signCacheKey(blockHash.String(), pubKey) + if signature, ok := c.signatureCache.Get(cachekey); ok { + block.Set(node.Order, signature.([]byte)) + c.eventDispatcher.Post(event.BlockSignatureEvent{BlockHash: blockHash, Signature: signature.([]byte), XPub: node.XPub[:]}) + c.signatureCache.Remove(cachekey) + } else { + continue } } - if ed25519.Verify(ed25519.PublicKey(pubkey), blockHash.Bytes(), block.Witness[node.order]) { - isDoubleSign, err := b.checkDoubleSign(node.order, block.Height, block.Hash()) - 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.BlockWitness.Delete(node.Order) + continue + } else 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(&blockHash, pubkey) - if err != nil { - return 0, err - } - if isBlocker { - hasBlockerSign = true - } - } - } else { - // discard the invalid signature - block.Witness[node.order] = nil + if blocker == pubKey { + 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 { - continue +// 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) + + // save the signature if the block is not exist + if blockHeader == nil { + var xPubKey chainkd.XPub + copy(xPubKey[:], xPub[:]) + if !xPubKey.Verify(blockHash.Bytes(), signature) { + return errInvalidSignature } - 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 - } + cacheKey := signCacheKey(blockHash.String(), xpubStr) + c.signatureCache.Add(cacheKey, signature) + return nil + } - return true, nil - } + consensusNode, err := c.getConsensusNode(&blockHeader.PreviousBlockHash, xpubStr) + if err != nil { + return err } - return false, nil -} -// SignBlock signing the block if current node is consensus node -func (b *bbft) SignBlock(block *types.Block) ([]byte, error) { - xprv := config.CommonConfig.PrivateKey() - xpub := [64]byte(xprv.XPub()) - blockHash := block.Hash() - node, err := b.consensusNodeManager.getConsensusNode(&blockHash, hex.EncodeToString(xpub[:])) - if err != nil && err != errNotFoundConsensusNode { - return nil, err + if blockHeader.BlockWitness.Get(consensusNode.Order) != nil { + return nil } - if node == nil { - return nil, nil + c.cond.L.Lock() + defer c.cond.L.Unlock() + if err := c.checkNodeSign(blockHeader, consensusNode, signature); err != nil { + return err } - signature := xprv.Sign(block.Hash().Bytes()) - block.Witness[node.order] = signature - return signature, nil + if err := c.updateBlockSignature(blockHeader, consensusNode.Order, signature); err != nil { + return err + } + return c.eventDispatcher.Post(event.BlockSignatureEvent{BlockHash: *blockHash, Signature: signature, XPub: xPub}) } -func (b *bbft) updateBlockSignature(block *types.Block, nodeOrder uint64, signature []byte) error { - blockHash := block.Hash() - blockNode := b.consensusNodeManager.blockIndex.GetNode(&blockHash) - - 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 { - return err - } +// SignBlock signing the block if current node is consensus node +func (c *Chain) SignBlock(block *types.Block) ([]byte, error) { + xprv := config.CommonConfig.PrivateKey() + xpubStr := xprv.XPub().String() + node, err := c.getConsensusNode(&block.PreviousBlockHash, xpubStr) + if err == errNotFoundConsensusNode { + return nil, nil + } else if err != nil { + return nil, err } - block.Witness[nodeOrder] = signature - txStatus, err := b.consensusNodeManager.store.GetTransactionStatus(&blockHash) - if err != nil { - return err + if err := c.checkDoubleSign(&block.BlockHeader, node.XPub.String()); err == errDoubleSignBlock { + return nil, nil + } else if err != nil { + return nil, err } - return b.consensusNodeManager.store.SaveBlock(block, txStatus) + signature := block.Get(node.Order) + if len(signature) == 0 { + signature = xprv.Sign(block.Hash().Bytes()) + block.Set(node.Order, signature) + } + return signature, nil }