6 log "github.com/sirupsen/logrus"
8 "github.com/bytom/bytom/errors"
9 "github.com/bytom/bytom/event"
10 "github.com/bytom/bytom/protocol/bc"
11 "github.com/bytom/bytom/protocol/bc/types"
12 "github.com/bytom/bytom/protocol/state"
13 "github.com/bytom/bytom/protocol/validation"
17 // ErrBadBlock is returned when a block is invalid.
18 ErrBadBlock = errors.New("invalid block")
19 // ErrBadStateRoot is returned when the computed assets merkle root
20 // disagrees with the one declared in a block header.
21 ErrBadStateRoot = errors.New("invalid state merkle root")
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 bcBlock := types.MapBlock(block)
81 utxoView := state.NewUtxoViewpoint()
82 if err := c.store.GetTransactionsUtxo(utxoView, bcBlock.Transactions); err != nil {
85 if err := utxoView.ApplyBlock(bcBlock); err != nil {
89 verification, checkpoint, err := c.casper.ApplyBlock(block)
94 if verification != nil {
95 if err := c.broadcastVerification(verification); err != nil {
100 contractView := state.NewContractViewpoint()
101 if err := contractView.ApplyBlock(block); err != nil {
105 node := c.index.GetNode(&bcBlock.ID)
106 if err := c.setState(node, utxoView, contractView, checkpoint); err != nil {
110 for _, tx := range block.Transactions {
111 c.txPool.RemoveTransaction(&tx.Tx.ID)
116 func (c *Chain) reorganizeChain(node *state.BlockNode) error {
117 attachNodes, detachNodes := c.calcReorganizeNodes(node)
118 utxoView := state.NewUtxoViewpoint()
119 contractView := state.NewContractViewpoint()
121 txsToRestore := map[bc.Hash]*types.Tx{}
122 for _, detachNode := range detachNodes {
123 b, err := c.store.GetBlock(&detachNode.Hash)
128 detachBlock := types.MapBlock(b)
129 if err := c.store.GetTransactionsUtxo(utxoView, detachBlock.Transactions); err != nil {
133 if err := utxoView.DetachBlock(detachBlock); err != nil {
137 if err := contractView.DetachBlock(b); err != nil {
141 for _, tx := range b.Transactions {
142 txsToRestore[tx.ID] = tx
144 log.WithFields(log.Fields{"module": logModule, "height": node.Height, "hash": node.Hash.String()}).Debug("detach from mainchain")
147 txsToRemove := map[bc.Hash]*types.Tx{}
148 var affectedCheckpoints []*state.Checkpoint
149 for _, attachNode := range attachNodes {
150 b, err := c.store.GetBlock(&attachNode.Hash)
155 attachBlock := types.MapBlock(b)
156 if err := c.store.GetTransactionsUtxo(utxoView, attachBlock.Transactions); err != nil {
160 if err := utxoView.ApplyBlock(attachBlock); err != nil {
164 verification, checkpoint, err := c.casper.ApplyBlock(b)
169 affectedCheckpoints = append(affectedCheckpoints, checkpoint)
171 if err := c.broadcastVerification(verification); err != nil {
175 if err := contractView.ApplyBlock(b); err != nil {
179 for _, tx := range b.Transactions {
180 if _, ok := txsToRestore[tx.ID]; !ok {
181 txsToRemove[tx.ID] = tx
183 delete(txsToRestore, tx.ID)
187 log.WithFields(log.Fields{"module": logModule, "height": node.Height, "hash": node.Hash.String()}).Debug("attach from mainchain")
190 if err := c.setState(node, utxoView, contractView, affectedCheckpoints...); err != nil {
194 for txHash := range txsToRemove {
195 c.txPool.RemoveTransaction(&txHash)
198 for _, tx := range txsToRestore {
199 // the number of restored Tx should be very small or most of time ZERO
200 // Error returned from validation is ignored, tx could still be lost if validation fails.
201 // TODO: adjust tx timestamp so that it won't starve in pool.
202 if _, err := c.ValidateTx(tx); err != nil {
203 log.WithFields(log.Fields{"module": logModule, "tx_id": tx.Tx.ID.String(), "error": err}).Info("restore tx fail")
207 if len(txsToRestore) > 0 {
208 log.WithFields(log.Fields{"module": logModule, "num": len(txsToRestore)}).Debug("restore txs back to pool")
214 func (c *Chain) broadcastVerification(v *Verification) error {
215 pubKey, err := hex.DecodeString(v.PubKey)
220 signature, err := hex.DecodeString(v.Signature)
225 return c.eventDispatcher.Post(event.BlockVerificationEvent{
226 SourceHeight: v.SourceHeight,
227 SourceHash: v.SourceHash,
228 TargetHeight: v.TargetHeight,
229 TargetHash: v.TargetHash,
231 Signature: signature,
235 // SaveBlock will validate and save block into storage
236 func (c *Chain) saveBlock(block *types.Block) error {
237 bcBlock := types.MapBlock(block)
238 parent := c.index.GetNode(&block.PreviousBlockHash)
240 if err := validation.ValidateBlock(bcBlock, parent, c.ProgramConverter); err != nil {
241 return errors.Sub(ErrBadBlock, err)
244 if err := c.store.SaveBlock(block); err != nil {
248 c.orphanManage.Delete(&bcBlock.ID)
249 node, err := state.NewBlockNode(&block.BlockHeader, parent)
254 c.index.AddNode(node)
258 func (c *Chain) saveSubBlock(block *types.Block) *types.Block {
259 blockHash := block.Hash()
260 prevOrphans, ok := c.orphanManage.GetPrevOrphans(&blockHash)
266 for _, prevOrphan := range prevOrphans {
267 orphanBlock, ok := c.orphanManage.Get(prevOrphan)
269 log.WithFields(log.Fields{"module": logModule, "hash": prevOrphan.String()}).Warning("saveSubBlock fail to get block from orphanManage")
272 if err := c.saveBlock(orphanBlock); err != nil {
273 log.WithFields(log.Fields{"module": logModule, "hash": prevOrphan.String(), "height": orphanBlock.Height}).Warning("saveSubBlock fail to save block")
277 if subBestBlock := c.saveSubBlock(orphanBlock); subBestBlock.Height > bestBlock.Height {
278 bestBlock = subBestBlock
284 type processBlockResponse struct {
289 type processBlockMsg struct {
291 reply chan processBlockResponse
294 // ProcessBlock is the entry for chain update
295 func (c *Chain) ProcessBlock(block *types.Block) (bool, error) {
296 reply := make(chan processBlockResponse, 1)
297 c.processBlockCh <- &processBlockMsg{block: block, reply: reply}
299 return response.isOrphan, response.err
302 func (c *Chain) blockProcessor() {
305 case msg := <-c.processBlockCh:
306 isOrphan, err := c.processBlock(msg.block)
307 msg.reply <- processBlockResponse{isOrphan: isOrphan, err: err}
308 case newBestHash := <-c.rollbackNotifyCh:
309 if err := c.rollback(newBestHash); err != nil {
310 log.WithFields(log.Fields{"module": logModule, "err": err}).Warning("fail on rollback block")
316 // ProcessBlock is the entry for handle block insert
317 func (c *Chain) processBlock(block *types.Block) (bool, error) {
318 blockHash := block.Hash()
319 if c.BlockExist(&blockHash) {
320 log.WithFields(log.Fields{"module": logModule, "hash": blockHash.String(), "height": block.Height}).Info("block has been processed")
321 return c.orphanManage.BlockExist(&blockHash), nil
324 if parent := c.index.GetNode(&block.PreviousBlockHash); parent == nil {
325 c.orphanManage.Add(block)
329 if err := c.saveBlock(block); err != nil {
333 bestBlock := c.saveSubBlock(block)
334 bestBlockHash := bestBlock.Hash()
335 bestNode := c.index.GetNode(&bestBlockHash)
337 if bestNode.Parent == c.bestNode {
338 log.WithFields(log.Fields{"module": logModule}).Debug("append block to the end of mainchain")
339 return false, c.connectBlock(bestBlock)
344 func (c *Chain) rollback(newBestHash bc.Hash) error {
345 if c.bestNode.Hash == newBestHash {
349 node := c.index.GetNode(&newBestHash)
350 log.WithFields(log.Fields{"module": logModule}).Debug("start to reorganize chain")
351 return c.reorganizeChain(node)