OSDN Git Service

Fix mining (#113)
[bytom/vapor.git] / protocol / consensus_node_manager.go
index 62fc3ad..675b680 100644 (file)
@@ -3,7 +3,6 @@ package protocol
 import (
        "encoding/hex"
        "sort"
-       "time"
 
        "github.com/vapor/config"
        "github.com/vapor/errors"
@@ -14,8 +13,9 @@ import (
 )
 
 const (
-       numOfConsensusNode = 21
-       roundVoteBlockNums = 1000
+       NumOfConsensusNode = 21
+       RoundVoteBlockNums = 1000
+       MinVoteNum         = 5000000
 
        // BlockTimeInterval indicate product one block per 500 milliseconds
        BlockTimeInterval = 500
@@ -24,9 +24,8 @@ const (
 )
 
 var (
-       errHasNoChanceProductBlock = errors.New("the node has no chance to product a block in this round of voting")
-       errNotFoundConsensusNode   = errors.New("can not found consensus node")
-       errNotFoundBlockNode       = errors.New("can not find block node")
+       errNotFoundConsensusNode = errors.New("can not found consensus node")
+       errNotFoundBlockNode     = errors.New("can not find block node")
 )
 
 type consensusNode struct {
@@ -53,8 +52,8 @@ func newConsensusNodeManager(store Store, blockIndex *state.BlockIndex) *consens
        }
 }
 
-func (c *consensusNodeManager) getConsensusNode(blockHash *bc.Hash, pubkey string) (*consensusNode, error) {
-       consensusNodeMap, err := c.getConsensusNodesByVoteResult(blockHash)
+func (c *consensusNodeManager) getConsensusNode(prevBlockHash *bc.Hash, pubkey string) (*consensusNode, error) {
+       consensusNodeMap, err := c.getConsensusNodesByVoteResult(prevBlockHash)
        if err != nil {
                return nil, err
        }
@@ -66,13 +65,8 @@ func (c *consensusNodeManager) getConsensusNode(blockHash *bc.Hash, pubkey strin
        return node, nil
 }
 
-func (c *consensusNodeManager) isBlocker(blockHash *bc.Hash, pubkey string) (bool, error) {
-       blockNode := c.blockIndex.GetNode(blockHash)
-       if blockNode == nil {
-               return false, errNotFoundBlockNode
-       }
-
-       consensusNode, err := c.getConsensusNode(blockHash, pubkey)
+func (c *consensusNodeManager) isBlocker(prevBlockHash *bc.Hash, pubKey string, timeStamp uint64) (bool, error) {
+       consensusNode, err := c.getConsensusNode(prevBlockHash, pubKey)
        if err != nil && err != errNotFoundConsensusNode {
                return false, err
        }
@@ -81,91 +75,57 @@ func (c *consensusNodeManager) isBlocker(blockHash *bc.Hash, pubkey string) (boo
                return false, nil
        }
 
-       prevVoteRoundLastBlock, err := c.getPrevRoundVoteLastBlock(blockNode)
+       prevVoteRoundLastBlock, err := c.getPrevRoundVoteLastBlock(prevBlockHash)
        if err != nil {
                return false, err
        }
 
        startTimestamp := prevVoteRoundLastBlock.Timestamp + BlockTimeInterval
-
-       begin := getLastBlockTimeInTimeRange(startTimestamp, blockNode.Timestamp, consensusNode.order)
+       begin := getLastBlockTimeInTimeRange(startTimestamp, timeStamp, consensusNode.order)
        end := begin + BlockNumEachNode*BlockTimeInterval
-       return blockNode.Timestamp >= begin && blockNode.Timestamp < end, nil
-}
-
-func (c *consensusNodeManager) nextLeaderTimeRange(pubkey []byte, bestBlockHash *bc.Hash) (uint64, uint64, error) {
-       bestBlockNode := c.blockIndex.GetNode(bestBlockHash)
-       if bestBlockNode == nil {
-               return 0, 0, errNotFoundBlockNode
-       }
-
-       consensusNode, err := c.getConsensusNode(bestBlockHash, hex.EncodeToString(pubkey))
-       if err != nil {
-               return 0, 0, err
-       }
-
-       prevRoundLastBlock, err := c.getPrevRoundVoteLastBlock(bestBlockNode)
-       if err != nil {
-               return 0, 0, nil
-       }
-
-       startTime := prevRoundLastBlock.Timestamp + BlockTimeInterval
-       endTime := startTime + roundVoteBlockNums*BlockTimeInterval
-
-       nextLeaderTime, err := nextLeaderTimeHelper(startTime, endTime, uint64(time.Now().UnixNano()/1e6), consensusNode.order)
-       if err != nil {
-               return 0, 0, err
-       }
-
-       return nextLeaderTime, nextLeaderTime + BlockNumEachNode*BlockTimeInterval, nil
-}
-
-func nextLeaderTimeHelper(startTime, endTime, now, nodeOrder uint64) (uint64, error) {
-       nextLeaderTimestamp := getLastBlockTimeInTimeRange(startTime, now, nodeOrder)
-       roundBlockTime := uint64(BlockNumEachNode * numOfConsensusNode * BlockTimeInterval)
-
-       if int64(now-nextLeaderTimestamp) >= BlockNumEachNode*BlockTimeInterval {
-               nextLeaderTimestamp += roundBlockTime
-               if nextLeaderTimestamp >= endTime {
-                       return 0, errHasNoChanceProductBlock
-               }
-       }
-
-       return nextLeaderTimestamp, nil
+       return timeStamp >= begin && timeStamp < end, nil
 }
 
 func getLastBlockTimeInTimeRange(startTimestamp, endTimestamp, order uint64) uint64 {
        // One round of product block time for all consensus nodes
-       roundBlockTime := uint64(BlockNumEachNode * numOfConsensusNode * BlockTimeInterval)
+       roundBlockTime := uint64(BlockNumEachNode * NumOfConsensusNode * BlockTimeInterval)
        // The start time of the last round of product block
        lastRoundStartTime := startTimestamp + (endTimestamp-startTimestamp)/roundBlockTime*roundBlockTime
        // The time of product block of the consensus in last round
        return lastRoundStartTime + order*(BlockNumEachNode*BlockTimeInterval)
 }
 
-func (c *consensusNodeManager) getPrevRoundVoteLastBlock(blockNode *state.BlockNode) (*state.BlockNode, error) {
-       prevVoteRoundLastBlockHeight := blockNode.Height/roundVoteBlockNums*roundVoteBlockNums - 1
-       lastBlockNode := blockNode.GetParent(prevVoteRoundLastBlockHeight)
+func (c *consensusNodeManager) getPrevRoundVoteLastBlock(prevBlockHash *bc.Hash) (*state.BlockNode, error) {
+       prevBlockNode := c.blockIndex.GetNode(prevBlockHash)
+       if prevBlockNode == nil {
+               return nil, errNotFoundBlockNode
+       }
+
+       blockHeight := prevBlockNode.Height + 1
+
+       prevVoteRoundLastBlockHeight := blockHeight/RoundVoteBlockNums*RoundVoteBlockNums - 1
+       // first round
+       if blockHeight/RoundVoteBlockNums == 0 {
+               prevVoteRoundLastBlockHeight = 0
+       }
+
+       lastBlockNode := prevBlockNode.GetParent(prevVoteRoundLastBlockHeight)
        if lastBlockNode == nil {
                return nil, errNotFoundBlockNode
        }
        return lastBlockNode, nil
 }
 
-func (c *consensusNodeManager) getConsensusNodesByVoteResult(blockHash *bc.Hash) (map[string]*consensusNode, error) {
-       blockNode := c.blockIndex.GetNode(blockHash)
-       if blockNode == nil {
+func (c *consensusNodeManager) getConsensusNodesByVoteResult(prevBlockHash *bc.Hash) (map[string]*consensusNode, error) {
+       prevBlockNode := c.blockIndex.GetNode(prevBlockHash)
+       if prevBlockNode == nil {
                return nil, errNotFoundBlockNode
        }
 
-       seq := blockNode.Height / roundVoteBlockNums
-       if seq == 0 {
-               return initVoteResult(), nil
-       }
-
+       seq := (prevBlockNode.Height + 1) / RoundVoteBlockNums
        voteResult, err := c.store.GetVoteResult(seq)
        if err != nil {
-               // fail to find vote result, try to construct
+               // TODO find previous round vote
                voteResult = &state.VoteResult{
                        Seq:       seq,
                        NumOfVote: make(map[string]uint64),
@@ -173,7 +133,7 @@ func (c *consensusNodeManager) getConsensusNodesByVoteResult(blockHash *bc.Hash)
                }
        }
 
-       lastBlockNode, err := c.getPrevRoundVoteLastBlock(blockNode)
+       lastBlockNode, err := c.getPrevRoundVoteLastBlock(prevBlockHash)
        if err != nil {
                return nil, err
        }
@@ -182,12 +142,18 @@ func (c *consensusNodeManager) getConsensusNodesByVoteResult(blockHash *bc.Hash)
                return nil, err
        }
 
+       if len(voteResult.NumOfVote) == 0 {
+               return initConsensusNodes(), nil
+       }
+
        var nodes []*consensusNode
        for pubkey, voteNum := range voteResult.NumOfVote {
-               nodes = append(nodes, &consensusNode{
-                       pubkey:  pubkey,
-                       voteNum: voteNum,
-               })
+               if voteNum >= MinVoteNum {
+                       nodes = append(nodes, &consensusNode{
+                               pubkey:  pubkey,
+                               voteNum: voteNum,
+                       })
+               }
        }
        // In principle, there is no need to sort all voting nodes.
        // if there is a performance problem, consider the optimization later.
@@ -195,7 +161,7 @@ func (c *consensusNodeManager) getConsensusNodesByVoteResult(blockHash *bc.Hash)
        sort.Sort(consensusNodeSlice(nodes))
 
        result := make(map[string]*consensusNode)
-       for i := 0; i < numOfConsensusNode; i++ {
+       for i := 0; i < len(nodes) && i < NumOfConsensusNode; i++ {
                node := nodes[i]
                node.order = uint64(i)
                result[node.pubkey] = node
@@ -204,7 +170,9 @@ func (c *consensusNodeManager) getConsensusNodesByVoteResult(blockHash *bc.Hash)
 }
 
 func (c *consensusNodeManager) reorganizeVoteResult(voteResult *state.VoteResult, forkChainNode *state.BlockNode) error {
-       var mainChainNode *state.BlockNode
+       genesisBlockHash := config.GenesisBlock().Hash()
+       mainChainNode := c.blockIndex.GetNode(&genesisBlockHash)
+
        emptyHash := bc.Hash{}
        if voteResult.LastBlockHash != emptyHash {
                mainChainNode = c.blockIndex.GetNode(&voteResult.LastBlockHash)
@@ -216,14 +184,13 @@ func (c *consensusNodeManager) reorganizeVoteResult(voteResult *state.VoteResult
        var attachNodes []*state.BlockNode
        var detachNodes []*state.BlockNode
 
-       for forkChainNode.Hash != mainChainNode.Hash && forkChainNode.Height >= (voteResult.Seq-1)*roundVoteBlockNums {
-               attachNodes = append([]*state.BlockNode{forkChainNode}, attachNodes...)
-               forkChainNode = forkChainNode.Parent
-
-               if mainChainNode != nil && forkChainNode.Height == mainChainNode.Height {
+       for forkChainNode != nil && mainChainNode != nil && forkChainNode.Hash != mainChainNode.Hash {
+               if forkChainNode.Height == mainChainNode.Height {
                        detachNodes = append(detachNodes, mainChainNode)
                        mainChainNode = mainChainNode.Parent
                }
+               attachNodes = append([]*state.BlockNode{forkChainNode}, attachNodes...)
+               forkChainNode = forkChainNode.Parent
        }
 
        for _, node := range detachNodes {
@@ -251,27 +218,13 @@ func (c *consensusNodeManager) reorganizeVoteResult(voteResult *state.VoteResult
 }
 
 func (c *consensusNodeManager) applyBlock(voteResultMap map[uint64]*state.VoteResult, block *types.Block) (err error) {
-       voteSeq := block.Height / roundVoteBlockNums
-       voteResult := voteResultMap[voteSeq]
-
-       if voteResult == nil {
-               voteResult, err = c.store.GetVoteResult(voteSeq)
-               if err != nil && err != ErrNotFoundVoteResult {
-                       return err
-               }
-       }
-
-       if voteResult == nil {
-               voteResult = &state.VoteResult{
-                       Seq:           voteSeq,
-                       NumOfVote:     make(map[string]uint64),
-                       LastBlockHash: block.Hash(),
-               }
+       voteResult, err := c.getVoteResult(voteResultMap, block.Height)
+       if err != nil {
+               return err
        }
 
-       voteResultMap[voteSeq] = voteResult
-
-       if voteResult.LastBlockHash != block.PreviousBlockHash {
+       emptyHash := bc.Hash{}
+       if voteResult.LastBlockHash != emptyHash && voteResult.LastBlockHash != block.PreviousBlockHash {
                return errors.New("bbft append block error, the block parent hash is not equals last block hash of vote result")
        }
 
@@ -302,12 +255,69 @@ func (c *consensusNodeManager) applyBlock(voteResultMap map[uint64]*state.VoteRe
                }
        }
 
-       voteResult.Finalized = (block.Height+1)%roundVoteBlockNums == 0
+       voteResult.Finalized = (block.Height+1)%RoundVoteBlockNums == 0
        return nil
 }
 
+func (c *consensusNodeManager) getVoteResult(voteResultMap map[uint64]*state.VoteResult, blockHeight uint64) (*state.VoteResult, error) {
+       var err error
+       // This round of voting prepares for the next round
+       seq := blockHeight/RoundVoteBlockNums + 1
+       voteResult := voteResultMap[seq]
+       if blockHeight == 0 {
+               voteResult = &state.VoteResult{
+                       Seq:       seq,
+                       NumOfVote: make(map[string]uint64),
+                       Finalized: false,
+               }
+       }
+
+       if voteResult == nil {
+               prevVoteResult := voteResultMap[seq-1]
+               if prevVoteResult != nil {
+                       voteResult = &state.VoteResult{
+                               Seq:       seq,
+                               NumOfVote: prevVoteResult.NumOfVote,
+                               Finalized: false,
+                       }
+               }
+       }
+
+       if voteResult == nil {
+               voteResult, err = c.store.GetVoteResult(seq)
+               if err != nil && err != ErrNotFoundVoteResult {
+                       return nil, err
+               }
+       }
+
+       if voteResult == nil {
+               voteResult, err = c.store.GetVoteResult(seq - 1)
+               if err != nil && err != ErrNotFoundVoteResult {
+                       return nil, err
+               }
+
+               if voteResult != nil {
+                       // previous round voting must have finalized
+                       if !voteResult.Finalized {
+                               return nil, errors.New("previous round voting has not finalized")
+                       }
+
+                       voteResult.Seq = seq
+                       voteResult.Finalized = false
+                       voteResult.LastBlockHash = bc.Hash{}
+               }
+       }
+
+       if voteResult == nil {
+               return nil, errors.New("fail to get vote result")
+       }
+
+       voteResultMap[seq] = voteResult
+       return voteResult, nil
+}
+
 func (c *consensusNodeManager) detachBlock(voteResultMap map[uint64]*state.VoteResult, block *types.Block) error {
-       voteSeq := block.Height / roundVoteBlockNums
+       voteSeq := block.Height / RoundVoteBlockNums
        voteResult := voteResultMap[voteSeq]
 
        if voteResult == nil {
@@ -353,7 +363,7 @@ func (c *consensusNodeManager) detachBlock(voteResultMap map[uint64]*state.VoteR
        return nil
 }
 
-func initVoteResult() map[string]*consensusNode {
+func initConsensusNodes() map[string]*consensusNode {
        voteResult := map[string]*consensusNode{}
        for i, pubkey := range config.CommonConfig.Federation.Xpubs {
                pubkeyStr := pubkey.String()