OSDN Git Service

merge with dev
[bytom/bytom.git] / protocol / block.go
1 package protocol
2
3 import (
4         log "github.com/sirupsen/logrus"
5
6         "github.com/bytom/errors"
7         "github.com/bytom/protocol/bc"
8         "github.com/bytom/protocol/bc/legacy"
9         "github.com/bytom/protocol/state"
10         "github.com/bytom/protocol/validation"
11 )
12
13 var (
14         // ErrBadBlock is returned when a block is invalid.
15         ErrBadBlock = errors.New("invalid block")
16
17         // ErrStaleState is returned when the Chain does not have a current
18         // blockchain state.
19         ErrStaleState = errors.New("stale blockchain state")
20
21         // ErrBadStateRoot is returned when the computed assets merkle root
22         // disagrees with the one declared in a block header.
23         ErrBadStateRoot = errors.New("invalid state merkle root")
24 )
25
26 func (c *Chain) BlockExist(hash *bc.Hash) bool {
27         return c.orphanManage.BlockExist(hash) || c.store.BlockExist(hash)
28 }
29
30 func (c *Chain) GetBlockByHash(hash *bc.Hash) (*legacy.Block, error) {
31         return c.store.GetBlock(hash)
32 }
33
34 func (c *Chain) GetBlockByHeight(height uint64) (*legacy.Block, error) {
35         c.state.cond.L.Lock()
36         hash, ok := c.state.mainChain[height]
37         c.state.cond.L.Unlock()
38         if !ok {
39                 return nil, errors.New("can't find block in given hight")
40         }
41         return c.GetBlockByHash(hash)
42 }
43
44 // ValidateBlock validates an incoming block in advance of applying it
45 // to a snapshot (with ApplyValidBlock) and committing it to the
46 // blockchain (with CommitAppliedBlock).
47 func (c *Chain) ValidateBlock(block, prev *legacy.Block) error {
48         blockEnts := legacy.MapBlock(block)
49         prevEnts := legacy.MapBlock(prev)
50         if err := validation.ValidateBlock(blockEnts, prevEnts); err != nil {
51                 return errors.Sub(ErrBadBlock, err)
52         }
53         return nil
54 }
55
56 func (c *Chain) ConnectBlock(block *legacy.Block) error {
57         c.state.cond.L.Lock()
58         defer c.state.cond.L.Unlock()
59         return c.connectBlock(block)
60 }
61
62 func (c *Chain) connectBlock(block *legacy.Block) error {
63         newSnapshot := state.Copy(c.state.snapshot)
64         if err := newSnapshot.ApplyBlock(legacy.MapBlock(block)); err != nil {
65                 return err
66         }
67
68         blockHash := block.Hash()
69         if err := c.setState(block, newSnapshot, map[uint64]*bc.Hash{block.Height: &blockHash}); err != nil {
70                 return err
71         }
72
73         for _, tx := range block.Transactions {
74                 c.txPool.RemoveTransaction(&tx.Tx.ID)
75         }
76         return nil
77 }
78
79 func (c *Chain) getReorganizeBlocks(block *legacy.Block) ([]*legacy.Block, []*legacy.Block) {
80         attachBlocks := []*legacy.Block{}
81         detachBlocks := []*legacy.Block{}
82         ancestor := block
83
84         for !c.inMainchain(ancestor) {
85                 attachBlocks = append([]*legacy.Block{ancestor}, attachBlocks...)
86                 ancestor, _ = c.GetBlockByHash(&ancestor.PreviousBlockHash)
87         }
88
89         for d := c.state.block; d.Hash() != ancestor.Hash(); d, _ = c.GetBlockByHash(&d.PreviousBlockHash) {
90                 detachBlocks = append(detachBlocks, d)
91         }
92
93         return attachBlocks, detachBlocks
94 }
95
96 func (c *Chain) reorganizeChain(block *legacy.Block) error {
97         attachBlocks, detachBlocks := c.getReorganizeBlocks(block)
98         newSnapshot := state.Copy(c.state.snapshot)
99         chainChanges := map[uint64]*bc.Hash{}
100
101         for _, d := range detachBlocks {
102                 if err := newSnapshot.DetachBlock(legacy.MapBlock(d)); err != nil {
103                         return err
104                 }
105         }
106
107         for _, a := range attachBlocks {
108                 if err := newSnapshot.ApplyBlock(legacy.MapBlock(a)); err != nil {
109                         return err
110                 }
111                 aHash := a.Hash()
112                 chainChanges[a.Height] = &aHash
113         }
114
115         return c.setState(block, newSnapshot, chainChanges)
116 }
117
118 func (c *Chain) SaveBlock(block *legacy.Block) error {
119         preBlock, _ := c.GetBlockByHash(&block.PreviousBlockHash)
120         if err := c.ValidateBlock(block, preBlock); err != nil {
121                 return err
122         }
123         if err := c.store.SaveBlock(block); err != nil {
124                 return err
125         }
126         blockHash := block.Hash()
127         log.WithFields(log.Fields{"height": block.Height, "hash": blockHash.String()}).Info("Block saved on disk")
128         return nil
129 }
130
131 func (c *Chain) findBestChainTail(block *legacy.Block) (bestBlock *legacy.Block) {
132         bestBlock = block
133         blockHash := block.Hash()
134         preorphans, ok := c.orphanManage.preOrphans[blockHash]
135         if !ok {
136                 return
137         }
138
139         for _, preorphan := range preorphans {
140                 orphanBlock, ok := c.orphanManage.Get(preorphan)
141                 if !ok {
142                         continue
143                 }
144
145                 if err := c.SaveBlock(orphanBlock); err != nil {
146                         log.WithFields(log.Fields{
147                                 "height": block.Height,
148                                 "hash":   blockHash.String(),
149                         }).Errorf("findBestChainTail fail on save block %v", err)
150                         continue
151                 }
152
153                 if subResult := c.findBestChainTail(orphanBlock); subResult.Height > bestBlock.Height {
154                         bestBlock = subResult
155                 }
156         }
157
158         c.orphanManage.Delete(&blockHash)
159         return
160 }
161
162 func (c *Chain) ProcessBlock(block *legacy.Block) (bool, error) {
163         blockHash := block.Hash()
164         if c.BlockExist(&blockHash) {
165                 log.WithField("hash", blockHash.String()).Info("Skip process due to block already been handled")
166                 return false, nil
167         }
168         if !c.store.BlockExist(&block.PreviousBlockHash) {
169                 c.orphanManage.Add(block)
170                 return true, nil
171         }
172         if err := c.SaveBlock(block); err != nil {
173                 return false, err
174         }
175
176         bestBlock := c.findBestChainTail(block)
177         c.state.cond.L.Lock()
178         if c.state.block.Hash() == bestBlock.PreviousBlockHash {
179                 defer c.state.cond.L.Unlock()
180                 return false, c.connectBlock(bestBlock)
181         }
182
183         if bestBlock.Height > c.state.height && bestBlock.Bits >= c.state.block.Bits {
184                 defer c.state.cond.L.Unlock()
185                 return false, c.reorganizeChain(bestBlock)
186         }
187         c.state.cond.L.Unlock()
188         return false, nil
189 }