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 {
75 defer c.cond.L.Unlock()
76 if err := c.checkNodeSign(blockNode.BlockHeader(), consensusNode, signature); err != nil {
80 if err := c.updateBlockSignature(blockNode, consensusNode.Order, signature); err != nil {
83 return c.eventDispatcher.Post(event.BlockSignatureEvent{BlockHash: *blockHash, Signature: signature, XPub: xPub})
86 // validateSign verify the signatures of block, and return the number of correct signature
87 // if some signature is invalid, they will be reset to nil
88 // if the block has not the signature of blocker, it will return error
89 func (c *Chain) validateSign(block *types.Block) error {
90 consensusNodeMap, err := c.consensusNodeManager.getConsensusNodes(&block.PreviousBlockHash)
95 hasBlockerSign := false
96 blockHash := block.Hash()
97 for pubKey, node := range consensusNodeMap {
98 if len(block.Witness) <= int(node.Order) {
102 if block.Witness[node.Order] == nil {
103 cachekey := signCacheKey(blockHash.String(), pubKey)
104 if signature, ok := c.signatureCache.Get(cachekey); ok {
105 block.Witness[node.Order] = signature.([]byte)
111 if err := c.checkNodeSign(&block.BlockHeader, node, block.Witness[node.Order]); err == errDoubleSignBlock {
112 log.WithFields(log.Fields{"module": logModule, "blockHash": blockHash.String(), "pubKey": pubKey}).Warn("the consensus node double sign the same height of different block")
113 block.Witness[node.Order] = nil
115 } else if err != nil {
119 isBlocker, err := c.consensusNodeManager.isBlocker(&block.PreviousBlockHash, pubKey, block.Timestamp)
125 hasBlockerSign = true
131 return errors.New("the block has no signature of the blocker")
136 func (c *Chain) checkNodeSign(bh *types.BlockHeader, consensusNode *state.ConsensusNode, signature []byte) error {
137 if !consensusNode.XPub.Verify(bh.Hash().Bytes(), signature) {
138 return errInvalidSignature
141 blockNodes := c.consensusNodeManager.blockIndex.NodesByHeight(bh.Height)
142 for _, blockNode := range blockNodes {
143 if blockNode.Hash == bh.Hash() {
147 consensusNode, err := c.consensusNodeManager.getConsensusNode(&blockNode.Parent.Hash, consensusNode.XPub.String())
148 if err != nil && err != errNotFoundConsensusNode {
152 if err == errNotFoundConsensusNode {
156 if ok, err := blockNode.BlockWitness.Test(uint32(consensusNode.Order)); err == nil && ok {
157 return errDoubleSignBlock
163 // SignBlock signing the block if current node is consensus node
164 func (c *Chain) SignBlock(block *types.Block) ([]byte, error) {
165 xprv := config.CommonConfig.PrivateKey()
166 xpubStr := xprv.XPub().String()
167 node, err := c.consensusNodeManager.getConsensusNode(&block.PreviousBlockHash, xpubStr)
168 if err == errNotFoundConsensusNode {
170 } else if err != nil {
175 defer c.cond.L.Unlock()
176 //check double sign in same block height
177 blockNodes := c.consensusNodeManager.blockIndex.NodesByHeight(block.Height)
178 for _, blockNode := range blockNodes {
179 // Has already signed the same height block
180 if ok, err := blockNode.BlockWitness.Test(uint32(node.Order)); err == nil && ok {
185 for blockNode := c.index.GetNode(&block.PreviousBlockHash); !c.index.InMainchain(blockNode.Hash); blockNode = blockNode.Parent {
186 if blockNode.Height <= c.bestIrreversibleNode.Height {
187 return nil, errSignForkChain
191 signature := block.Witness[node.Order]
192 if len(signature) == 0 {
193 signature = xprv.Sign(block.Hash().Bytes())
194 block.Witness[node.Order] = signature
196 return signature, nil
199 func (c *Chain) updateBlockSignature(blockNode *state.BlockNode, nodeOrder uint64, signature []byte) error {
200 if err := blockNode.BlockWitness.Set(uint32(nodeOrder)); err != nil {
204 block, err := c.store.GetBlock(&blockNode.Hash)
209 block.Witness[nodeOrder] = signature
210 txStatus, err := c.store.GetTransactionStatus(&blockNode.Hash)
215 if err := c.store.SaveBlock(block, txStatus); err != nil {
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