OSDN Git Service

fix detach vote (#164)
[bytom/vapor.git] / protocol / bbft.go
1 package protocol
2
3 import (
4         "encoding/hex"
5         "fmt"
6
7         log "github.com/sirupsen/logrus"
8
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"
15 )
16
17 const (
18         maxSignatureCacheSize = 10000
19 )
20
21 var (
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")
26 )
27
28 func signCacheKey(blockHash, pubkey string) string {
29         return fmt.Sprintf("%s:%s", blockHash, pubkey)
30 }
31
32 func (c *Chain) isIrreversible(blockNode *state.BlockNode) bool {
33         consensusNodes, err := c.consensusNodeManager.getConsensusNodes(&blockNode.Parent.Hash)
34         if err != nil {
35                 return false
36         }
37
38         signCount := 0
39         for i := 0; i < len(consensusNodes); i++ {
40                 if ok, _ := blockNode.BlockWitness.Test(uint32(i)); ok {
41                         signCount++
42                 }
43         }
44
45         return signCount > len(consensusNodes)*2/3
46 }
47
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)
51 }
52
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
59         if blockNode == nil {
60                 cacheKey := signCacheKey(blockHash.String(), xpubStr)
61                 c.signatureCache.Add(cacheKey, signature)
62                 return nil
63         }
64
65         consensusNode, err := c.consensusNodeManager.getConsensusNode(&blockNode.Parent.Hash, xpubStr)
66         if err != nil {
67                 return err
68         }
69
70         if exist, _ := blockNode.BlockWitness.Test(uint32(consensusNode.Order)); exist {
71                 return nil
72         }
73
74         c.cond.L.Lock()
75         defer c.cond.L.Unlock()
76         if err := c.checkNodeSign(blockNode.BlockHeader(), consensusNode, signature); err != nil {
77                 return err
78         }
79
80         if err := c.updateBlockSignature(blockNode, consensusNode.Order, signature); err != nil {
81                 return err
82         }
83         return c.eventDispatcher.Post(event.BlockSignatureEvent{BlockHash: *blockHash, Signature: signature, XPub: xPub})
84 }
85
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)
91         if err != nil {
92                 return err
93         }
94
95         hasBlockerSign := false
96         blockHash := block.Hash()
97         for pubKey, node := range consensusNodeMap {
98                 if len(block.Witness) <= int(node.Order) {
99                         continue
100                 }
101
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)
106                         } else {
107                                 continue
108                         }
109                 }
110
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
114                         continue
115                 } else if err != nil {
116                         return err
117                 }
118
119                 isBlocker, err := c.consensusNodeManager.isBlocker(&block.PreviousBlockHash, pubKey, block.Timestamp)
120                 if err != nil {
121                         return err
122                 }
123
124                 if isBlocker {
125                         hasBlockerSign = true
126                 }
127
128         }
129
130         if !hasBlockerSign {
131                 return errors.New("the block has no signature of the blocker")
132         }
133         return nil
134 }
135
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
139         }
140
141         blockNodes := c.consensusNodeManager.blockIndex.NodesByHeight(bh.Height)
142         for _, blockNode := range blockNodes {
143                 if blockNode.Hash == bh.Hash() {
144                         continue
145                 }
146
147                 consensusNode, err := c.consensusNodeManager.getConsensusNode(&blockNode.Parent.Hash, consensusNode.XPub.String())
148                 if err != nil && err != errNotFoundConsensusNode {
149                         return err
150                 }
151
152                 if err == errNotFoundConsensusNode {
153                         continue
154                 }
155
156                 if ok, err := blockNode.BlockWitness.Test(uint32(consensusNode.Order)); err == nil && ok {
157                         return errDoubleSignBlock
158                 }
159         }
160         return nil
161 }
162
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 {
169                 return nil, nil
170         } else if err != nil {
171                 return nil, err
172         }
173
174         c.cond.L.Lock()
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 {
181                         return nil, nil
182                 }
183         }
184
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
188                 }
189         }
190
191         signature := block.Witness[node.Order]
192         if len(signature) == 0 {
193                 signature = xprv.Sign(block.Hash().Bytes())
194                 block.Witness[node.Order] = signature
195         }
196         return signature, nil
197 }
198
199 func (c *Chain) updateBlockSignature(blockNode *state.BlockNode, nodeOrder uint64, signature []byte) error {
200         if err := blockNode.BlockWitness.Set(uint32(nodeOrder)); err != nil {
201                 return err
202         }
203
204         block, err := c.store.GetBlock(&blockNode.Hash)
205         if err != nil {
206                 return err
207         }
208
209         block.Witness[nodeOrder] = signature
210         txStatus, err := c.store.GetTransactionStatus(&blockNode.Hash)
211         if err != nil {
212                 return err
213         }
214
215         if err := c.store.SaveBlock(block, txStatus); err != nil {
216                 return err
217         }
218
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 {
221                         return err
222                 }
223
224                 c.bestIrreversibleNode = blockNode
225         }
226         return nil
227 }