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 node := c.index.GetNode(hash)
33 return nil, errors.New("can't find block in given hash")
35 return c.store.GetBlock(hash, node.Height)
38 // GetBlockByHeight return a block header by given height
39 func (c *Chain) GetBlockByHeight(height uint64) (*types.Block, error) {
40 node := c.index.NodeByHeight(height)
42 return nil, errors.New("can't find block in given height")
44 return c.store.GetBlock(&node.Hash, height)
47 // GetHeaderByHash return a block header by given hash
48 func (c *Chain) GetHeaderByHash(hash *bc.Hash) (*types.BlockHeader, error) {
49 node := c.index.GetNode(hash)
51 return nil, errors.New("can't find block header in given hash")
53 return node.BlockHeader(), nil
56 // GetHeaderByHeight return a block header by given height
57 func (c *Chain) GetHeaderByHeight(height uint64) (*types.BlockHeader, error) {
58 node := c.index.NodeByHeight(height)
60 return nil, errors.New("can't find block header in given height")
62 return node.BlockHeader(), nil
65 func (c *Chain) calcReorganizeNodes(node *state.BlockNode) ([]*state.BlockNode, []*state.BlockNode) {
66 var attachNodes []*state.BlockNode
67 var detachNodes []*state.BlockNode
70 for c.index.NodeByHeight(attachNode.Height) != attachNode {
71 attachNodes = append([]*state.BlockNode{attachNode}, attachNodes...)
72 attachNode = attachNode.Parent
75 detachNode := c.bestNode
76 for detachNode != attachNode {
77 detachNodes = append(detachNodes, detachNode)
78 detachNode = detachNode.Parent
80 return attachNodes, detachNodes
83 func (c *Chain) connectBlock(block *types.Block) (err error) {
84 irreversibleNode := c.bestIrreversibleNode
85 bcBlock := types.MapBlock(block)
86 if bcBlock.TransactionStatus, err = c.store.GetTransactionStatus(&bcBlock.ID); err != nil {
90 utxoView := state.NewUtxoViewpoint()
91 if err := c.store.GetTransactionsUtxo(utxoView, bcBlock.Transactions); err != nil {
94 if err := utxoView.ApplyBlock(bcBlock, bcBlock.TransactionStatus); err != nil {
98 voteResult, err := c.consensusNodeManager.getBestVoteResult()
102 if err := voteResult.ApplyBlock(block); err != nil {
106 node := c.index.GetNode(&bcBlock.ID)
107 if c.isIrreversible(node) && block.Height > irreversibleNode.Height {
108 irreversibleNode = node
111 if err := c.setState(node, irreversibleNode, utxoView, []*state.VoteResult{voteResult}); err != nil {
115 for _, tx := range block.Transactions {
116 c.txPool.RemoveTransaction(&tx.Tx.ID)
121 func (c *Chain) reorganizeChain(node *state.BlockNode) error {
122 attachNodes, detachNodes := c.calcReorganizeNodes(node)
123 utxoView := state.NewUtxoViewpoint()
124 voteResults := []*state.VoteResult{}
125 irreversibleNode := c.bestIrreversibleNode
126 voteResult, err := c.consensusNodeManager.getBestVoteResult()
131 for _, detachNode := range detachNodes {
132 b, err := c.store.GetBlock(&detachNode.Hash, detachNode.Height)
137 detachBlock := types.MapBlock(b)
138 if err := c.store.GetTransactionsUtxo(utxoView, detachBlock.Transactions); err != nil {
142 txStatus, err := c.GetTransactionStatus(&detachBlock.ID)
147 if err := utxoView.DetachBlock(detachBlock, txStatus); err != nil {
151 if err := voteResult.DetachBlock(b); err != nil {
155 log.WithFields(log.Fields{"module": logModule, "height": node.Height, "hash": node.Hash.String()}).Debug("detach from mainchain")
158 for _, attachNode := range attachNodes {
159 b, err := c.store.GetBlock(&attachNode.Hash, attachNode.Height)
164 attachBlock := types.MapBlock(b)
165 if err := c.store.GetTransactionsUtxo(utxoView, attachBlock.Transactions); err != nil {
169 txStatus, err := c.GetTransactionStatus(&attachBlock.ID)
174 if err := utxoView.ApplyBlock(attachBlock, txStatus); err != nil {
178 if err := voteResult.ApplyBlock(b); err != nil {
182 if voteResult.IsFinalize() {
183 voteResults = append(voteResults, voteResult.Fork())
186 if c.isIrreversible(attachNode) && attachNode.Height > irreversibleNode.Height {
187 irreversibleNode = attachNode
190 log.WithFields(log.Fields{"module": logModule, "height": node.Height, "hash": node.Hash.String()}).Debug("attach from mainchain")
193 if detachNodes[len(detachNodes)-1].Height <= c.bestIrreversibleNode.Height && irreversibleNode.Height <= c.bestIrreversibleNode.Height {
194 return errors.New("rollback block below the height of irreversible block")
196 voteResults = append(voteResults, voteResult.Fork())
197 return c.setState(node, irreversibleNode, utxoView, voteResults)
200 // SaveBlock will validate and save block into storage
201 func (c *Chain) saveBlock(block *types.Block) error {
202 if err := c.validateSign(block); err != nil {
203 return errors.Sub(ErrBadBlock, err)
206 parent := c.index.GetNode(&block.PreviousBlockHash)
207 bcBlock := types.MapBlock(block)
208 if err := validation.ValidateBlock(bcBlock, parent); err != nil {
209 return errors.Sub(ErrBadBlock, err)
212 signature, err := c.SignBlock(block)
214 return errors.Sub(ErrBadBlock, err)
217 if err := c.store.SaveBlock(block, bcBlock.TransactionStatus); err != nil {
221 c.orphanManage.Delete(&bcBlock.ID)
222 node, err := state.NewBlockNode(&block.BlockHeader, parent)
227 c.index.AddNode(node)
229 if len(signature) != 0 {
230 xPub := config.CommonConfig.PrivateKey().XPub()
231 if err := c.eventDispatcher.Post(event.BlockSignatureEvent{BlockHash: block.Hash(), Signature: signature, XPub: xPub[:]}); err != nil {
238 func (c *Chain) saveSubBlock(block *types.Block) *types.Block {
239 blockHash := block.Hash()
240 prevOrphans, ok := c.orphanManage.GetPrevOrphans(&blockHash)
246 for _, prevOrphan := range prevOrphans {
247 orphanBlock, ok := c.orphanManage.Get(prevOrphan)
249 log.WithFields(log.Fields{"module": logModule, "hash": prevOrphan.String()}).Warning("saveSubBlock fail to get block from orphanManage")
252 if err := c.saveBlock(orphanBlock); err != nil {
253 log.WithFields(log.Fields{"module": logModule, "hash": prevOrphan.String(), "height": orphanBlock.Height}).Warning("saveSubBlock fail to save block")
257 if subBestBlock := c.saveSubBlock(orphanBlock); subBestBlock.Height > bestBlock.Height {
258 bestBlock = subBestBlock
264 type processBlockResponse struct {
269 type processBlockMsg struct {
271 reply chan processBlockResponse
274 // ProcessBlock is the entry for chain update
275 func (c *Chain) ProcessBlock(block *types.Block) (bool, error) {
276 reply := make(chan processBlockResponse, 1)
277 c.processBlockCh <- &processBlockMsg{block: block, reply: reply}
279 return response.isOrphan, response.err
282 func (c *Chain) blockProcesser() {
283 for msg := range c.processBlockCh {
284 isOrphan, err := c.processBlock(msg.block)
285 msg.reply <- processBlockResponse{isOrphan: isOrphan, err: err}
289 // ProcessBlock is the entry for handle block insert
290 func (c *Chain) processBlock(block *types.Block) (bool, error) {
291 blockHash := block.Hash()
292 if c.BlockExist(&blockHash) {
293 log.WithFields(log.Fields{"module": logModule, "hash": blockHash.String(), "height": block.Height}).Info("block has been processed")
294 return c.orphanManage.BlockExist(&blockHash), nil
297 if parent := c.index.GetNode(&block.PreviousBlockHash); parent == nil {
298 c.orphanManage.Add(block)
302 if err := c.saveBlock(block); err != nil {
306 bestBlock := c.saveSubBlock(block)
307 bestBlockHash := bestBlock.Hash()
308 bestNode := c.index.GetNode(&bestBlockHash)
311 defer c.cond.L.Unlock()
312 if bestNode.Parent == c.bestNode {
313 log.WithFields(log.Fields{"module": logModule}).Debug("append block to the end of mainchain")
314 return false, c.connectBlock(bestBlock)
317 if bestNode.Height > c.bestNode.Height {
318 log.WithFields(log.Fields{"module": logModule}).Debug("start to reorganize chain")
319 return false, c.reorganizeChain(bestNode)