4 log "github.com/sirupsen/logrus"
6 "github.com/vapor/config"
7 "github.com/vapor/errors"
8 "github.com/vapor/event"
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"
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")
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)
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)
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)
37 return nil, errors.New("can't find block in given height")
39 return c.store.GetBlock(&node.Hash)
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)
46 return nil, errors.New("can't find block header in given hash")
48 return node.BlockHeader(), nil
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)
55 return nil, errors.New("can't find block header in given height")
57 return node.BlockHeader(), nil
60 func (c *Chain) calcReorganizeNodes(node *state.BlockNode) ([]*state.BlockNode, []*state.BlockNode) {
61 var attachNodes []*state.BlockNode
62 var detachNodes []*state.BlockNode
65 for c.index.NodeByHeight(attachNode.Height) != attachNode {
66 attachNodes = append([]*state.BlockNode{attachNode}, attachNodes...)
67 attachNode = attachNode.Parent
70 detachNode := c.bestNode
71 for detachNode != attachNode {
72 detachNodes = append(detachNodes, detachNode)
73 detachNode = detachNode.Parent
75 return attachNodes, detachNodes
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 {
85 utxoView := state.NewUtxoViewpoint()
86 if err := c.store.GetTransactionsUtxo(utxoView, bcBlock.Transactions); err != nil {
89 if err := utxoView.ApplyBlock(bcBlock, bcBlock.TransactionStatus); err != nil {
93 voteResultMap := make(map[uint64]*state.VoteResult)
94 if err := c.consensusNodeManager.applyBlock(voteResultMap, block); err != nil {
98 node := c.index.GetNode(&bcBlock.ID)
99 if c.isIrreversible(node) && block.Height > irreversibleNode.Height {
100 irreversibleNode = node
103 if err := c.setState(node, irreversibleNode, utxoView, voteResultMap); err != nil {
107 for _, tx := range block.Transactions {
108 c.txPool.RemoveTransaction(&tx.Tx.ID)
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
119 for _, detachNode := range detachNodes {
120 b, err := c.store.GetBlock(&detachNode.Hash)
125 if b.Height <= irreversibleNode.Height {
126 return errors.New("the height of rollback block below the height of irreversible block")
129 detachBlock := types.MapBlock(b)
130 if err := c.store.GetTransactionsUtxo(utxoView, detachBlock.Transactions); err != nil {
134 txStatus, err := c.GetTransactionStatus(&detachBlock.ID)
139 if err := utxoView.DetachBlock(detachBlock, txStatus); err != nil {
143 if err := c.consensusNodeManager.detachBlock(voteResultMap, b); err != nil {
147 log.WithFields(log.Fields{"module": logModule, "height": node.Height, "hash": node.Hash.String()}).Debug("detach from mainchain")
150 for _, attachNode := range attachNodes {
151 b, err := c.store.GetBlock(&attachNode.Hash)
156 attachBlock := types.MapBlock(b)
157 if err := c.store.GetTransactionsUtxo(utxoView, attachBlock.Transactions); err != nil {
161 txStatus, err := c.GetTransactionStatus(&attachBlock.ID)
166 if err := utxoView.ApplyBlock(attachBlock, txStatus); err != nil {
170 if err := c.consensusNodeManager.applyBlock(voteResultMap, b); err != nil {
174 if c.isIrreversible(attachNode) && b.Height > irreversibleNode.Height {
175 irreversibleNode = attachNode
178 log.WithFields(log.Fields{"module": logModule, "height": node.Height, "hash": node.Hash.String()}).Debug("attach from mainchain")
181 return c.setState(node, irreversibleNode, utxoView, voteResultMap)
184 // SaveBlock will validate and save block into storage
185 func (c *Chain) saveBlock(block *types.Block) error {
186 if _, err := c.validateSign(block); err != nil {
187 return errors.Sub(ErrBadBlock, err)
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)
196 signature, err := c.SignBlock(block)
198 return errors.Sub(ErrBadBlock, err)
201 if err := c.store.SaveBlock(block, bcBlock.TransactionStatus); err != nil {
205 c.orphanManage.Delete(&bcBlock.ID)
206 node, err := state.NewBlockNode(&block.BlockHeader, parent)
211 c.index.AddNode(node)
213 if len(signature) != 0 {
214 xPub := config.CommonConfig.PrivateKey().XPub()
215 if err := c.eventDispatcher.Post(event.BlockSignatureEvent{BlockHash: block.Hash(), Signature: signature, XPub: xPub}); err != nil {
222 func (c *Chain) saveSubBlock(block *types.Block) *types.Block {
223 blockHash := block.Hash()
224 prevOrphans, ok := c.orphanManage.GetPrevOrphans(&blockHash)
230 for _, prevOrphan := range prevOrphans {
231 orphanBlock, ok := c.orphanManage.Get(prevOrphan)
233 log.WithFields(log.Fields{"module": logModule, "hash": prevOrphan.String()}).Warning("saveSubBlock fail to get block from orphanManage")
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")
241 if subBestBlock := c.saveSubBlock(orphanBlock); subBestBlock.Height > bestBlock.Height {
242 bestBlock = subBestBlock
248 type processBlockResponse struct {
253 type processBlockMsg struct {
255 reply chan processBlockResponse
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}
263 return response.isOrphan, response.err
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}
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")
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
285 if parent := c.index.GetNode(&block.PreviousBlockHash); parent == nil {
286 c.orphanManage.Add(block)
290 if err := c.saveBlock(block); err != nil {
294 bestBlock := c.saveSubBlock(block)
295 bestBlockHash := bestBlock.Hash()
296 bestNode := c.index.GetNode(&bestBlockHash)
298 if bestNode.Parent == c.bestNode {
299 log.WithFields(log.Fields{"module": logModule}).Debug("append block to the end of mainchain")
300 return false, c.connectBlock(bestBlock)
303 if bestNode.Height > c.bestNode.Height {
304 log.WithFields(log.Fields{"module": logModule}).Debug("start to reorganize chain")
305 return false, c.reorganizeChain(bestNode)