OSDN Git Service

8e5523b1af0eff3bf09a1e1ffb368e5325419ce6
[bytom/vapor.git] / protocol / block.go
1 package protocol
2
3 import (
4         log "github.com/sirupsen/logrus"
5
6         "github.com/vapor/errors"
7         "github.com/vapor/event"
8         "github.com/vapor/config"
9         "github.com/vapor/protocol/bc"
10         "github.com/vapor/protocol/bc/types"
11         "github.com/vapor/protocol/state"
12         "github.com/vapor/protocol/validation"
13 )
14
15 var (
16         // ErrBadBlock is returned when a block is invalid.
17         ErrBadBlock = errors.New("invalid block")
18         // ErrBadStateRoot is returned when the computed assets merkle root
19         // disagrees with the one declared in a block header.
20         ErrBadStateRoot = errors.New("invalid state merkle root")
21 )
22
23 // BlockExist check is a block in chain or orphan
24 func (c *Chain) BlockExist(hash *bc.Hash) bool {
25         return c.index.BlockExist(hash) || c.orphanManage.BlockExist(hash)
26 }
27
28 // GetBlockByHash return a block by given hash
29 func (c *Chain) GetBlockByHash(hash *bc.Hash) (*types.Block, error) {
30         return c.store.GetBlock(hash)
31 }
32
33 // GetBlockByHeight return a block header by given height
34 func (c *Chain) GetBlockByHeight(height uint64) (*types.Block, error) {
35         node := c.index.NodeByHeight(height)
36         if node == nil {
37                 return nil, errors.New("can't find block in given height")
38         }
39         return c.store.GetBlock(&node.Hash)
40 }
41
42 // GetHeaderByHash return a block header by given hash
43 func (c *Chain) GetHeaderByHash(hash *bc.Hash) (*types.BlockHeader, error) {
44         node := c.index.GetNode(hash)
45         if node == nil {
46                 return nil, errors.New("can't find block header in given hash")
47         }
48         return node.BlockHeader(), nil
49 }
50
51 // GetHeaderByHeight return a block header by given height
52 func (c *Chain) GetHeaderByHeight(height uint64) (*types.BlockHeader, error) {
53         node := c.index.NodeByHeight(height)
54         if node == nil {
55                 return nil, errors.New("can't find block header in given height")
56         }
57         return node.BlockHeader(), nil
58 }
59
60 func (c *Chain) calcReorganizeNodes(node *state.BlockNode) ([]*state.BlockNode, []*state.BlockNode) {
61         var attachNodes []*state.BlockNode
62         var detachNodes []*state.BlockNode
63
64         attachNode := node
65         for c.index.NodeByHeight(attachNode.Height) != attachNode {
66                 attachNodes = append([]*state.BlockNode{attachNode}, attachNodes...)
67                 attachNode = attachNode.Parent
68         }
69
70         detachNode := c.bestNode
71         for detachNode != attachNode {
72                 detachNodes = append(detachNodes, detachNode)
73                 detachNode = detachNode.Parent
74         }
75         return attachNodes, detachNodes
76 }
77
78 func (c *Chain) connectBlock(block *types.Block) (err error) {
79         irreversibleNode := c.bestIrreversibleNode
80         bcBlock := types.MapBlock(block)
81         if bcBlock.TransactionStatus, err = c.store.GetTransactionStatus(&bcBlock.ID); err != nil {
82                 return err
83         }
84
85         utxoView := state.NewUtxoViewpoint()
86         if err := c.store.GetTransactionsUtxo(utxoView, bcBlock.Transactions); err != nil {
87                 return err
88         }
89         if err := utxoView.ApplyBlock(bcBlock, bcBlock.TransactionStatus); err != nil {
90                 return err
91         }
92
93         voteResultMap := make(map[uint64]*state.VoteResult)
94         if err := c.bbft.ApplyBlock(voteResultMap, block); err != nil {
95                 return err
96         }
97
98         node := c.index.GetNode(&bcBlock.ID)
99         if c.bbft.isIrreversible(block) && block.Height > irreversibleNode.Height {
100                 irreversibleNode = node
101         }
102
103         if err := c.setState(node, irreversibleNode, utxoView, voteResultMap); err != nil {
104                 return err
105         }
106
107         for _, tx := range block.Transactions {
108                 c.txPool.RemoveTransaction(&tx.Tx.ID)
109         }
110         return nil
111 }
112
113 func (c *Chain) reorganizeChain(node *state.BlockNode) error {
114         attachNodes, detachNodes := c.calcReorganizeNodes(node)
115         utxoView := state.NewUtxoViewpoint()
116         voteResultMap := make(map[uint64]*state.VoteResult)
117         irreversibleNode := c.bestIrreversibleNode
118
119         for _, detachNode := range detachNodes {
120                 b, err := c.store.GetBlock(&detachNode.Hash)
121                 if err != nil {
122                         return err
123                 }
124
125                 if b.Height <= irreversibleNode.Height {
126                         return errors.New("the height of rollback block below the height of irreversible block")
127                 }
128
129                 detachBlock := types.MapBlock(b)
130                 if err := c.store.GetTransactionsUtxo(utxoView, detachBlock.Transactions); err != nil {
131                         return err
132                 }
133
134                 txStatus, err := c.GetTransactionStatus(&detachBlock.ID)
135                 if err != nil {
136                         return err
137                 }
138
139                 if err := utxoView.DetachBlock(detachBlock, txStatus); err != nil {
140                         return err
141                 }
142
143                 if err := c.bbft.DetachBlock(voteResultMap, b); err != nil {
144                         return err
145                 }
146
147                 log.WithFields(log.Fields{"module": logModule, "height": node.Height, "hash": node.Hash.String()}).Debug("detach from mainchain")
148         }
149
150         for _, attachNode := range attachNodes {
151                 b, err := c.store.GetBlock(&attachNode.Hash)
152                 if err != nil {
153                         return err
154                 }
155
156                 attachBlock := types.MapBlock(b)
157                 if err := c.store.GetTransactionsUtxo(utxoView, attachBlock.Transactions); err != nil {
158                         return err
159                 }
160
161                 txStatus, err := c.GetTransactionStatus(&attachBlock.ID)
162                 if err != nil {
163                         return err
164                 }
165
166                 if err := utxoView.ApplyBlock(attachBlock, txStatus); err != nil {
167                         return err
168                 }
169
170                 if err := c.bbft.ApplyBlock(voteResultMap, b); err != nil {
171                         return err
172                 }
173
174                 if c.bbft.isIrreversible(b) && b.Height > irreversibleNode.Height {
175                         irreversibleNode = attachNode
176                 }
177
178                 log.WithFields(log.Fields{"module": logModule, "height": node.Height, "hash": node.Hash.String()}).Debug("attach from mainchain")
179         }
180
181         return c.setState(node, irreversibleNode, utxoView, voteResultMap)
182 }
183
184 // SaveBlock will validate and save block into storage
185 func (c *Chain) saveBlock(block *types.Block) error {
186         if err := c.bbft.ValidateBlock(block); err != nil {
187                 return errors.Sub(ErrBadBlock, err)
188         }
189
190         parent := c.index.GetNode(&block.PreviousBlockHash)
191         bcBlock := types.MapBlock(block)
192         if err := validation.ValidateBlock(bcBlock, parent); err != nil {
193                 return errors.Sub(ErrBadBlock, err)
194         }
195
196         signature, err := c.bbft.SignBlock(block)
197         if err != nil {
198                 return errors.Sub(ErrBadBlock, err)
199         }
200
201         if err := c.store.SaveBlock(block, bcBlock.TransactionStatus); err != nil {
202                 return err
203         }
204
205         c.orphanManage.Delete(&bcBlock.ID)
206         node, err := state.NewBlockNode(&block.BlockHeader, parent)
207         if err != nil {
208                 return err
209         }
210
211         c.index.AddNode(node)
212
213         if len(signature) != 0 {
214                 xPub := config.CommonConfig.PrivateKey().XPub()
215                 if err := c.bbft.eventDispatcher.Post(event.BlockSignatureEvent{BlockHash: block.Hash(), Signature: signature, XPub: xPub}); err != nil {
216                         return err
217                 }
218         }
219         return nil
220 }
221
222 func (c *Chain) saveSubBlock(block *types.Block) *types.Block {
223         blockHash := block.Hash()
224         prevOrphans, ok := c.orphanManage.GetPrevOrphans(&blockHash)
225         if !ok {
226                 return block
227         }
228
229         bestBlock := block
230         for _, prevOrphan := range prevOrphans {
231                 orphanBlock, ok := c.orphanManage.Get(prevOrphan)
232                 if !ok {
233                         log.WithFields(log.Fields{"module": logModule, "hash": prevOrphan.String()}).Warning("saveSubBlock fail to get block from orphanManage")
234                         continue
235                 }
236                 if err := c.saveBlock(orphanBlock); err != nil {
237                         log.WithFields(log.Fields{"module": logModule, "hash": prevOrphan.String(), "height": orphanBlock.Height}).Warning("saveSubBlock fail to save block")
238                         continue
239                 }
240
241                 if subBestBlock := c.saveSubBlock(orphanBlock); subBestBlock.Height > bestBlock.Height {
242                         bestBlock = subBestBlock
243                 }
244         }
245         return bestBlock
246 }
247
248 type processBlockResponse struct {
249         isOrphan bool
250         err      error
251 }
252
253 type processBlockMsg struct {
254         block *types.Block
255         reply chan processBlockResponse
256 }
257
258 // ProcessBlock is the entry for chain update
259 func (c *Chain) ProcessBlock(block *types.Block) (bool, error) {
260         reply := make(chan processBlockResponse, 1)
261         c.processBlockCh <- &processBlockMsg{block: block, reply: reply}
262         response := <-reply
263         return response.isOrphan, response.err
264 }
265
266 func (c *Chain) blockProcesser() {
267         for msg := range c.processBlockCh {
268                 isOrphan, err := c.processBlock(msg.block)
269                 msg.reply <- processBlockResponse{isOrphan: isOrphan, err: err}
270         }
271 }
272
273 // ProcessBlock is the entry for handle block insert
274 func (c *Chain) processBlock(block *types.Block) (bool, error) {
275         if block.Height <= c.bestIrreversibleNode.Height {
276                 return false, errors.New("the height of block below the height of irreversible block")
277         }
278
279         blockHash := block.Hash()
280         if c.BlockExist(&blockHash) {
281                 log.WithFields(log.Fields{"module": logModule, "hash": blockHash.String(), "height": block.Height}).Info("block has been processed")
282                 return c.orphanManage.BlockExist(&blockHash), nil
283         }
284
285         parent := c.index.GetNode(&block.PreviousBlockHash)
286         if parent == nil {
287                 c.orphanManage.Add(block)
288                 return true, nil
289         }
290
291         forkPointBlock := parent
292         for !c.index.InMainchain(forkPointBlock.Hash) {
293                 forkPointBlock = forkPointBlock.Parent
294         }
295         if forkPointBlock.Height < c.bestIrreversibleNode.Height {
296                 return false, errors.New("the block impossible to be block of main chain")
297         }
298
299         if err := c.saveBlock(block); err != nil {
300                 return false, err
301         }
302
303         bestBlock := c.saveSubBlock(block)
304         bestBlockHash := bestBlock.Hash()
305         bestNode := c.index.GetNode(&bestBlockHash)
306
307         if bestNode.Parent == c.bestNode {
308                 log.WithFields(log.Fields{"module": logModule}).Debug("append block to the end of mainchain")
309                 return false, c.connectBlock(bestBlock)
310         }
311
312         if bestNode.Height > c.bestNode.Height {
313                 log.WithFields(log.Fields{"module": logModule}).Debug("start to reorganize chain")
314                 return false, c.reorganizeChain(bestNode)
315         }
316         return false, nil
317 }
318
319 func (c *Chain) ProcessBlockSignature(signature []byte, xPub [64]byte, blockHeight uint64, blockHash *bc.Hash) error {  
320         isIrreversible, err := c.bbft.ProcessBlockSignature(signature, xPub, blockHeight, blockHash)
321         if err != nil {
322                 return err
323         }
324
325         if isIrreversible && blockHeight > c.bestIrreversibleNode.Height {
326                 bestIrreversibleNode := c.index.GetNode(blockHash)
327                 if err := c.store.SaveChainNodeStatus(c.bestNode, bestIrreversibleNode); err != nil {
328                         return err
329                 }
330
331                 c.bestIrreversibleNode = bestIrreversibleNode
332         }
333         return nil
334 }