4 log "github.com/sirupsen/logrus"
6 "github.com/bytom/errors"
7 "github.com/bytom/protocol/bc"
8 "github.com/bytom/protocol/bc/types"
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")
16 // ErrBadStateRoot is returned when the computed assets merkle root
17 // disagrees with the one declared in a block header.
18 ErrBadStateRoot = errors.New("invalid state merkle root")
21 // BlockExist check is a block in chain or orphan
22 func (c *Chain) BlockExist(hash *bc.Hash) bool {
23 return c.index.BlockExist(hash) || c.orphanManage.BlockExist(hash)
26 // GetBlockByHash return a block by given hash
27 func (c *Chain) GetBlockByHash(hash *bc.Hash) (*types.Block, error) {
28 return c.store.GetBlock(hash)
31 // GetBlockByHeight return a block by given height
32 func (c *Chain) GetBlockByHeight(height uint64) (*types.Block, error) {
33 node := c.index.NodeByHeight(height)
35 return nil, errors.New("can't find block in given hight")
37 return c.store.GetBlock(&node.Hash)
40 func (c *Chain) calcReorganizeNodes(node *state.BlockNode) ([]*state.BlockNode, []*state.BlockNode) {
41 var attachNodes []*state.BlockNode
42 var detachNodes []*state.BlockNode
45 for c.index.NodeByHeight(attachNode.Height) != attachNode {
46 attachNodes = append([]*state.BlockNode{attachNode}, attachNodes...)
47 attachNode = attachNode.Parent
50 detachNode := c.bestNode
51 for detachNode != attachNode {
52 detachNodes = append(detachNodes, detachNode)
53 detachNode = detachNode.Parent
55 return attachNodes, detachNodes
58 func (c *Chain) connectBlock(block *types.Block) (err error) {
59 bcBlock := types.MapBlock(block)
60 if bcBlock.TransactionStatus, err = c.store.GetTransactionStatus(&bcBlock.ID); err != nil {
64 utxoView := state.NewUtxoViewpoint()
65 if err := c.store.GetTransactionsUtxo(utxoView, bcBlock.Transactions); err != nil {
68 if err := utxoView.ApplyBlock(bcBlock, bcBlock.TransactionStatus); err != nil {
72 node := c.index.GetNode(&bcBlock.ID)
73 if err := c.setState(node, utxoView); err != nil {
77 for _, tx := range block.Transactions {
78 c.txPool.RemoveTransaction(&tx.Tx.ID)
83 func (c *Chain) reorganizeChain(node *state.BlockNode) error {
84 attachNodes, detachNodes := c.calcReorganizeNodes(node)
85 utxoView := state.NewUtxoViewpoint()
87 for _, detachNode := range detachNodes {
88 b, err := c.store.GetBlock(&detachNode.Hash)
93 detachBlock := types.MapBlock(b)
94 if err := c.store.GetTransactionsUtxo(utxoView, detachBlock.Transactions); err != nil {
97 txStatus, err := c.GetTransactionStatus(&detachBlock.ID)
101 if err := utxoView.DetachBlock(detachBlock, txStatus); err != nil {
105 log.WithFields(log.Fields{"height": node.Height, "hash": node.Hash.String()}).Debug("detach from mainchain")
108 for _, attachNode := range attachNodes {
109 b, err := c.store.GetBlock(&attachNode.Hash)
114 attachBlock := types.MapBlock(b)
115 if err := c.store.GetTransactionsUtxo(utxoView, attachBlock.Transactions); err != nil {
118 txStatus, err := c.GetTransactionStatus(&attachBlock.ID)
122 if err := utxoView.ApplyBlock(attachBlock, txStatus); err != nil {
126 log.WithFields(log.Fields{"height": node.Height, "hash": node.Hash.String()}).Debug("attach from mainchain")
129 return c.setState(node, utxoView)
132 // SaveBlock will validate and save block into storage
133 func (c *Chain) saveBlock(block *types.Block) error {
134 bcBlock := types.MapBlock(block)
135 parent := c.index.GetNode(&block.PreviousBlockHash)
137 if err := validation.ValidateBlock(bcBlock, parent); err != nil {
138 return errors.Sub(ErrBadBlock, err)
140 if err := c.store.SaveBlock(block, bcBlock.TransactionStatus); err != nil {
144 c.orphanManage.Delete(&bcBlock.ID)
145 node, err := state.NewBlockNode(&block.BlockHeader, parent)
150 c.index.AddNode(node)
154 func (c *Chain) saveSubBlock(block *types.Block) *types.Block {
155 blockHash := block.Hash()
156 prevOrphans, ok := c.orphanManage.GetPrevOrphans(&blockHash)
162 for _, prevOrphan := range prevOrphans {
163 orphanBlock, ok := c.orphanManage.Get(prevOrphan)
165 log.WithFields(log.Fields{"hash": prevOrphan.String()}).Warning("saveSubBlock fail to get block from orphanManage")
168 if err := c.saveBlock(orphanBlock); err != nil {
169 log.WithFields(log.Fields{"hash": prevOrphan.String(), "height": orphanBlock.Height}).Warning("saveSubBlock fail to save block")
173 if subBestBlock := c.saveSubBlock(orphanBlock); subBestBlock.Height > bestBlock.Height {
174 bestBlock = subBestBlock
180 type processBlockResponse struct {
185 type processBlockMsg struct {
187 reply chan processBlockResponse
190 // ProcessBlock is the entry for chain update
191 func (c *Chain) ProcessBlock(block *types.Block) (bool, error) {
192 reply := make(chan processBlockResponse, 1)
193 c.processBlockCh <- &processBlockMsg{block: block, reply: reply}
195 return response.isOrphan, response.err
198 func (c *Chain) blockProcesser() {
199 for msg := range c.processBlockCh {
200 isOrphan, err := c.processBlock(msg.block)
201 msg.reply <- processBlockResponse{isOrphan: isOrphan, err: err}
205 // ProcessBlock is the entry for handle block insert
206 func (c *Chain) processBlock(block *types.Block) (bool, error) {
207 blockHash := block.Hash()
208 if c.BlockExist(&blockHash) {
209 log.WithFields(log.Fields{"hash": blockHash.String(), "height": block.Height}).Info("block has been processed")
210 return c.orphanManage.BlockExist(&blockHash), nil
213 if parent := c.index.GetNode(&block.PreviousBlockHash); parent == nil {
214 c.orphanManage.Add(block)
218 if err := c.saveBlock(block); err != nil {
222 bestBlock := c.saveSubBlock(block)
223 bestBlockHash := bestBlock.Hash()
224 bestNode := c.index.GetNode(&bestBlockHash)
226 if bestNode.Parent == c.bestNode {
227 log.Debug("append block to the end of mainchain")
228 return false, c.connectBlock(bestBlock)
231 if bestNode.Height > c.bestNode.Height && bestNode.WorkSum.Cmp(c.bestNode.WorkSum) >= 0 {
232 log.Debug("start to reorganize chain")
233 return false, c.reorganizeChain(bestNode)