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 // GetVoteResultByHash return vote result by block hash
49 func (c *Chain) GetVoteResultByHash(blockHash *bc.Hash) (*state.VoteResult, error) {
50 blockNode := c.index.GetNode(blockHash)
51 return c.consensusNodeManager.getVoteResult(state.CalcVoteSeq(blockNode.Height), blockNode)
54 // IsBlocker returns whether the consensus node is a blocker at the specified time
55 func (c *Chain) IsBlocker(prevBlockHash *bc.Hash, pubkey string, timeStamp uint64) (bool, error) {
56 return c.consensusNodeManager.isBlocker(prevBlockHash, pubkey, timeStamp)
59 // ProcessBlockSignature process the received block signature messages
60 // return whether a block become irreversible, if so, the chain module must update status
61 func (c *Chain) ProcessBlockSignature(signature, xPub []byte, blockHash *bc.Hash) error {
62 xpubStr := hex.EncodeToString(xPub[:])
63 blockNode := c.index.GetNode(blockHash)
64 // save the signature if the block is not exist
66 cacheKey := signCacheKey(blockHash.String(), xpubStr)
67 c.signatureCache.Add(cacheKey, signature)
71 consensusNode, err := c.consensusNodeManager.getConsensusNode(&blockNode.Parent.Hash, xpubStr)
76 if exist, _ := blockNode.BlockWitness.Test(uint32(consensusNode.Order)); exist {
81 defer c.cond.L.Unlock()
82 if err := c.checkNodeSign(blockNode.BlockHeader(), consensusNode, signature); err != nil {
86 if err := c.updateBlockSignature(blockNode, consensusNode.Order, signature); err != nil {
89 return c.eventDispatcher.Post(event.BlockSignatureEvent{BlockHash: *blockHash, Signature: signature, XPub: xPub})
92 // validateSign verify the signatures of block, and return the number of correct signature
93 // if some signature is invalid, they will be reset to nil
94 // if the block has not the signature of blocker, it will return error
95 func (c *Chain) validateSign(block *types.Block) error {
96 consensusNodeMap, err := c.consensusNodeManager.getConsensusNodes(&block.PreviousBlockHash)
101 hasBlockerSign := false
102 blockHash := block.Hash()
103 for pubKey, node := range consensusNodeMap {
104 if len(block.Witness) <= int(node.Order) {
108 if block.Witness[node.Order] == nil {
109 cachekey := signCacheKey(blockHash.String(), pubKey)
110 if signature, ok := c.signatureCache.Get(cachekey); ok {
111 block.Witness[node.Order] = signature.([]byte)
117 if err := c.checkNodeSign(&block.BlockHeader, node, block.Witness[node.Order]); err == errDoubleSignBlock {
118 log.WithFields(log.Fields{"module": logModule, "blockHash": blockHash.String(), "pubKey": pubKey}).Warn("the consensus node double sign the same height of different block")
119 block.Witness[node.Order] = nil
121 } else if err != nil {
125 isBlocker, err := c.consensusNodeManager.isBlocker(&block.PreviousBlockHash, pubKey, block.Timestamp)
131 hasBlockerSign = true
137 return errors.New("the block has no signature of the blocker")
142 func (c *Chain) checkNodeSign(bh *types.BlockHeader, consensusNode *state.ConsensusNode, signature []byte) error {
143 if !consensusNode.XPub.Verify(bh.Hash().Bytes(), signature) {
144 return errInvalidSignature
147 blockNodes := c.consensusNodeManager.blockIndex.NodesByHeight(bh.Height)
148 for _, blockNode := range blockNodes {
149 if blockNode.Hash == bh.Hash() {
153 consensusNode, err := c.consensusNodeManager.getConsensusNode(&blockNode.Parent.Hash, consensusNode.XPub.String())
154 if err != nil && err != errNotFoundConsensusNode {
158 if err == errNotFoundConsensusNode {
162 if ok, err := blockNode.BlockWitness.Test(uint32(consensusNode.Order)); err == nil && ok {
163 return errDoubleSignBlock
169 // SignBlock signing the block if current node is consensus node
170 func (c *Chain) SignBlock(block *types.Block) ([]byte, error) {
171 xprv := config.CommonConfig.PrivateKey()
172 xpubStr := xprv.XPub().String()
173 node, err := c.consensusNodeManager.getConsensusNode(&block.PreviousBlockHash, xpubStr)
174 if err == errNotFoundConsensusNode {
176 } else if err != nil {
181 defer c.cond.L.Unlock()
182 //check double sign in same block height
183 blockNodes := c.consensusNodeManager.blockIndex.NodesByHeight(block.Height)
184 for _, blockNode := range blockNodes {
185 // Has already signed the same height block
186 if ok, err := blockNode.BlockWitness.Test(uint32(node.Order)); err == nil && ok {
191 for blockNode := c.index.GetNode(&block.PreviousBlockHash); !c.index.InMainchain(blockNode.Hash); blockNode = blockNode.Parent {
192 if blockNode.Height <= c.bestIrreversibleNode.Height {
193 return nil, errSignForkChain
197 signature := block.Witness[node.Order]
198 if len(signature) == 0 {
199 signature = xprv.Sign(block.Hash().Bytes())
200 block.Witness[node.Order] = signature
202 return signature, nil
205 func (c *Chain) updateBlockSignature(blockNode *state.BlockNode, nodeOrder uint64, signature []byte) error {
206 if err := blockNode.BlockWitness.Set(uint32(nodeOrder)); err != nil {
210 block, err := c.store.GetBlock(&blockNode.Hash)
215 block.Witness[nodeOrder] = signature
216 txStatus, err := c.store.GetTransactionStatus(&blockNode.Hash)
221 if err := c.store.SaveBlock(block, txStatus); err != nil {
225 if c.isIrreversible(blockNode) && blockNode.Height > c.bestIrreversibleNode.Height {
226 if err := c.store.SaveChainStatus(c.bestNode, blockNode, state.NewUtxoViewpoint(), []*state.VoteResult{}); err != nil {
230 c.bestIrreversibleNode = blockNode