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")
21 errBelowIrreversibleBlock = errors.New("the height of block below the height of irreversible block")
24 // BlockExist check is a block in chain or orphan
25 func (c *Chain) BlockExist(hash *bc.Hash) bool {
26 return c.index.BlockExist(hash) || c.orphanManage.BlockExist(hash)
29 // GetBlockByHash return a block by given hash
30 func (c *Chain) GetBlockByHash(hash *bc.Hash) (*types.Block, error) {
31 return c.store.GetBlock(hash)
34 // GetBlockByHeight return a block header by given height
35 func (c *Chain) GetBlockByHeight(height uint64) (*types.Block, error) {
36 node := c.index.NodeByHeight(height)
38 return nil, errors.New("can't find block in given height")
40 return c.store.GetBlock(&node.Hash)
43 // GetHeaderByHash return a block header by given hash
44 func (c *Chain) GetHeaderByHash(hash *bc.Hash) (*types.BlockHeader, error) {
45 node := c.index.GetNode(hash)
47 return nil, errors.New("can't find block header in given hash")
49 return node.BlockHeader(), nil
52 // GetHeaderByHeight return a block header by given height
53 func (c *Chain) GetHeaderByHeight(height uint64) (*types.BlockHeader, error) {
54 node := c.index.NodeByHeight(height)
56 return nil, errors.New("can't find block header in given height")
58 return node.BlockHeader(), nil
61 func (c *Chain) calcReorganizeNodes(node *state.BlockNode) ([]*state.BlockNode, []*state.BlockNode) {
62 var attachNodes []*state.BlockNode
63 var detachNodes []*state.BlockNode
66 for c.index.NodeByHeight(attachNode.Height) != attachNode {
67 attachNodes = append([]*state.BlockNode{attachNode}, attachNodes...)
68 attachNode = attachNode.Parent
71 detachNode := c.bestNode
72 for detachNode != attachNode {
73 detachNodes = append(detachNodes, detachNode)
74 detachNode = detachNode.Parent
76 return attachNodes, detachNodes
79 func (c *Chain) connectBlock(block *types.Block) (err error) {
80 irreversibleNode := c.bestIrreversibleNode
81 bcBlock := types.MapBlock(block)
82 if bcBlock.TransactionStatus, err = c.store.GetTransactionStatus(&bcBlock.ID); err != nil {
86 utxoView := state.NewUtxoViewpoint()
87 if err := c.store.GetTransactionsUtxo(utxoView, bcBlock.Transactions); err != nil {
90 if err := utxoView.ApplyBlock(bcBlock, bcBlock.TransactionStatus); err != nil {
94 voteResult, err := c.consensusNodeManager.getBestVoteResult()
98 if err := voteResult.ApplyBlock(block); err != nil {
102 node := c.index.GetNode(&bcBlock.ID)
103 if c.isIrreversible(node) && block.Height > irreversibleNode.Height {
104 irreversibleNode = node
107 if err := c.setState(node, irreversibleNode, utxoView, []*state.VoteResult{voteResult}); err != nil {
111 for _, tx := range block.Transactions {
112 c.txPool.RemoveTransaction(&tx.Tx.ID)
117 func (c *Chain) reorganizeChain(node *state.BlockNode) error {
118 attachNodes, detachNodes := c.calcReorganizeNodes(node)
119 utxoView := state.NewUtxoViewpoint()
120 voteResults := []*state.VoteResult{}
121 irreversibleNode := c.bestIrreversibleNode
122 voteResult, err := c.consensusNodeManager.getBestVoteResult()
127 for _, detachNode := range detachNodes {
128 b, err := c.store.GetBlock(&detachNode.Hash)
133 detachBlock := types.MapBlock(b)
134 if err := c.store.GetTransactionsUtxo(utxoView, detachBlock.Transactions); err != nil {
138 txStatus, err := c.GetTransactionStatus(&detachBlock.ID)
143 if err := utxoView.DetachBlock(detachBlock, txStatus); err != nil {
147 if err := voteResult.DetachBlock(b); err != nil {
151 log.WithFields(log.Fields{"module": logModule, "height": node.Height, "hash": node.Hash.String()}).Debug("detach from mainchain")
154 for _, attachNode := range attachNodes {
155 b, err := c.store.GetBlock(&attachNode.Hash)
160 attachBlock := types.MapBlock(b)
161 if err := c.store.GetTransactionsUtxo(utxoView, attachBlock.Transactions); err != nil {
165 txStatus, err := c.GetTransactionStatus(&attachBlock.ID)
170 if err := utxoView.ApplyBlock(attachBlock, txStatus); err != nil {
174 if err := voteResult.ApplyBlock(b); err != nil {
178 if voteResult.IsFinalize() {
179 voteResults = append(voteResults, voteResult.Fork())
182 if c.isIrreversible(attachNode) && attachNode.Height > irreversibleNode.Height {
183 irreversibleNode = attachNode
186 log.WithFields(log.Fields{"module": logModule, "height": node.Height, "hash": node.Hash.String()}).Debug("attach from mainchain")
189 if detachNodes[len(detachNodes)-1].Height <= c.bestIrreversibleNode.Height && irreversibleNode.Height <= c.bestIrreversibleNode.Height {
190 return errors.New("rollback block below the height of irreversible block")
192 voteResults = append(voteResults, voteResult.Fork())
193 return c.setState(node, irreversibleNode, utxoView, voteResults)
196 // SaveBlock will validate and save block into storage
197 func (c *Chain) saveBlock(block *types.Block) error {
198 if err := c.validateSign(block); err != nil {
199 return errors.Sub(ErrBadBlock, err)
202 parent := c.index.GetNode(&block.PreviousBlockHash)
203 bcBlock := types.MapBlock(block)
204 if err := validation.ValidateBlock(bcBlock, parent); err != nil {
205 return errors.Sub(ErrBadBlock, err)
208 signature, err := c.SignBlock(block)
210 return errors.Sub(ErrBadBlock, err)
213 if err := c.store.SaveBlock(block, bcBlock.TransactionStatus); err != nil {
217 c.orphanManage.Delete(&bcBlock.ID)
218 node, err := state.NewBlockNode(&block.BlockHeader, parent)
223 c.index.AddNode(node)
225 if len(signature) != 0 {
226 xPub := config.CommonConfig.PrivateKey().XPub()
227 if err := c.eventDispatcher.Post(event.BlockSignatureEvent{BlockHash: block.Hash(), Signature: signature, XPub: xPub[:]}); err != nil {
234 func (c *Chain) saveSubBlock(block *types.Block) *types.Block {
235 blockHash := block.Hash()
236 prevOrphans, ok := c.orphanManage.GetPrevOrphans(&blockHash)
242 for _, prevOrphan := range prevOrphans {
243 orphanBlock, ok := c.orphanManage.Get(prevOrphan)
245 log.WithFields(log.Fields{"module": logModule, "hash": prevOrphan.String()}).Warning("saveSubBlock fail to get block from orphanManage")
248 if err := c.saveBlock(orphanBlock); err != nil {
249 log.WithFields(log.Fields{"module": logModule, "hash": prevOrphan.String(), "height": orphanBlock.Height}).Warning("saveSubBlock fail to save block")
253 if subBestBlock := c.saveSubBlock(orphanBlock); subBestBlock.Height > bestBlock.Height {
254 bestBlock = subBestBlock
260 type processBlockResponse struct {
265 type processBlockMsg struct {
267 reply chan processBlockResponse
270 // ProcessBlock is the entry for chain update
271 func (c *Chain) ProcessBlock(block *types.Block) (bool, error) {
272 reply := make(chan processBlockResponse, 1)
273 c.processBlockCh <- &processBlockMsg{block: block, reply: reply}
275 return response.isOrphan, response.err
278 func (c *Chain) blockProcesser() {
279 for msg := range c.processBlockCh {
280 isOrphan, err := c.processBlock(msg.block)
281 msg.reply <- processBlockResponse{isOrphan: isOrphan, err: err}
285 // ProcessBlock is the entry for handle block insert
286 func (c *Chain) processBlock(block *types.Block) (bool, error) {
287 blockHash := block.Hash()
288 if c.BlockExist(&blockHash) {
289 log.WithFields(log.Fields{"module": logModule, "hash": blockHash.String(), "height": block.Height}).Info("block has been processed")
290 return c.orphanManage.BlockExist(&blockHash), nil
293 if parent := c.index.GetNode(&block.PreviousBlockHash); parent == nil {
294 c.orphanManage.Add(block)
298 if err := c.saveBlock(block); err != nil {
302 bestBlock := c.saveSubBlock(block)
303 bestBlockHash := bestBlock.Hash()
304 bestNode := c.index.GetNode(&bestBlockHash)
307 defer c.cond.L.Unlock()
308 if bestNode.Parent == c.bestNode {
309 log.WithFields(log.Fields{"module": logModule}).Debug("append block to the end of mainchain")
310 return false, c.connectBlock(bestBlock)
313 if bestNode.Height > c.bestNode.Height {
314 log.WithFields(log.Fields{"module": logModule}).Debug("start to reorganize chain")
315 return false, c.reorganizeChain(bestNode)