4 log "github.com/sirupsen/logrus"
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"
14 // ErrBadBlock is returned when a block is invalid.
15 ErrBadBlock = errors.New("invalid block")
17 // ErrStaleState is returned when the Chain does not have a current
19 ErrStaleState = errors.New("stale blockchain state")
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")
26 func (c *Chain) BlockExist(hash *bc.Hash) bool {
27 return c.orphanManage.BlockExist(hash) || c.store.BlockExist(hash)
30 func (c *Chain) GetBlockByHash(hash *bc.Hash) (*legacy.Block, error) {
31 return c.store.GetBlock(hash)
34 func (c *Chain) GetBlockByHeight(height uint64) (*legacy.Block, error) {
36 hash, ok := c.state.mainChain[height]
37 c.state.cond.L.Unlock()
39 return nil, errors.New("can't find block in given hight")
41 return c.GetBlockByHash(hash)
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)
56 func (c *Chain) ConnectBlock(block *legacy.Block) error {
58 defer c.state.cond.L.Unlock()
59 return c.connectBlock(block)
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 {
68 blockHash := block.Hash()
69 if err := c.setState(block, newSnapshot, map[uint64]*bc.Hash{block.Height: &blockHash}); err != nil {
73 for _, tx := range block.Transactions {
74 c.txPool.RemoveTransaction(&tx.Tx.ID)
79 func (c *Chain) getReorganizeBlocks(block *legacy.Block) ([]*legacy.Block, []*legacy.Block) {
80 attachBlocks := []*legacy.Block{}
81 detachBlocks := []*legacy.Block{}
84 for !c.inMainchain(ancestor) {
85 attachBlocks = append([]*legacy.Block{ancestor}, attachBlocks...)
86 ancestor, _ = c.GetBlockByHash(&ancestor.PreviousBlockHash)
89 for d := c.state.block; d.Hash() != ancestor.Hash(); d, _ = c.GetBlockByHash(&d.PreviousBlockHash) {
90 detachBlocks = append(detachBlocks, d)
93 return attachBlocks, detachBlocks
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{}
101 for _, d := range detachBlocks {
102 if err := newSnapshot.DetachBlock(legacy.MapBlock(d)); err != nil {
107 for _, a := range attachBlocks {
108 if err := newSnapshot.ApplyBlock(legacy.MapBlock(a)); err != nil {
112 chainChanges[a.Height] = &aHash
115 return c.setState(block, newSnapshot, chainChanges)
118 func (c *Chain) SaveBlock(block *legacy.Block) error {
119 preBlock, _ := c.GetBlockByHash(&block.PreviousBlockHash)
120 if err := c.ValidateBlock(block, preBlock); err != nil {
123 if err := c.store.SaveBlock(block); err != nil {
126 blockHash := block.Hash()
127 log.WithFields(log.Fields{"height": block.Height, "hash": blockHash.String()}).Info("Block saved on disk")
131 func (c *Chain) findBestChainTail(block *legacy.Block) (bestBlock *legacy.Block) {
133 blockHash := block.Hash()
134 preorphans, ok := c.orphanManage.preOrphans[blockHash]
139 for _, preorphan := range preorphans {
140 orphanBlock, ok := c.orphanManage.Get(preorphan)
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)
153 if subResult := c.findBestChainTail(orphanBlock); subResult.Height > bestBlock.Height {
154 bestBlock = subResult
158 c.orphanManage.Delete(&blockHash)
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")
168 if !c.store.BlockExist(&block.PreviousBlockHash) {
169 c.orphanManage.Add(block)
172 if err := c.SaveBlock(block); err != nil {
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)
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)
187 c.state.cond.L.Unlock()