var (
// ErrBadBlock is returned when a block is invalid.
ErrBadBlock = errors.New("invalid block")
-
// ErrBadStateRoot is returned when the computed assets merkle root
// disagrees with the one declared in a block header.
ErrBadStateRoot = errors.New("invalid state merkle root")
// BlockExist check is a block in chain or orphan
func (c *Chain) BlockExist(hash *bc.Hash) bool {
- return c.orphanManage.BlockExist(hash) || c.store.BlockExist(hash)
+ return c.index.BlockExist(hash) || c.orphanManage.BlockExist(hash)
}
// GetBlockByHash return a block by given hash
return c.store.GetBlock(hash)
}
-// GetBlockByHeight return a block by given height
+// GetBlockByHeight return a block header by given height
func (c *Chain) GetBlockByHeight(height uint64) (*types.Block, error) {
- c.state.cond.L.Lock()
- hash, ok := c.state.mainChain[height]
- c.state.cond.L.Unlock()
- if !ok {
- return nil, errors.New("can't find block in given hight")
+ node := c.index.NodeByHeight(height)
+ if node == nil {
+ return nil, errors.New("can't find block in given height")
+ }
+ return c.store.GetBlock(&node.Hash)
+}
+
+// GetHeaderByHash return a block header by given hash
+func (c *Chain) GetHeaderByHash(hash *bc.Hash) (*types.BlockHeader, error) {
+ node := c.index.GetNode(hash)
+ if node == nil {
+ return nil, errors.New("can't find block header in given hash")
}
- return c.GetBlockByHash(hash)
+ return node.BlockHeader(), nil
}
-// ConnectBlock append block to end of chain
-func (c *Chain) ConnectBlock(block *types.Block) error {
- c.state.cond.L.Lock()
- defer c.state.cond.L.Unlock()
- return c.connectBlock(block)
+// GetHeaderByHeight return a block header by given height
+func (c *Chain) GetHeaderByHeight(height uint64) (*types.BlockHeader, error) {
+ node := c.index.NodeByHeight(height)
+ if node == nil {
+ return nil, errors.New("can't find block header in given height")
+ }
+ return node.BlockHeader(), nil
+}
+
+func (c *Chain) calcReorganizeNodes(node *state.BlockNode) ([]*state.BlockNode, []*state.BlockNode) {
+ var attachNodes []*state.BlockNode
+ var detachNodes []*state.BlockNode
+
+ attachNode := node
+ for c.index.NodeByHeight(attachNode.Height) != attachNode {
+ attachNodes = append([]*state.BlockNode{attachNode}, attachNodes...)
+ attachNode = attachNode.Parent
+ }
+
+ detachNode := c.bestNode
+ for detachNode != attachNode {
+ detachNodes = append(detachNodes, detachNode)
+ detachNode = detachNode.Parent
+ }
+ return attachNodes, detachNodes
}
func (c *Chain) connectBlock(block *types.Block) (err error) {
bcBlock := types.MapBlock(block)
- utxoView := state.NewUtxoViewpoint()
- bcBlock.TransactionStatus, err = c.store.GetTransactionStatus(&bcBlock.ID)
- if err != nil {
+ if bcBlock.TransactionStatus, err = c.store.GetTransactionStatus(&bcBlock.ID); err != nil {
return err
}
+ utxoView := state.NewUtxoViewpoint()
if err := c.store.GetTransactionsUtxo(utxoView, bcBlock.Transactions); err != nil {
return err
}
return err
}
- blockHash := block.Hash()
- if err := c.setState(block, utxoView, map[uint64]*bc.Hash{block.Height: &blockHash}); err != nil {
+ node := c.index.GetNode(&bcBlock.ID)
+ if err := c.setState(node, utxoView); err != nil {
return err
}
return nil
}
-func (c *Chain) getReorganizeBlocks(block *types.Block) ([]*types.Block, []*types.Block) {
- attachBlocks := []*types.Block{}
- detachBlocks := []*types.Block{}
- ancestor := block
-
- for !c.inMainchain(ancestor) {
- attachBlocks = append([]*types.Block{ancestor}, attachBlocks...)
- ancestor, _ = c.GetBlockByHash(&ancestor.PreviousBlockHash)
- }
-
- for d := c.state.block; d.Hash() != ancestor.Hash(); d, _ = c.GetBlockByHash(&d.PreviousBlockHash) {
- detachBlocks = append(detachBlocks, d)
- }
-
- return attachBlocks, detachBlocks
-}
-
-func (c *Chain) reorganizeChain(block *types.Block) error {
- attachBlocks, detachBlocks := c.getReorganizeBlocks(block)
+func (c *Chain) reorganizeChain(node *state.BlockNode) error {
+ attachNodes, detachNodes := c.calcReorganizeNodes(node)
utxoView := state.NewUtxoViewpoint()
- chainChanges := map[uint64]*bc.Hash{}
- for _, d := range detachBlocks {
- detachBlock := types.MapBlock(d)
+ txsToRestore := map[bc.Hash]*types.Tx{}
+ for _, detachNode := range detachNodes {
+ b, err := c.store.GetBlock(&detachNode.Hash)
+ if err != nil {
+ return err
+ }
+
+ detachBlock := types.MapBlock(b)
if err := c.store.GetTransactionsUtxo(utxoView, detachBlock.Transactions); err != nil {
return err
}
if err := utxoView.DetachBlock(detachBlock, txStatus); err != nil {
return err
}
+
+ for _, tx := range b.Transactions {
+ txsToRestore[tx.ID] = tx
+ }
+ log.WithFields(log.Fields{"module": logModule, "height": node.Height, "hash": node.Hash.String()}).Debug("detach from mainchain")
}
- for _, a := range attachBlocks {
- attachBlock := types.MapBlock(a)
+ txsToRemove := map[bc.Hash]*types.Tx{}
+ for _, attachNode := range attachNodes {
+ b, err := c.store.GetBlock(&attachNode.Hash)
+ if err != nil {
+ return err
+ }
+
+ attachBlock := types.MapBlock(b)
if err := c.store.GetTransactionsUtxo(utxoView, attachBlock.Transactions); err != nil {
return err
}
if err != nil {
return err
}
-
if err := utxoView.ApplyBlock(attachBlock, txStatus); err != nil {
return err
}
- chainChanges[a.Height] = &attachBlock.ID
- }
- return c.setState(block, utxoView, chainChanges)
-}
+ for _, tx := range b.Transactions {
+ if _, ok := txsToRestore[tx.ID]; !ok {
+ txsToRemove[tx.ID] = tx
+ } else {
+ delete(txsToRestore, tx.ID)
+ }
+ }
-// SaveBlock will validate and save block into storage
-func (c *Chain) SaveBlock(block *types.Block) error {
- preBlock, _ := c.GetBlockByHash(&block.PreviousBlockHash)
- blockEnts := types.MapBlock(block)
- prevEnts := types.MapBlock(preBlock)
+ log.WithFields(log.Fields{"module": logModule, "height": node.Height, "hash": node.Hash.String()}).Debug("attach from mainchain")
+ }
- seed, err := c.GetSeed(block.Height, &block.PreviousBlockHash)
- if err != nil {
+ if err := c.setState(node, utxoView); err != nil {
return err
}
- if err := validation.ValidateBlock(blockEnts, prevEnts, seed, c.store); err != nil {
+ for txHash := range txsToRemove {
+ c.txPool.RemoveTransaction(&txHash)
+ }
+
+ for _, tx := range txsToRestore {
+ // the number of restored Tx should be very small or most of time ZERO
+ // Error returned from validation is ignored, tx could still be lost if validation fails.
+ // TODO: adjust tx timestamp so that it won't starve in pool.
+ if _, err := c.ValidateTx(tx); err != nil {
+ log.WithFields(log.Fields{"module": logModule, "tx_id": tx.Tx.ID.String(), "error": err}).Info("restore tx fail")
+ }
+ }
+
+ if len(txsToRestore) > 0 {
+ log.WithFields(log.Fields{"module": logModule, "num": len(txsToRestore)}).Debug("restore txs back to pool")
+ }
+
+ return nil
+}
+
+// SaveBlock will validate and save block into storage
+func (c *Chain) saveBlock(block *types.Block) error {
+ bcBlock := types.MapBlock(block)
+ parent := c.index.GetNode(&block.PreviousBlockHash)
+
+ if err := validation.ValidateBlock(bcBlock, parent); err != nil {
return errors.Sub(ErrBadBlock, err)
}
+ if err := c.store.SaveBlock(block, bcBlock.TransactionStatus); err != nil {
+ return err
+ }
- if err := c.store.SaveBlock(block, blockEnts.TransactionStatus, seed); err != nil {
+ c.orphanManage.Delete(&bcBlock.ID)
+ node, err := state.NewBlockNode(&block.BlockHeader, parent)
+ if err != nil {
return err
}
- blockHash := block.Hash()
- log.WithFields(log.Fields{"height": block.Height, "hash": blockHash.String()}).Info("Block saved on disk")
+ c.index.AddNode(node)
return nil
}
-func (c *Chain) findBestChainTail(block *types.Block) (bestBlock *types.Block) {
- bestBlock = block
+func (c *Chain) saveSubBlock(block *types.Block) *types.Block {
blockHash := block.Hash()
- preorphans, ok := c.orphanManage.preOrphans[blockHash]
+ prevOrphans, ok := c.orphanManage.GetPrevOrphans(&blockHash)
if !ok {
- return
+ return block
}
- for _, preorphan := range preorphans {
- orphanBlock, ok := c.orphanManage.Get(preorphan)
+ bestBlock := block
+ for _, prevOrphan := range prevOrphans {
+ orphanBlock, ok := c.orphanManage.Get(prevOrphan)
if !ok {
+ log.WithFields(log.Fields{"module": logModule, "hash": prevOrphan.String()}).Warning("saveSubBlock fail to get block from orphanManage")
continue
}
-
- if err := c.SaveBlock(orphanBlock); err != nil {
- log.WithFields(log.Fields{
- "height": block.Height,
- "hash": blockHash.String(),
- }).Errorf("findBestChainTail fail on save block %v", err)
+ if err := c.saveBlock(orphanBlock); err != nil {
+ log.WithFields(log.Fields{"module": logModule, "hash": prevOrphan.String(), "height": orphanBlock.Height}).Warning("saveSubBlock fail to save block")
continue
}
- if subResult := c.findBestChainTail(orphanBlock); subResult.Height > bestBlock.Height {
- bestBlock = subResult
+ if subBestBlock := c.saveSubBlock(orphanBlock); subBestBlock.Height > bestBlock.Height {
+ bestBlock = subBestBlock
}
}
+ return bestBlock
+}
- c.orphanManage.Delete(&blockHash)
- return
+type processBlockResponse struct {
+ isOrphan bool
+ err error
}
-// ProcessBlock is the entry for handle block insert
+type processBlockMsg struct {
+ block *types.Block
+ reply chan processBlockResponse
+}
+
+// ProcessBlock is the entry for chain update
func (c *Chain) ProcessBlock(block *types.Block) (bool, error) {
+ reply := make(chan processBlockResponse, 1)
+ c.processBlockCh <- &processBlockMsg{block: block, reply: reply}
+ response := <-reply
+ return response.isOrphan, response.err
+}
+
+func (c *Chain) blockProcesser() {
+ for msg := range c.processBlockCh {
+ isOrphan, err := c.processBlock(msg.block)
+ msg.reply <- processBlockResponse{isOrphan: isOrphan, err: err}
+ }
+}
+
+// ProcessBlock is the entry for handle block insert
+func (c *Chain) processBlock(block *types.Block) (bool, error) {
blockHash := block.Hash()
if c.BlockExist(&blockHash) {
- log.WithField("hash", blockHash.String()).Info("Skip process due to block already been handled")
- return false, nil
+ log.WithFields(log.Fields{"module": logModule, "hash": blockHash.String(), "height": block.Height}).Info("block has been processed")
+ return c.orphanManage.BlockExist(&blockHash), nil
}
- if !c.store.BlockExist(&block.PreviousBlockHash) {
+
+ if parent := c.index.GetNode(&block.PreviousBlockHash); parent == nil {
c.orphanManage.Add(block)
return true, nil
}
- if err := c.SaveBlock(block); err != nil {
+
+ if err := c.saveBlock(block); err != nil {
return false, err
}
- bestBlock := c.findBestChainTail(block)
- c.state.cond.L.Lock()
- defer c.state.cond.L.Unlock()
- if c.state.block.Hash() == bestBlock.PreviousBlockHash {
+ bestBlock := c.saveSubBlock(block)
+ bestBlockHash := bestBlock.Hash()
+ bestNode := c.index.GetNode(&bestBlockHash)
+
+ if bestNode.Parent == c.bestNode {
+ log.WithFields(log.Fields{"module": logModule}).Debug("append block to the end of mainchain")
return false, c.connectBlock(bestBlock)
}
- if bestBlock.Height > c.state.block.Height && bestBlock.Bits >= c.state.block.Bits {
- return false, c.reorganizeChain(bestBlock)
+ if bestNode.Height > c.bestNode.Height && bestNode.WorkSum.Cmp(c.bestNode.WorkSum) >= 0 {
+ log.WithFields(log.Fields{"module": logModule}).Debug("start to reorganize chain")
+ return false, c.reorganizeChain(bestNode)
}
-
return false, nil
}