OSDN Git Service

update from master
[bytom/vapor.git] / protocol / block.go
index 983e6cd..d5ef5cf 100644 (file)
@@ -3,7 +3,9 @@ package protocol
 import (
        log "github.com/sirupsen/logrus"
 
+       "github.com/vapor/config"
        "github.com/vapor/errors"
+       "github.com/vapor/event"
        "github.com/vapor/protocol/bc"
        "github.com/vapor/protocol/bc/types"
        "github.com/vapor/protocol/state"
@@ -15,7 +17,8 @@ var (
        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")
+       ErrBadStateRoot           = errors.New("invalid state merkle root")
+       errBelowIrreversibleBlock = errors.New("the height of block below the height of irreversible block")
 )
 
 // BlockExist check is a block in chain or orphan
@@ -25,7 +28,11 @@ func (c *Chain) BlockExist(hash *bc.Hash) bool {
 
 // GetBlockByHash return a block by given hash
 func (c *Chain) GetBlockByHash(hash *bc.Hash) (*types.Block, error) {
-       return c.store.GetBlock(hash)
+       node := c.index.GetNode(hash)
+       if node == nil {
+               return nil, errors.New("can't find block in given hash")
+       }
+       return c.store.GetBlock(hash, node.Height)
 }
 
 // GetBlockByHeight return a block header by given height
@@ -34,7 +41,7 @@ func (c *Chain) GetBlockByHeight(height uint64) (*types.Block, error) {
        if node == nil {
                return nil, errors.New("can't find block in given height")
        }
-       return c.store.GetBlock(&node.Hash)
+       return c.store.GetBlock(&node.Hash, height)
 }
 
 // GetHeaderByHash return a block header by given hash
@@ -88,17 +95,20 @@ func (c *Chain) connectBlock(block *types.Block) (err error) {
                return err
        }
 
-       voteResultMap := make(map[uint64]*state.VoteResult)
-       if err := c.bbft.ApplyBlock(voteResultMap, block); err != nil {
+       voteResult, err := c.consensusNodeManager.getBestVoteResult()
+       if err != nil {
+               return err
+       }
+       if err := voteResult.ApplyBlock(block); err != nil {
                return err
        }
 
        node := c.index.GetNode(&bcBlock.ID)
-       if c.bbft.isIrreversible(block) && block.Height > irreversibleNode.Height {
+       if c.isIrreversible(node) && block.Height > irreversibleNode.Height {
                irreversibleNode = node
        }
 
-       if err := c.setState(node, irreversibleNode, utxoView, voteResultMap); err != nil {
+       if err := c.setState(node, irreversibleNode, utxoView, []*state.VoteResult{voteResult}); err != nil {
                return err
        }
 
@@ -111,32 +121,34 @@ func (c *Chain) connectBlock(block *types.Block) (err error) {
 func (c *Chain) reorganizeChain(node *state.BlockNode) error {
        attachNodes, detachNodes := c.calcReorganizeNodes(node)
        utxoView := state.NewUtxoViewpoint()
-       voteResultMap := make(map[uint64]*state.VoteResult)
+       voteResults := []*state.VoteResult{}
        irreversibleNode := c.bestIrreversibleNode
-       
+       voteResult, err := c.consensusNodeManager.getBestVoteResult()
+       if err != nil {
+               return err
+       }
+
        for _, detachNode := range detachNodes {
-               b, err := c.store.GetBlock(&detachNode.Hash)
+               b, err := c.store.GetBlock(&detachNode.Hash, detachNode.Height)
                if err != nil {
                        return err
                }
 
-               if b.Height <= irreversibleNode.Height {
-                       return errors.New("the height of rollback block below the height of irreversible block")
-               }
-
                detachBlock := types.MapBlock(b)
                if err := c.store.GetTransactionsUtxo(utxoView, detachBlock.Transactions); err != nil {
                        return err
                }
+
                txStatus, err := c.GetTransactionStatus(&detachBlock.ID)
                if err != nil {
                        return err
                }
+
                if err := utxoView.DetachBlock(detachBlock, txStatus); err != nil {
                        return err
                }
-               
-               if err := c.bbft.DetachBlock(voteResultMap, b); err != nil {
+
+               if err := voteResult.DetachBlock(b); err != nil {
                        return err
                }
 
@@ -144,7 +156,7 @@ func (c *Chain) reorganizeChain(node *state.BlockNode) error {
        }
 
        for _, attachNode := range attachNodes {
-               b, err := c.store.GetBlock(&attachNode.Hash)
+               b, err := c.store.GetBlock(&attachNode.Hash, attachNode.Height)
                if err != nil {
                        return err
                }
@@ -153,44 +165,55 @@ func (c *Chain) reorganizeChain(node *state.BlockNode) error {
                if err := c.store.GetTransactionsUtxo(utxoView, attachBlock.Transactions); err != nil {
                        return err
                }
+
                txStatus, err := c.GetTransactionStatus(&attachBlock.ID)
                if err != nil {
                        return err
                }
+
                if err := utxoView.ApplyBlock(attachBlock, txStatus); err != nil {
                        return err
                }
 
-               if err := c.bbft.ApplyBlock(voteResultMap, b); err != nil {
+               if err := voteResult.ApplyBlock(b); err != nil {
                        return err
                }
 
-               if c.bbft.isIrreversible(b) && b.Height > irreversibleNode.Height {
+               if voteResult.IsFinalize() {
+                       voteResults = append(voteResults, voteResult.Fork())
+               }
+
+               if c.isIrreversible(attachNode) && attachNode.Height > irreversibleNode.Height {
                        irreversibleNode = attachNode
                }
 
                log.WithFields(log.Fields{"module": logModule, "height": node.Height, "hash": node.Hash.String()}).Debug("attach from mainchain")
        }
 
-       return c.setState(node, irreversibleNode, utxoView, voteResultMap)
+       if detachNodes[len(detachNodes)-1].Height <= c.bestIrreversibleNode.Height && irreversibleNode.Height <= c.bestIrreversibleNode.Height {
+               return errors.New("rollback block below the height of irreversible block")
+       }
+       voteResults = append(voteResults, voteResult.Fork())
+       return c.setState(node, irreversibleNode, utxoView, voteResults)
 }
 
 // SaveBlock will validate and save block into storage
 func (c *Chain) saveBlock(block *types.Block) error {
-       if err := c.bbft.ValidateBlock(block); err != nil {
+       if err := c.validateSign(block); err != nil {
                return errors.Sub(ErrBadBlock, err)
        }
 
        parent := c.index.GetNode(&block.PreviousBlockHash)
-       if err := validation.ValidateBlock(types.MapBlock(block), parent); err != nil {
+       bcBlock := types.MapBlock(block)
+       if err := validation.ValidateBlock(bcBlock, parent); err != nil {
                return errors.Sub(ErrBadBlock, err)
        }
 
-       if err := c.bbft.SignBlock(block); err != nil {
+       signature, err := c.SignBlock(block)
+       if err != nil {
                return errors.Sub(ErrBadBlock, err)
        }
 
-       bcBlock := types.MapBlock(block)
        if err := c.store.SaveBlock(block, bcBlock.TransactionStatus); err != nil {
                return err
        }
@@ -202,6 +225,13 @@ func (c *Chain) saveBlock(block *types.Block) error {
        }
 
        c.index.AddNode(node)
+
+       if len(signature) != 0 {
+               xPub := config.CommonConfig.PrivateKey().XPub()
+               if err := c.eventDispatcher.Post(event.BlockSignatureEvent{BlockHash: block.Hash(), Signature: signature, XPub: xPub[:]}); err != nil {
+                       return err
+               }
+       }
        return nil
 }
 
@@ -258,18 +288,13 @@ func (c *Chain) blockProcesser() {
 
 // ProcessBlock is the entry for handle block insert
 func (c *Chain) processBlock(block *types.Block) (bool, error) {
-       if block.Height <= c.bestIrreversibleNode.Height {
-               return false, errors.New("the height of block below the height of irreversible block")
-       }
-       
        blockHash := block.Hash()
        if c.BlockExist(&blockHash) {
                log.WithFields(log.Fields{"module": logModule, "hash": blockHash.String(), "height": block.Height}).Info("block has been processed")
                return c.orphanManage.BlockExist(&blockHash), nil
        }
 
-       parent := c.index.GetNode(&block.PreviousBlockHash)
-       if parent == nil {
+       if parent := c.index.GetNode(&block.PreviousBlockHash); parent == nil {
                c.orphanManage.Add(block)
                return true, nil
        }
@@ -282,6 +307,8 @@ func (c *Chain) processBlock(block *types.Block) (bool, error) {
        bestBlockHash := bestBlock.Hash()
        bestNode := c.index.GetNode(&bestBlockHash)
 
+       c.cond.L.Lock()
+       defer c.cond.L.Unlock()
        if bestNode.Parent == c.bestNode {
                log.WithFields(log.Fields{"module": logModule}).Debug("append block to the end of mainchain")
                return false, c.connectBlock(bestBlock)