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"
17 maxSignatureCacheSize = 10000
21 errVotingOperationOverFlow = errors.New("voting operation result overflow")
22 errDoubleSignBlock = errors.New("the consensus is double sign in same height of different block")
23 errInvalidSignature = errors.New("the signature of block is invalid")
26 func signCacheKey(blockHash, pubkey string) string {
27 return fmt.Sprintf("%s:%s", blockHash, pubkey)
30 func (c *Chain) isIrreversible(blockNode *state.BlockNode) bool {
31 consensusNodes, err := c.consensusNodeManager.getConsensusNodesByVoteResult(&blockNode.Parent.Hash)
37 for i := 0; i < len(consensusNodes); i++ {
38 if ok, _ := blockNode.BlockWitness.Test(uint32(i)); ok {
43 return signCount > len(consensusNodes)*2/3
46 // NextLeaderTime returns the start time of the specified public key as the next leader node
47 func (c *Chain) IsBlocker(prevBlockHash *bc.Hash, pubkey string, timeStamp uint64) (bool, error) {
48 return c.consensusNodeManager.isBlocker(prevBlockHash, pubkey, timeStamp)
51 // ProcessBlockSignature process the received block signature messages
52 // return whether a block become irreversible, if so, the chain module must update status
53 func (c *Chain) ProcessBlockSignature(signature []byte, xPub [64]byte, blockHash *bc.Hash) error {
54 xpubStr := hex.EncodeToString(xPub[:])
55 blockNode := c.index.GetNode(blockHash)
56 // save the signature if the block is not exist
58 cacheKey := signCacheKey(blockHash.String(), xpubStr)
59 c.signatureCache.Add(cacheKey, signature)
63 consensusNode, err := c.consensusNodeManager.getConsensusNode(&blockNode.Parent.Hash, xpubStr)
68 if consensusNode.XPub.Verify(blockHash.Bytes(), signature) {
69 return errInvalidSignature
72 isDoubleSign, err := c.checkDoubleSign(consensusNode.Order, blockNode.Height, *blockHash)
78 return errDoubleSignBlock
81 if err := c.updateBlockSignature(&blockNode.Hash, consensusNode.Order, signature); err != nil {
85 if c.isIrreversible(blockNode) && blockNode.Height > c.bestIrreversibleNode.Height {
86 bestIrreversibleNode := c.index.GetNode(blockHash)
87 if err := c.store.SaveChainNodeStatus(c.bestNode, bestIrreversibleNode); err != nil {
91 c.bestIrreversibleNode = bestIrreversibleNode
96 // validateSign verify the signatures of block, and return the number of correct signature
97 // if some signature is invalid, they will be reset to nil
98 // if the block has not the signature of blocker, it will return error
99 func (c *Chain) validateSign(block *types.Block) (uint64, error) {
100 consensusNodeMap, err := c.consensusNodeManager.getConsensusNodesByVoteResult(&block.PreviousBlockHash)
105 hasBlockerSign := false
106 signCount := uint64(0)
107 blockHash := block.Hash()
108 for pubKey, node := range consensusNodeMap {
109 if len(block.Witness) <= int(node.Order) {
113 if block.Witness[node.Order] == nil {
114 cachekey := signCacheKey(blockHash.String(), pubKey)
115 if signature, ok := c.signatureCache.Get(cachekey); ok {
116 block.Witness[node.Order] = signature.([]byte)
122 if ok := node.XPub.Verify(blockHash.Bytes(), block.Witness[node.Order]); !ok {
123 block.Witness[node.Order] = nil
127 isDoubleSign, err := c.checkDoubleSign(node.Order, block.Height, block.Hash())
133 // Consensus node is signed twice with the same block height, discard the signature
134 log.WithFields(log.Fields{"module": logModule, "blockHash": blockHash.String(), "pubKey": pubKey}).Warn("the consensus node double sign the same height of different block")
135 block.Witness[node.Order] = nil
140 isBlocker, err := c.consensusNodeManager.isBlocker(&block.PreviousBlockHash, pubKey, block.Timestamp)
146 hasBlockerSign = true
152 return 0, errors.New("the block has no signature of the blocker")
154 return signCount, nil
157 func (c *Chain) checkDoubleSign(nodeOrder, blockHeight uint64, blockHash bc.Hash) (bool, error) {
158 blockNodes := c.consensusNodeManager.blockIndex.NodesByHeight(blockHeight)
159 for _, blockNode := range blockNodes {
160 if blockNode.Hash == blockHash {
163 if ok, err := blockNode.BlockWitness.Test(uint32(nodeOrder)); err != nil && ok {
164 if err := c.updateBlockSignature(&blockHash, nodeOrder, nil); err != nil {
174 // SignBlock signing the block if current node is consensus node
175 func (c *Chain) SignBlock(block *types.Block) ([]byte, error) {
176 xprv := config.CommonConfig.PrivateKey()
177 xpub := [64]byte(xprv.XPub())
178 node, err := c.consensusNodeManager.getConsensusNode(&block.PreviousBlockHash, hex.EncodeToString(xpub[:]))
179 if err != nil && err != errNotFoundConsensusNode {
187 blockNodes := c.consensusNodeManager.blockIndex.NodesByHeight(block.Height)
188 for _, blockNode := range blockNodes {
189 // Has already signed the same height block
190 if ok, err := blockNode.BlockWitness.Test(uint32(node.Order)); err != nil && ok {
195 signature := block.Witness[node.Order]
196 if len(signature) == 0 {
197 signature = xprv.Sign(block.Hash().Bytes())
198 block.Witness[node.Order] = signature
200 return signature, nil
203 func (c *Chain) updateBlockSignature(blockHash *bc.Hash, nodeOrder uint64, signature []byte) error {
204 blockNode := c.consensusNodeManager.blockIndex.GetNode(blockHash)
205 if len(signature) != 0 {
206 if err := blockNode.BlockWitness.Set(uint32(nodeOrder)); err != nil {
210 if err := blockNode.BlockWitness.Clean(uint32(nodeOrder)); err != nil {
215 block, err := c.store.GetBlock(blockHash)
220 block.Witness[nodeOrder] = signature
221 txStatus, err := c.consensusNodeManager.store.GetTransactionStatus(blockHash)
226 return c.consensusNodeManager.store.SaveBlock(block, txStatus)