7 log "github.com/sirupsen/logrus"
9 "github.com/vapor/config"
10 "github.com/vapor/errors"
11 "github.com/vapor/protocol/bc"
12 "github.com/vapor/protocol/bc/types"
13 "github.com/vapor/protocol/state"
14 "github.com/vapor/event"
18 maxSignatureCacheSize = 10000
22 errVotingOperationOverFlow = errors.New("voting operation result overflow")
23 errDoubleSignBlock = errors.New("the consensus is double sign in same height of different block")
24 errInvalidSignature = errors.New("the signature of block is invalid")
27 func signCacheKey(blockHash, pubkey string) string {
28 return fmt.Sprintf("%s:%s", blockHash, pubkey)
31 func (c *Chain) isIrreversible(blockNode *state.BlockNode) bool {
32 consensusNodes, err := c.consensusNodeManager.getConsensusNodes(&blockNode.Parent.Hash)
38 for i := 0; i < len(consensusNodes); i++ {
39 if ok, _ := blockNode.BlockWitness.Test(uint32(i)); ok {
44 return signCount > len(consensusNodes)*2/3
47 // NextLeaderTime returns the start time of the specified public key as the next leader node
48 func (c *Chain) IsBlocker(prevBlockHash *bc.Hash, pubkey string, timeStamp uint64) (bool, error) {
49 return c.consensusNodeManager.isBlocker(prevBlockHash, pubkey, timeStamp)
52 // ProcessBlockSignature process the received block signature messages
53 // return whether a block become irreversible, if so, the chain module must update status
54 func (c *Chain) ProcessBlockSignature(signature []byte, xPub [64]byte, blockHash *bc.Hash) error {
55 xpubStr := hex.EncodeToString(xPub[:])
56 blockNode := c.index.GetNode(blockHash)
57 // save the signature if the block is not exist
59 cacheKey := signCacheKey(blockHash.String(), xpubStr)
60 c.signatureCache.Add(cacheKey, signature)
64 consensusNode, err := c.consensusNodeManager.getConsensusNode(&blockNode.Parent.Hash, xpubStr)
69 if exist, err := blockNode.BlockWitness.Test(uint32(consensusNode.Order)); err != nil && exist {
73 if !consensusNode.XPub.Verify(blockHash.Bytes(), signature) {
74 return errInvalidSignature
77 isDoubleSign, err := c.checkDoubleSign(consensusNode.Order, blockNode.Height, *blockHash)
83 return errDoubleSignBlock
86 if err := c.updateBlockSignature(&blockNode.Hash, consensusNode.Order, signature); err != nil {
90 if c.isIrreversible(blockNode) && blockNode.Height > c.bestIrreversibleNode.Height {
91 bestIrreversibleNode := c.index.GetNode(blockHash)
92 if err := c.store.SaveChainNodeStatus(c.bestNode, bestIrreversibleNode); err != nil {
96 c.bestIrreversibleNode = bestIrreversibleNode
99 return c.eventDispatcher.Post(event.BlockSignatureEvent{BlockHash: *blockHash, Signature: signature, XPub: xPub})
102 // validateSign verify the signatures of block, and return the number of correct signature
103 // if some signature is invalid, they will be reset to nil
104 // if the block has not the signature of blocker, it will return error
105 func (c *Chain) validateSign(block *types.Block) (uint64, error) {
106 consensusNodeMap, err := c.consensusNodeManager.getConsensusNodes(&block.PreviousBlockHash)
111 hasBlockerSign := false
112 signCount := uint64(0)
113 blockHash := block.Hash()
114 for pubKey, node := range consensusNodeMap {
115 if len(block.Witness) <= int(node.Order) {
119 if block.Witness[node.Order] == nil {
120 cachekey := signCacheKey(blockHash.String(), pubKey)
121 if signature, ok := c.signatureCache.Get(cachekey); ok {
122 block.Witness[node.Order] = signature.([]byte)
128 if ok := node.XPub.Verify(blockHash.Bytes(), block.Witness[node.Order]); !ok {
129 block.Witness[node.Order] = nil
133 isDoubleSign, err := c.checkDoubleSign(node.Order, block.Height, block.Hash())
139 // Consensus node is signed twice with the same block height, discard the signature
140 log.WithFields(log.Fields{"module": logModule, "blockHash": blockHash.String(), "pubKey": pubKey}).Warn("the consensus node double sign the same height of different block")
141 block.Witness[node.Order] = nil
146 isBlocker, err := c.consensusNodeManager.isBlocker(&block.PreviousBlockHash, pubKey, block.Timestamp)
152 hasBlockerSign = true
158 return 0, errors.New("the block has no signature of the blocker")
160 return signCount, nil
163 func (c *Chain) checkDoubleSign(nodeOrder, blockHeight uint64, blockHash bc.Hash) (bool, error) {
164 blockNodes := c.consensusNodeManager.blockIndex.NodesByHeight(blockHeight)
165 for _, blockNode := range blockNodes {
166 if blockNode.Hash == blockHash {
169 if ok, err := blockNode.BlockWitness.Test(uint32(nodeOrder)); err != nil && ok {
170 if err := c.updateBlockSignature(&blockHash, nodeOrder, nil); err != nil {
180 // SignBlock signing the block if current node is consensus node
181 func (c *Chain) SignBlock(block *types.Block) ([]byte, error) {
182 xprv := config.CommonConfig.PrivateKey()
183 xpub := [64]byte(xprv.XPub())
184 node, err := c.consensusNodeManager.getConsensusNode(&block.PreviousBlockHash, hex.EncodeToString(xpub[:]))
185 if err != nil && err != errNotFoundConsensusNode {
193 blockNodes := c.consensusNodeManager.blockIndex.NodesByHeight(block.Height)
194 for _, blockNode := range blockNodes {
195 // Has already signed the same height block
196 if ok, err := blockNode.BlockWitness.Test(uint32(node.Order)); err != nil && ok {
201 signature := block.Witness[node.Order]
202 if len(signature) == 0 {
203 signature = xprv.Sign(block.Hash().Bytes())
204 block.Witness[node.Order] = signature
206 return signature, nil
209 func (c *Chain) updateBlockSignature(blockHash *bc.Hash, nodeOrder uint64, signature []byte) error {
210 blockNode := c.consensusNodeManager.blockIndex.GetNode(blockHash)
211 if len(signature) != 0 {
212 if err := blockNode.BlockWitness.Set(uint32(nodeOrder)); err != nil {
216 if err := blockNode.BlockWitness.Clean(uint32(nodeOrder)); err != nil {
221 block, err := c.store.GetBlock(blockHash)
226 block.Witness[nodeOrder] = signature
227 txStatus, err := c.consensusNodeManager.store.GetTransactionStatus(blockHash)
232 return c.consensusNodeManager.store.SaveBlock(block, txStatus)