4 log "github.com/sirupsen/logrus"
6 "github.com/vapor/errors"
7 "github.com/vapor/protocol/bc"
8 "github.com/vapor/protocol/bc/types"
9 "github.com/vapor/protocol/state"
10 "github.com/vapor/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 header 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 height")
37 return c.store.GetBlock(&node.Hash)
40 // GetHeaderByHash return a block header by given hash
41 func (c *Chain) GetHeaderByHash(hash *bc.Hash) (*types.BlockHeader, error) {
42 node := c.index.GetNode(hash)
44 return nil, errors.New("can't find block header in given hash")
46 return node.BlockHeader(), nil
49 // GetHeaderByHeight return a block header by given height
50 func (c *Chain) GetHeaderByHeight(height uint64) (*types.BlockHeader, error) {
51 node := c.index.NodeByHeight(height)
53 return nil, errors.New("can't find block header in given height")
55 return node.BlockHeader(), nil
58 func (c *Chain) calcReorganizeNodes(node *state.BlockNode) ([]*state.BlockNode, []*state.BlockNode) {
59 var attachNodes []*state.BlockNode
60 var detachNodes []*state.BlockNode
63 for c.index.NodeByHeight(attachNode.Height) != attachNode {
64 attachNodes = append([]*state.BlockNode{attachNode}, attachNodes...)
65 attachNode = attachNode.Parent
68 detachNode := c.bestNode
69 for detachNode != attachNode {
70 detachNodes = append(detachNodes, detachNode)
71 detachNode = detachNode.Parent
73 return attachNodes, detachNodes
76 func (c *Chain) connectBlock(block *types.Block) (err error) {
77 irreversibleNode := c.bestIrreversibleNode
78 bcBlock := types.MapBlock(block)
79 if bcBlock.TransactionStatus, err = c.store.GetTransactionStatus(&bcBlock.ID); err != nil {
83 utxoView := state.NewUtxoViewpoint()
84 if err := c.store.GetTransactionsUtxo(utxoView, bcBlock.Transactions); err != nil {
87 if err := utxoView.ApplyBlock(bcBlock, bcBlock.TransactionStatus); err != nil {
91 voteResultMap := make(map[uint64]*state.VoteResult)
92 if err := c.bbft.ApplyBlock(voteResultMap, block); err != nil {
96 node := c.index.GetNode(&bcBlock.ID)
97 if c.bbft.isIrreversible(block) && block.Height > irreversibleNode.Height {
98 irreversibleNode = node
101 if err := c.setState(node, irreversibleNode, utxoView, voteResultMap); err != nil {
105 for _, tx := range block.Transactions {
106 c.txPool.RemoveTransaction(&tx.Tx.ID)
111 func (c *Chain) reorganizeChain(node *state.BlockNode) error {
112 attachNodes, detachNodes := c.calcReorganizeNodes(node)
113 utxoView := state.NewUtxoViewpoint()
114 voteResultMap := make(map[uint64]*state.VoteResult)
115 irreversibleNode := c.bestIrreversibleNode
117 for _, detachNode := range detachNodes {
118 b, err := c.store.GetBlock(&detachNode.Hash)
123 if b.Height <= irreversibleNode.Height {
124 return errors.New("the height of rollback block below the height of irreversible block")
127 detachBlock := types.MapBlock(b)
128 if err := c.store.GetTransactionsUtxo(utxoView, detachBlock.Transactions); err != nil {
131 txStatus, err := c.GetTransactionStatus(&detachBlock.ID)
135 if err := utxoView.DetachBlock(detachBlock, txStatus); err != nil {
139 if err := c.bbft.DetachBlock(voteResultMap, b); err != nil {
143 log.WithFields(log.Fields{"module": logModule, "height": node.Height, "hash": node.Hash.String()}).Debug("detach from mainchain")
146 for _, attachNode := range attachNodes {
147 b, err := c.store.GetBlock(&attachNode.Hash)
152 attachBlock := types.MapBlock(b)
153 if err := c.store.GetTransactionsUtxo(utxoView, attachBlock.Transactions); err != nil {
156 txStatus, err := c.GetTransactionStatus(&attachBlock.ID)
160 if err := utxoView.ApplyBlock(attachBlock, txStatus); err != nil {
164 if err := c.bbft.ApplyBlock(voteResultMap, b); err != nil {
168 if c.bbft.isIrreversible(b) && b.Height > irreversibleNode.Height {
169 irreversibleNode = attachNode
172 log.WithFields(log.Fields{"module": logModule, "height": node.Height, "hash": node.Hash.String()}).Debug("attach from mainchain")
175 return c.setState(node, irreversibleNode, utxoView, voteResultMap)
178 // SaveBlock will validate and save block into storage
179 func (c *Chain) saveBlock(block *types.Block) error {
180 if err := c.bbft.ValidateBlock(block); err != nil {
181 return errors.Sub(ErrBadBlock, err)
184 parent := c.index.GetNode(&block.PreviousBlockHash)
185 if err := validation.ValidateBlock(types.MapBlock(block), parent); err != nil {
186 return errors.Sub(ErrBadBlock, err)
189 if err := c.bbft.SignBlock(block); err != nil {
190 return errors.Sub(ErrBadBlock, err)
193 bcBlock := types.MapBlock(block)
194 if err := c.store.SaveBlock(block, bcBlock.TransactionStatus); err != nil {
198 c.orphanManage.Delete(&bcBlock.ID)
199 node, err := state.NewBlockNode(&block.BlockHeader, parent)
204 c.index.AddNode(node)
208 func (c *Chain) saveSubBlock(block *types.Block) *types.Block {
209 blockHash := block.Hash()
210 prevOrphans, ok := c.orphanManage.GetPrevOrphans(&blockHash)
216 for _, prevOrphan := range prevOrphans {
217 orphanBlock, ok := c.orphanManage.Get(prevOrphan)
219 log.WithFields(log.Fields{"module": logModule, "hash": prevOrphan.String()}).Warning("saveSubBlock fail to get block from orphanManage")
222 if err := c.saveBlock(orphanBlock); err != nil {
223 log.WithFields(log.Fields{"module": logModule, "hash": prevOrphan.String(), "height": orphanBlock.Height}).Warning("saveSubBlock fail to save block")
227 if subBestBlock := c.saveSubBlock(orphanBlock); subBestBlock.Height > bestBlock.Height {
228 bestBlock = subBestBlock
234 type processBlockResponse struct {
239 type processBlockMsg struct {
241 reply chan processBlockResponse
244 // ProcessBlock is the entry for chain update
245 func (c *Chain) ProcessBlock(block *types.Block) (bool, error) {
246 reply := make(chan processBlockResponse, 1)
247 c.processBlockCh <- &processBlockMsg{block: block, reply: reply}
249 return response.isOrphan, response.err
252 func (c *Chain) blockProcesser() {
253 for msg := range c.processBlockCh {
254 isOrphan, err := c.processBlock(msg.block)
255 msg.reply <- processBlockResponse{isOrphan: isOrphan, err: err}
259 // ProcessBlock is the entry for handle block insert
260 func (c *Chain) processBlock(block *types.Block) (bool, error) {
261 if block.Height <= c.bestIrreversibleNode.Height {
262 return false, errors.New("the height of block below the height of irreversible block")
265 blockHash := block.Hash()
266 if c.BlockExist(&blockHash) {
267 log.WithFields(log.Fields{"module": logModule, "hash": blockHash.String(), "height": block.Height}).Info("block has been processed")
268 return c.orphanManage.BlockExist(&blockHash), nil
271 parent := c.index.GetNode(&block.PreviousBlockHash)
273 c.orphanManage.Add(block)
277 if err := c.saveBlock(block); err != nil {
281 bestBlock := c.saveSubBlock(block)
282 bestBlockHash := bestBlock.Hash()
283 bestNode := c.index.GetNode(&bestBlockHash)
285 if bestNode.Parent == c.bestNode {
286 log.WithFields(log.Fields{"module": logModule}).Debug("append block to the end of mainchain")
287 return false, c.connectBlock(bestBlock)
290 if bestNode.Height > c.bestNode.Height {
291 log.WithFields(log.Fields{"module": logModule}).Debug("start to reorganize chain")
292 return false, c.reorganizeChain(bestNode)