OSDN Git Service

Edit bbft (#133)
[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/protocol/bc"
12         "github.com/vapor/protocol/bc/types"
13         "github.com/vapor/protocol/state"
14 )
15
16 const (
17         maxSignatureCacheSize = 10000
18 )
19
20 var (
21         errVotingOperationOverFlow = errors.New("voting operation result overflow")
22         errDoubleSignBlock         = errors.New("the consensus is double sign in same height of different block")
23         errInvalidSignature        = errors.New("the signature of block is invalid")
24 )
25
26 func signCacheKey(blockHash, pubkey string) string {
27         return fmt.Sprintf("%s:%s", blockHash, pubkey)
28 }
29
30 func (c *Chain) isIrreversible(blockNode *state.BlockNode) bool {
31         consensusNodes, err := c.consensusNodeManager.getConsensusNodes(&blockNode.Parent.Hash)
32         if err != nil {
33                 return false
34         }
35
36         signCount := 0
37         for i := 0; i < len(consensusNodes); i++ {
38                 if ok, _ := blockNode.BlockWitness.Test(uint32(i)); ok {
39                         signCount++
40                 }
41         }
42
43         return signCount > len(consensusNodes)*2/3
44 }
45
46 // NextLeaderTime returns the start time of the specified public key as the next leader node
47 func (c *Chain) IsBlocker(prevBlockHash *bc.Hash, pubkey string, timeStamp uint64) (bool, error) {
48         return c.consensusNodeManager.isBlocker(prevBlockHash, pubkey, timeStamp)
49 }
50
51 // ProcessBlockSignature process the received block signature messages
52 // return whether a block become irreversible, if so, the chain module must update status
53 func (c *Chain) ProcessBlockSignature(signature []byte, xPub [64]byte, blockHash *bc.Hash) error {
54         xpubStr := hex.EncodeToString(xPub[:])
55         blockNode := c.index.GetNode(blockHash)
56         // save the signature if the block is not exist
57         if blockNode == nil {
58                 cacheKey := signCacheKey(blockHash.String(), xpubStr)
59                 c.signatureCache.Add(cacheKey, signature)
60                 return nil
61         }
62
63         consensusNode, err := c.consensusNodeManager.getConsensusNode(&blockNode.Parent.Hash, xpubStr)
64         if err != nil {
65                 return err
66         }
67
68         if consensusNode.XPub.Verify(blockHash.Bytes(), signature) {
69                 return errInvalidSignature
70         }
71
72         isDoubleSign, err := c.checkDoubleSign(consensusNode.Order, blockNode.Height, *blockHash)
73         if err != nil {
74                 return err
75         }
76
77         if isDoubleSign {
78                 return errDoubleSignBlock
79         }
80
81         if err := c.updateBlockSignature(&blockNode.Hash, consensusNode.Order, signature); err != nil {
82                 return err
83         }
84
85         if c.isIrreversible(blockNode) && blockNode.Height > c.bestIrreversibleNode.Height {
86                 bestIrreversibleNode := c.index.GetNode(blockHash)
87                 if err := c.store.SaveChainNodeStatus(c.bestNode, bestIrreversibleNode); err != nil {
88                         return err
89                 }
90
91                 c.bestIrreversibleNode = bestIrreversibleNode
92         }
93         return nil
94 }
95
96 // validateSign verify the signatures of block, and return the number of correct signature
97 // if some signature is invalid, they will be reset to nil
98 // if the block has not the signature of blocker, it will return error
99 func (c *Chain) validateSign(block *types.Block) (uint64, error) {
100         consensusNodeMap, err := c.consensusNodeManager.getConsensusNodes(&block.PreviousBlockHash)
101         if err != nil {
102                 return 0, err
103         }
104
105         hasBlockerSign := false
106         signCount := uint64(0)
107         blockHash := block.Hash()
108         for pubKey, node := range consensusNodeMap {
109                 if len(block.Witness) <= int(node.Order) {
110                         continue
111                 }
112
113                 if block.Witness[node.Order] == nil {
114                         cachekey := signCacheKey(blockHash.String(), pubKey)
115                         if signature, ok := c.signatureCache.Get(cachekey); ok {
116                                 block.Witness[node.Order] = signature.([]byte)
117                         } else {
118                                 continue
119                         }
120                 }
121
122                 if ok := node.XPub.Verify(blockHash.Bytes(), block.Witness[node.Order]); !ok {
123                         block.Witness[node.Order] = nil
124                         continue
125                 }
126
127                 isDoubleSign, err := c.checkDoubleSign(node.Order, block.Height, block.Hash())
128                 if err != nil {
129                         return 0, err
130                 }
131
132                 if isDoubleSign {
133                         // Consensus node is signed twice with the same block height, discard the signature
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.Witness[node.Order] = nil
136                         continue
137                 }
138
139                 signCount++
140                 isBlocker, err := c.consensusNodeManager.isBlocker(&block.PreviousBlockHash, pubKey, block.Timestamp)
141                 if err != nil {
142                         return 0, err
143                 }
144
145                 if isBlocker {
146                         hasBlockerSign = true
147                 }
148
149         }
150
151         if !hasBlockerSign {
152                 return 0, errors.New("the block has no signature of the blocker")
153         }
154         return signCount, nil
155 }
156
157 func (c *Chain) checkDoubleSign(nodeOrder, blockHeight uint64, blockHash bc.Hash) (bool, error) {
158         blockNodes := c.consensusNodeManager.blockIndex.NodesByHeight(blockHeight)
159         for _, blockNode := range blockNodes {
160                 if blockNode.Hash == blockHash {
161                         continue
162                 }
163                 if ok, err := blockNode.BlockWitness.Test(uint32(nodeOrder)); err != nil && ok {
164                         if err := c.updateBlockSignature(&blockHash, nodeOrder, nil); err != nil {
165                                 return false, err
166                         }
167
168                         return true, nil
169                 }
170         }
171         return false, nil
172 }
173
174 // SignBlock signing the block if current node is consensus node
175 func (c *Chain) SignBlock(block *types.Block) ([]byte, error) {
176         xprv := config.CommonConfig.PrivateKey()
177         xpub := [64]byte(xprv.XPub())
178         node, err := c.consensusNodeManager.getConsensusNode(&block.PreviousBlockHash, hex.EncodeToString(xpub[:]))
179         if err != nil && err != errNotFoundConsensusNode {
180                 return nil, err
181         }
182
183         if node == nil {
184                 return nil, nil
185         }
186
187         blockNodes := c.consensusNodeManager.blockIndex.NodesByHeight(block.Height)
188         for _, blockNode := range blockNodes {
189                 // Has already signed the same height block
190                 if ok, err := blockNode.BlockWitness.Test(uint32(node.Order)); err != nil && ok {
191                         return nil, nil
192                 }
193         }
194
195         signature := block.Witness[node.Order]
196         if len(signature) == 0 {
197                 signature = xprv.Sign(block.Hash().Bytes())
198                 block.Witness[node.Order] = signature
199         }
200         return signature, nil
201 }
202
203 func (c *Chain) updateBlockSignature(blockHash *bc.Hash, nodeOrder uint64, signature []byte) error {
204         blockNode := c.consensusNodeManager.blockIndex.GetNode(blockHash)
205         if len(signature) != 0 {
206                 if err := blockNode.BlockWitness.Set(uint32(nodeOrder)); err != nil {
207                         return err
208                 }
209         } else {
210                 if err := blockNode.BlockWitness.Clean(uint32(nodeOrder)); err != nil {
211                         return err
212                 }
213         }
214
215         block, err := c.store.GetBlock(blockHash)
216         if err != nil {
217                 return err
218         }
219
220         block.Witness[nodeOrder] = signature
221         txStatus, err := c.consensusNodeManager.store.GetTransactionStatus(blockHash)
222         if err != nil {
223                 return err
224         }
225
226         return c.consensusNodeManager.store.SaveBlock(block, txStatus)
227 }