7 log "github.com/sirupsen/logrus"
9 "github.com/vapor/config"
10 "github.com/vapor/errors"
11 "github.com/vapor/event"
12 "github.com/vapor/protocol/bc"
13 "github.com/vapor/protocol/bc/types"
14 "github.com/vapor/protocol/state"
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")
25 errSignForkChain = errors.New("can not sign fork before the irreversible block")
28 func signCacheKey(blockHash, pubkey string) string {
29 return fmt.Sprintf("%s:%s", blockHash, pubkey)
32 func (c *Chain) isIrreversible(blockNode *state.BlockNode) bool {
33 consensusNodes, err := c.consensusNodeManager.getConsensusNodes(blockNode.Parent)
39 for i := 0; i < len(consensusNodes); i++ {
40 if blockNode.BlockWitness[i] != nil {
45 return signCount > len(consensusNodes)*2/3
48 // GetVoteResultByHash return vote result by block hash
49 func (c *Chain) GetVoteResultByHash(blockHash *bc.Hash) (*state.VoteResult, error) {
50 blockNode, err := c.store.GetBlockNode(blockHash)
54 return c.consensusNodeManager.getVoteResult(state.CalcVoteSeq(blockNode.Height), blockNode)
57 // IsBlocker returns whether the consensus node is a blocker at the specified time
58 func (c *Chain) IsBlocker(prevBlockHash *bc.Hash, pubKey string, timeStamp uint64) (bool, error) {
59 xPub, err := c.consensusNodeManager.getBlocker(prevBlockHash, timeStamp)
63 return xPub == pubKey, nil
66 // GetBlock return blocker by specified timestamp
67 func (c *Chain) GetBlocker(prevBlockHash *bc.Hash, timestamp uint64) (string, error) {
68 return c.consensusNodeManager.getBlocker(prevBlockHash, timestamp)
71 // ProcessBlockSignature process the received block signature messages
72 // return whether a block become irreversible, if so, the chain module must update status
73 func (c *Chain) ProcessBlockSignature(signature, xPub []byte, blockHash *bc.Hash) error {
74 xpubStr := hex.EncodeToString(xPub[:])
75 blockNode, err := c.store.GetBlockNode(blockHash)
80 // save the signature if the block is not exist
82 cacheKey := signCacheKey(blockHash.String(), xpubStr)
83 c.signatureCache.Add(cacheKey, signature)
87 consensusNode, err := c.consensusNodeManager.getConsensusNode(blockNode.Parent, xpubStr)
92 if blockNode.BlockWitness[int64(consensusNode.Order)] != nil {
97 defer c.cond.L.Unlock()
98 if err := c.checkNodeSign(blockNode.BlockHeader(), consensusNode, signature); err != nil {
102 if err := c.updateBlockSignature(blockNode, consensusNode.Order, signature); err != nil {
105 return c.eventDispatcher.Post(event.BlockSignatureEvent{BlockHash: *blockHash, Signature: signature, XPub: xPub})
108 // validateSign verify the signatures of block, and return the number of correct signature
109 // if some signature is invalid, they will be reset to nil
110 // if the block has not the signature of blocker, it will return error
111 func (c *Chain) validateSign(block *types.Block) error {
112 consensusNodeMap, err := c.consensusNodeManager.getConsensusNodes(&block.PreviousBlockHash)
117 hasBlockerSign := false
118 blockHash := block.Hash()
119 for pubKey, node := range consensusNodeMap {
120 if len(block.Witness) <= int(node.Order) {
124 if block.Get(node.Order) == nil {
125 cachekey := signCacheKey(blockHash.String(), pubKey)
126 if signature, ok := c.signatureCache.Get(cachekey); ok {
127 block.Set(node.Order, signature.([]byte))
133 if err := c.checkNodeSign(&block.BlockHeader, node, block.Get(node.Order)); err == errDoubleSignBlock {
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.Delete(node.Order)
137 } else if err != nil {
141 isBlocker, err := c.IsBlocker(&block.PreviousBlockHash, pubKey, block.Timestamp)
147 hasBlockerSign = true
153 return errors.New("the block has no signature of the blocker")
158 func (c *Chain) checkNodeSign(bh *types.BlockHeader, consensusNode *state.ConsensusNode, signature []byte) error {
159 if !consensusNode.XPub.Verify(bh.Hash().Bytes(), signature) {
160 return errInvalidSignature
163 blockHashes, err := c.consensusNodeManager.store.GetBlockHashesByHeight(bh.Height)
168 for _, blockHash := range blockHashes {
169 if *blockHash == bh.Hash() {
173 blockNode, err := c.store.GetBlockNode(blockHash)
178 consensusNode, err := c.consensusNodeManager.getConsensusNode(blockNode.Parent, consensusNode.XPub.String())
179 if err != nil && err != errNotFoundConsensusNode {
183 if err == errNotFoundConsensusNode {
187 if blockNode.BlockWitness[consensusNode.Order] != nil {
188 return errDoubleSignBlock
194 // SignBlock signing the block if current node is consensus node
195 func (c *Chain) SignBlock(block *types.Block) ([]byte, error) {
196 xprv := config.CommonConfig.PrivateKey()
197 xpubStr := xprv.XPub().String()
198 node, err := c.consensusNodeManager.getConsensusNode(&block.PreviousBlockHash, xpubStr)
199 if err == errNotFoundConsensusNode {
201 } else if err != nil {
206 defer c.cond.L.Unlock()
207 //check double sign in same block height
208 blockHashes, err := c.consensusNodeManager.store.GetBlockHashesByHeight(block.Height)
213 for _, hash := range blockHashes {
214 blockNode, err := c.consensusNodeManager.store.GetBlockNode(hash)
219 // Has already signed the same height block
220 if blockNode.BlockWitness[int64(node.Order)] != nil {
225 blockNode, err := c.store.GetBlockNode(&block.PreviousBlockHash)
231 if blockNode.Height <= c.bestIrreversibleNode.Height {
232 return nil, errSignForkChain
235 if _, err := c.store.GetBlockHashByHeight(block.Height); err != nil {
239 blockNode, err = c.store.GetBlockNode(blockNode.Parent)
245 signature := block.Get(node.Order)
246 if len(signature) == 0 {
247 signature = xprv.Sign(block.Hash().Bytes())
248 block.Set(node.Order, signature)
250 return signature, nil
253 func (c *Chain) updateBlockSignature(blockNode *state.BlockNode, nodeOrder uint64, signature []byte) error {
254 blockHeader, err := c.store.GetBlockHeader(&blockNode.Hash)
259 blockHeader.Set(nodeOrder, signature)
261 if err := c.store.SaveBlockHeader(blockHeader); err != nil {
265 if c.isIrreversible(blockNode) && blockNode.Height > c.bestIrreversibleNode.Height {
266 if err := c.store.SaveChainStatus(c.bestNode, blockNode, state.NewUtxoViewpoint(), []*state.VoteResult{}); err != nil {
270 c.bestIrreversibleNode = blockNode