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.Hash)
39 for i := 0; i < len(consensusNodes); i++ {
40 if ok, _ := blockNode.BlockWitness.Test(uint32(i)); ok {
45 return signCount > len(consensusNodes)*2/3
48 // NextLeaderTime returns the start time of the specified public key as the next leader node
49 func (c *Chain) IsBlocker(prevBlockHash *bc.Hash, pubkey string, timeStamp uint64) (bool, error) {
50 return c.consensusNodeManager.isBlocker(prevBlockHash, pubkey, timeStamp)
53 // ProcessBlockSignature process the received block signature messages
54 // return whether a block become irreversible, if so, the chain module must update status
55 func (c *Chain) ProcessBlockSignature(signature, xPub []byte, blockHash *bc.Hash) error {
56 xpubStr := hex.EncodeToString(xPub[:])
57 blockNode := c.index.GetNode(blockHash)
58 // save the signature if the block is not exist
60 cacheKey := signCacheKey(blockHash.String(), xpubStr)
61 c.signatureCache.Add(cacheKey, signature)
65 consensusNode, err := c.consensusNodeManager.getConsensusNode(&blockNode.Parent.Hash, xpubStr)
70 if exist, _ := blockNode.BlockWitness.Test(uint32(consensusNode.Order)); exist {
74 if err := c.checkNodeSign(blockNode.BlockHeader(), consensusNode, signature); err != nil {
78 if err := c.updateBlockSignature(blockNode, consensusNode.Order, signature); err != nil {
81 return c.eventDispatcher.Post(event.BlockSignatureEvent{BlockHash: *blockHash, Signature: signature, XPub: xPub})
84 // validateSign verify the signatures of block, and return the number of correct signature
85 // if some signature is invalid, they will be reset to nil
86 // if the block has not the signature of blocker, it will return error
87 func (c *Chain) validateSign(block *types.Block) error {
88 consensusNodeMap, err := c.consensusNodeManager.getConsensusNodes(&block.PreviousBlockHash)
93 hasBlockerSign := false
94 blockHash := block.Hash()
95 for pubKey, node := range consensusNodeMap {
96 if len(block.Witness) <= int(node.Order) {
100 if block.Witness[node.Order] == nil {
101 cachekey := signCacheKey(blockHash.String(), pubKey)
102 if signature, ok := c.signatureCache.Get(cachekey); ok {
103 block.Witness[node.Order] = signature.([]byte)
109 if err := c.checkNodeSign(&block.BlockHeader, node, block.Witness[node.Order]); err == errDoubleSignBlock {
110 log.WithFields(log.Fields{"module": logModule, "blockHash": blockHash.String(), "pubKey": pubKey}).Warn("the consensus node double sign the same height of different block")
111 block.Witness[node.Order] = nil
113 } else if err != nil {
117 isBlocker, err := c.consensusNodeManager.isBlocker(&block.PreviousBlockHash, pubKey, block.Timestamp)
123 hasBlockerSign = true
129 return errors.New("the block has no signature of the blocker")
134 func (c *Chain) checkNodeSign(bh *types.BlockHeader, consensusNode *state.ConsensusNode, signature []byte) error {
135 if !consensusNode.XPub.Verify(bh.Hash().Bytes(), signature) {
136 return errInvalidSignature
139 blockNodes := c.consensusNodeManager.blockIndex.NodesByHeight(bh.Height)
140 for _, blockNode := range blockNodes {
141 if blockNode.Hash == bh.Hash() {
145 consensusNode, err := c.consensusNodeManager.getConsensusNode(&blockNode.Parent.Hash, consensusNode.XPub.String())
146 if err != nil && err != errNotFoundConsensusNode {
150 if err == errNotFoundConsensusNode {
154 if ok, err := blockNode.BlockWitness.Test(uint32(consensusNode.Order)); err == nil && ok {
155 return errDoubleSignBlock
161 // SignBlock signing the block if current node is consensus node
162 func (c *Chain) SignBlock(block *types.Block) ([]byte, error) {
163 xprv := config.CommonConfig.PrivateKey()
164 xpubStr := xprv.XPub().String()
165 node, err := c.consensusNodeManager.getConsensusNode(&block.PreviousBlockHash, xpubStr)
166 if err == errNotFoundConsensusNode {
168 } else if err != nil {
173 defer c.cond.L.Unlock()
174 //check double sign in same block height
175 blockNodes := c.consensusNodeManager.blockIndex.NodesByHeight(block.Height)
176 for _, blockNode := range blockNodes {
177 // Has already signed the same height block
178 if ok, err := blockNode.BlockWitness.Test(uint32(node.Order)); err == nil && ok {
183 for blockNode := c.index.GetNode(&block.PreviousBlockHash); !c.index.InMainchain(blockNode.Hash); blockNode = blockNode.Parent {
184 if blockNode.Height <= c.bestIrreversibleNode.Height {
185 return nil, errSignForkChain
189 signature := block.Witness[node.Order]
190 if len(signature) == 0 {
191 signature = xprv.Sign(block.Hash().Bytes())
192 block.Witness[node.Order] = signature
194 return signature, nil
197 func (c *Chain) updateBlockSignature(blockNode *state.BlockNode, nodeOrder uint64, signature []byte) error {
198 if err := blockNode.BlockWitness.Set(uint32(nodeOrder)); err != nil {
202 block, err := c.store.GetBlock(&blockNode.Hash)
207 block.Witness[nodeOrder] = signature
208 txStatus, err := c.store.GetTransactionStatus(&blockNode.Hash)
213 if err := c.store.SaveBlock(block, txStatus); err != nil {
218 defer c.cond.L.Unlock()
219 if c.isIrreversible(blockNode) && blockNode.Height > c.bestIrreversibleNode.Height {
220 if err := c.store.SaveChainStatus(c.bestNode, blockNode, state.NewUtxoViewpoint(), []*state.VoteResult{}); err != nil {
224 c.bestIrreversibleNode = blockNode