OSDN Git Service

split block (#180)
[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 // 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)
52 }
53
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         xPub, err := c.consensusNodeManager.getBlocker(prevBlockHash, timeStamp)
57         if err != nil {
58                 return false, err
59         }
60         return xPub == pubKey, nil
61 }
62
63 // GetBlock return blocker by specified timestamp
64 func (c *Chain) GetBlocker(prevBlockHash *bc.Hash, timestamp uint64) (string, error) {
65         return c.consensusNodeManager.getBlocker(prevBlockHash, timestamp)
66 }
67
68 // ProcessBlockSignature process the received block signature messages
69 // return whether a block become irreversible, if so, the chain module must update status
70 func (c *Chain) ProcessBlockSignature(signature, xPub []byte, blockHash *bc.Hash) error {
71         xpubStr := hex.EncodeToString(xPub[:])
72         blockNode := c.index.GetNode(blockHash)
73         // save the signature if the block is not exist
74         if blockNode == nil {
75                 cacheKey := signCacheKey(blockHash.String(), xpubStr)
76                 c.signatureCache.Add(cacheKey, signature)
77                 return nil
78         }
79
80         consensusNode, err := c.consensusNodeManager.getConsensusNode(&blockNode.Parent.Hash, xpubStr)
81         if err != nil {
82                 return err
83         }
84
85         if exist, _ := blockNode.BlockWitness.Test(uint32(consensusNode.Order)); exist {
86                 return nil
87         }
88
89         c.cond.L.Lock()
90         defer c.cond.L.Unlock()
91         if err := c.checkNodeSign(blockNode.BlockHeader(), consensusNode, signature); err != nil {
92                 return err
93         }
94
95         if err := c.updateBlockSignature(blockNode, consensusNode.Order, signature); err != nil {
96                 return err
97         }
98         return c.eventDispatcher.Post(event.BlockSignatureEvent{BlockHash: *blockHash, Signature: signature, XPub: xPub})
99 }
100
101 // validateSign verify the signatures of block, and return the number of correct signature
102 // if some signature is invalid, they will be reset to nil
103 // if the block has not the signature of blocker, it will return error
104 func (c *Chain) validateSign(block *types.Block) error {
105         consensusNodeMap, err := c.consensusNodeManager.getConsensusNodes(&block.PreviousBlockHash)
106         if err != nil {
107                 return err
108         }
109
110         hasBlockerSign := false
111         blockHash := block.Hash()
112         for pubKey, node := range consensusNodeMap {
113                 if len(block.Witness) <= int(node.Order) {
114                         continue
115                 }
116
117                 if block.Get(node.Order) == nil {
118                         cachekey := signCacheKey(blockHash.String(), pubKey)
119                         if signature, ok := c.signatureCache.Get(cachekey); ok {
120                                 block.Set(node.Order, signature.([]byte))
121                         } else {
122                                 continue
123                         }
124                 }
125
126                 if err := c.checkNodeSign(&block.BlockHeader, node, block.Get(node.Order)); err == errDoubleSignBlock {
127                         log.WithFields(log.Fields{"module": logModule, "blockHash": blockHash.String(), "pubKey": pubKey}).Warn("the consensus node double sign the same height of different block")
128                         block.Delete(node.Order)
129                         continue
130                 } else if err != nil {
131                         return err
132                 }
133
134                 isBlocker, err := c.IsBlocker(&block.PreviousBlockHash, pubKey, block.Timestamp)
135                 if err != nil {
136                         return err
137                 }
138
139                 if isBlocker {
140                         hasBlockerSign = true
141                 }
142
143         }
144
145         if !hasBlockerSign {
146                 return errors.New("the block has no signature of the blocker")
147         }
148         return nil
149 }
150
151 func (c *Chain) checkNodeSign(bh *types.BlockHeader, consensusNode *state.ConsensusNode, signature []byte) error {
152         if !consensusNode.XPub.Verify(bh.Hash().Bytes(), signature) {
153                 return errInvalidSignature
154         }
155
156         blockNodes := c.consensusNodeManager.blockIndex.NodesByHeight(bh.Height)
157         for _, blockNode := range blockNodes {
158                 if blockNode.Hash == bh.Hash() {
159                         continue
160                 }
161
162                 consensusNode, err := c.consensusNodeManager.getConsensusNode(&blockNode.Parent.Hash, consensusNode.XPub.String())
163                 if err != nil && err != errNotFoundConsensusNode {
164                         return err
165                 }
166
167                 if err == errNotFoundConsensusNode {
168                         continue
169                 }
170
171                 if ok, err := blockNode.BlockWitness.Test(uint32(consensusNode.Order)); err == nil && ok {
172                         return errDoubleSignBlock
173                 }
174         }
175         return nil
176 }
177
178 // SignBlock signing the block if current node is consensus node
179 func (c *Chain) SignBlock(block *types.Block) ([]byte, error) {
180         xprv := config.CommonConfig.PrivateKey()
181         xpubStr := xprv.XPub().String()
182         node, err := c.consensusNodeManager.getConsensusNode(&block.PreviousBlockHash, xpubStr)
183         if err == errNotFoundConsensusNode {
184                 return nil, nil
185         } else if err != nil {
186                 return nil, err
187         }
188
189         c.cond.L.Lock()
190         defer c.cond.L.Unlock()
191         //check double sign in same block height
192         blockNodes := c.consensusNodeManager.blockIndex.NodesByHeight(block.Height)
193         for _, blockNode := range blockNodes {
194                 // Has already signed the same height block
195                 if ok, err := blockNode.BlockWitness.Test(uint32(node.Order)); err == nil && ok {
196                         return nil, nil
197                 }
198         }
199
200         for blockNode := c.index.GetNode(&block.PreviousBlockHash); !c.index.InMainchain(blockNode.Hash); blockNode = blockNode.Parent {
201                 if blockNode.Height <= c.bestIrreversibleNode.Height {
202                         return nil, errSignForkChain
203                 }
204         }
205
206         signature := block.Get(node.Order)
207         if len(signature) == 0 {
208                 signature = xprv.Sign(block.Hash().Bytes())
209                 block.Set(node.Order, signature)
210         }
211         return signature, nil
212 }
213
214 func (c *Chain) updateBlockSignature(blockNode *state.BlockNode, nodeOrder uint64, signature []byte) error {
215         if err := blockNode.BlockWitness.Set(uint32(nodeOrder)); err != nil {
216                 return err
217         }
218
219         blockHeader, err := c.store.GetBlockHeader(&blockNode.Hash, blockNode.Height)
220         if err != nil {
221                 return err
222         }
223
224         blockHeader.Set(nodeOrder, signature)
225
226         if err := c.store.SaveBlockHeader(blockHeader); err != nil {
227                 return err
228         }
229
230         if c.isIrreversible(blockNode) && blockNode.Height > c.bestIrreversibleNode.Height {
231                 if err := c.store.SaveChainStatus(c.bestNode, blockNode, state.NewUtxoViewpoint(), []*state.VoteResult{}); err != nil {
232                         return err
233                 }
234
235                 c.bestIrreversibleNode = blockNode
236         }
237         return nil
238 }