OSDN Git Service

modify function name
[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)
34         if err != nil {
35                 return false
36         }
37
38         signCount := 0
39         for i := 0; i < len(consensusNodes); i++ {
40                 if blockNode.BlockWitness[i] != nil {
41                         signCount++
42                 }
43         }
44
45         return signCount > len(consensusNodes)*2/3
46 }
47
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)
51         if err != nil {
52                 return nil, err
53         }
54         return c.consensusNodeManager.getVoteResult(state.CalcVoteSeq(blockNode.Height), blockNode)
55 }
56
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)
60         if err != nil {
61                 return false, err
62         }
63         return xPub == pubKey, nil
64 }
65
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)
69 }
70
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)
76         if err != nil {
77                 return err
78         }
79
80         // save the signature if the block is not exist
81         if blockNode == nil {
82                 cacheKey := signCacheKey(blockHash.String(), xpubStr)
83                 c.signatureCache.Add(cacheKey, signature)
84                 return nil
85         }
86
87         consensusNode, err := c.consensusNodeManager.getConsensusNode(blockNode.Parent, xpubStr)
88         if err != nil {
89                 return err
90         }
91
92         if blockNode.BlockWitness[int64(consensusNode.Order)] != nil {
93                 return nil
94         }
95
96         c.cond.L.Lock()
97         defer c.cond.L.Unlock()
98         if err := c.checkNodeSign(blockNode.BlockHeader(), consensusNode, signature); err != nil {
99                 return err
100         }
101
102         if err := c.updateBlockSignature(blockNode, consensusNode.Order, signature); err != nil {
103                 return err
104         }
105         return c.eventDispatcher.Post(event.BlockSignatureEvent{BlockHash: *blockHash, Signature: signature, XPub: xPub})
106 }
107
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)
113         if err != nil {
114                 return err
115         }
116
117         hasBlockerSign := false
118         blockHash := block.Hash()
119         for pubKey, node := range consensusNodeMap {
120                 if len(block.Witness) <= int(node.Order) {
121                         continue
122                 }
123
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))
128                         } else {
129                                 continue
130                         }
131                 }
132
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)
136                         continue
137                 } else if err != nil {
138                         return err
139                 }
140
141                 isBlocker, err := c.IsBlocker(&block.PreviousBlockHash, pubKey, block.Timestamp)
142                 if err != nil {
143                         return err
144                 }
145
146                 if isBlocker {
147                         hasBlockerSign = true
148                 }
149
150         }
151
152         if !hasBlockerSign {
153                 return errors.New("the block has no signature of the blocker")
154         }
155         return nil
156 }
157
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
161         }
162
163         blockHashes, err := c.consensusNodeManager.store.GetBlockHashesByHeight(bh.Height)
164         if err != nil {
165                 return err
166         }
167
168         for _, blockHash := range blockHashes {
169                 if *blockHash == bh.Hash() {
170                         continue
171                 }
172
173                 blockNode, err := c.store.GetBlockNode(blockHash)
174                 if err != nil {
175                         return err
176                 }
177
178                 consensusNode, err := c.consensusNodeManager.getConsensusNode(blockNode.Parent, consensusNode.XPub.String())
179                 if err != nil && err != errNotFoundConsensusNode {
180                         return err
181                 }
182
183                 if err == errNotFoundConsensusNode {
184                         continue
185                 }
186
187                 if blockNode.BlockWitness[consensusNode.Order] != nil {
188                         return errDoubleSignBlock
189                 }
190         }
191         return nil
192 }
193
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 {
200                 return nil, nil
201         } else if err != nil {
202                 return nil, err
203         }
204
205         c.cond.L.Lock()
206         defer c.cond.L.Unlock()
207         //check double sign in same block height
208         blockHashes, err := c.consensusNodeManager.store.GetBlockHashesByHeight(block.Height)
209         if err != nil {
210                 return nil, err
211         }
212
213         for _, hash := range blockHashes {
214                 blockNode, err := c.consensusNodeManager.store.GetBlockNode(hash)
215                 if err != nil {
216                         return nil, err
217                 }
218
219                 // Has already signed the same height block
220                 if blockNode.BlockWitness[int64(node.Order)] != nil {
221                         return nil, nil
222                 }
223         }
224
225         blockNode, err := c.store.GetBlockNode(&block.PreviousBlockHash)
226         if err != nil {
227                 return nil, err
228         }
229
230         for {
231                 if blockNode.Height <= c.bestIrreversibleNode.Height {
232                         return nil, errSignForkChain
233                 }
234
235                 if _, err := c.store.GetBlockHashByHeight(block.Height); err != nil {
236                         break
237                 }
238
239                 blockNode, err = c.store.GetBlockNode(blockNode.Parent)
240                 if err != nil {
241                         return nil, err
242                 }
243         }
244
245         signature := block.Get(node.Order)
246         if len(signature) == 0 {
247                 signature = xprv.Sign(block.Hash().Bytes())
248                 block.Set(node.Order, signature)
249         }
250         return signature, nil
251 }
252
253 func (c *Chain) updateBlockSignature(blockNode *state.BlockNode, nodeOrder uint64, signature []byte) error {
254         blockHeader, err := c.store.GetBlockHeader(&blockNode.Hash)
255         if err != nil {
256                 return err
257         }
258
259         blockHeader.Set(nodeOrder, signature)
260
261         if err := c.store.SaveBlockHeader(blockHeader); err != nil {
262                 return err
263         }
264
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 {
267                         return err
268                 }
269
270                 c.bestIrreversibleNode = blockNode
271         }
272         return nil
273 }