OSDN Git Service

add get-consensus-nodes api (#159)
[bytom/vapor.git] / protocol / consensus_node_manager.go
index d116eb0..3b5f9ed 100644 (file)
 package protocol
 
 import (
-       "encoding/hex"
-       "fmt"
-       "sort"
-       "sync"
-       "time"
-
+       "github.com/vapor/consensus"
        "github.com/vapor/errors"
+       "github.com/vapor/protocol/bc"
        "github.com/vapor/protocol/state"
 )
 
-const (
-       numOfConsensusNode = 21
-       roundVoteBlockNums = 1000
-
-       // product one block per 500 milliseconds
-       blockTimeInterval = 500
-       blockNumEachNode  = 3
-)
-
 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")
-       errVoteResultIsNotfinalized = errors.New("vote result is not finalized")
+       errNotFoundConsensusNode = errors.New("can not found consensus node")
+       errNotFoundBlockNode     = errors.New("can not find block node")
 )
 
-type consensusNode struct {
-       pubkey  string
-       voteNum uint64
-       order   uint64
-}
-
-type consensusNodeSlice []*consensusNode
-
-func (c consensusNodeSlice) Len() int           { return len(c) }
-func (c consensusNodeSlice) Less(i, j int) bool { return c[i].voteNum > c[j].voteNum }
-func (c consensusNodeSlice) Swap(i, j int)      { c[i], c[j] = c[j], c[i] }
-
 type consensusNodeManager struct {
-       consensusNodeMap     map[string]*consensusNode
-       effectiveStartHeight uint64
-       store                Store
-       blockIndex           *state.BlockIndex
-       sync.RWMutex
+       store      Store
+       blockIndex *state.BlockIndex
 }
 
 func newConsensusNodeManager(store Store, blockIndex *state.BlockIndex) *consensusNodeManager {
        return &consensusNodeManager{
-               consensusNodeMap:     make(map[string]*consensusNode),
-               effectiveStartHeight: 1,
-               store:                store,
-               blockIndex:           blockIndex,
+               store:      store,
+               blockIndex: blockIndex,
        }
 }
 
-func (c *consensusNodeManager) getConsensusNode(height uint64, pubkey string) (*consensusNode, error) {
-       defer c.RUnlock()
-       c.RLock()
-       if height >= c.effectiveStartHeight+roundVoteBlockNums {
-               return nil, errors.New("the vote has not been completed for the specified block height ")
-       }
-
-       var err error
-       consensusNodeMap := c.consensusNodeMap
-       // query history vote result
-       if height < c.effectiveStartHeight {
-               consensusNodeMap, err = c.getConsensusNodesByVoteResult(height)
-               if err != nil {
-                       return nil, err
-               }
+func (c *consensusNodeManager) getConsensusNode(prevBlockHash *bc.Hash, pubkey string) (*state.ConsensusNode, error) {
+       consensusNodeMap, err := c.getConsensusNodes(prevBlockHash)
+       if err != nil {
+               return nil, err
        }
 
        node, exist := consensusNodeMap[pubkey]
        if !exist {
-               return node, errNotFoundConsensusNode
+               return nil, errNotFoundConsensusNode
        }
        return node, nil
 }
 
-func (c *consensusNodeManager) isBlocker(height uint64, blockTimestamp uint64, pubkey string) (bool, error) {
-       prevVoteRoundLastBlock := c.blockIndex.NodeByHeight(height - 1)
-       startTimestamp := prevVoteRoundLastBlock.Timestamp + blockTimeInterval
-
-       consensusNodeMap, err := c.getConsensusNodesByVoteResult(height)
+func (c *consensusNodeManager) isBlocker(prevBlockHash *bc.Hash, pubKey string, timeStamp uint64) (bool, error) {
+       consensusNodeMap, err := c.getConsensusNodes(prevBlockHash)
        if err != nil {
                return false, err
        }
 
-       blockerNode, exist := consensusNodeMap[pubkey]
-       if !exist {
+       consensusNode := consensusNodeMap[pubKey]
+       if consensusNode == nil {
                return false, nil
        }
 
-       begin := getLastBlockTimeInTimeRange(startTimestamp, blockTimestamp, blockerNode.order)
-       end := begin + blockNumEachNode*blockTimeInterval
-       return blockTimestamp >= begin && blockTimestamp < end, nil
-}
-
-func (c *consensusNodeManager) nextLeaderTime(pubkey []byte, bestBlockTimestamp, bestBlockHeight uint64) (*time.Time, error) {
-       defer c.RUnlock()
-       c.RLock()
-
-       startHeight := c.effectiveStartHeight
-       prevRoundLastBlock := c.blockIndex.NodeByHeight(startHeight - 1)
-       startTime := prevRoundLastBlock.Timestamp + blockTimeInterval
-       endTime := bestBlockTimestamp + (roundVoteBlockNums-bestBlockHeight%roundVoteBlockNums)*blockTimeInterval
-
-       consensusNode, exist := c.consensusNodeMap[hex.EncodeToString(pubkey)]
-       if !exist {
-               return nil, fmt.Errorf("pubkey:%s is not consensus node", hex.EncodeToString(pubkey))
-       }
-
-       nextLeaderTime, err := nextLeaderTimeHelper(startTime, endTime, uint64(time.Now().UnixNano()/1e6), consensusNode.order)
+       prevVoteRoundLastBlock, err := c.getPrevRoundLastBlock(prevBlockHash)
        if err != nil {
-               return nil, err
+               return false, err
        }
 
-       return nextLeaderTime, nil
+       startTimestamp := prevVoteRoundLastBlock.Timestamp + consensus.BlockTimeInterval
+       begin := getLastBlockTimeInTimeRange(startTimestamp, timeStamp, consensusNode.Order, uint64(len(consensusNodeMap)))
+       end := begin + consensus.BlockNumEachNode*consensus.BlockTimeInterval
+       return timeStamp >= begin && timeStamp < end, nil
 }
 
-func nextLeaderTimeHelper(startTime, endTime, now, nodeOrder uint64) (*time.Time, error) {
-       nextLeaderTimestamp := getLastBlockTimeInTimeRange(startTime, now, nodeOrder)
-       roundBlockTime := uint64(blockNumEachNode * numOfConsensusNode * blockTimeInterval)
+func getLastBlockTimeInTimeRange(startTimestamp, endTimestamp, order, numOfConsensusNode uint64) uint64 {
+       // One round of product block time for all consensus nodes
+       roundBlockTime := consensus.BlockNumEachNode * numOfConsensusNode * consensus.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*(consensus.BlockNumEachNode*consensus.BlockTimeInterval)
+}
 
-       if int64(now-nextLeaderTimestamp) >= blockNumEachNode*blockTimeInterval {
-               nextLeaderTimestamp += roundBlockTime
-               if nextLeaderTimestamp >= endTime {
-                       return nil, errHasNoChanceProductBlock
-               }
+func (c *consensusNodeManager) getPrevRoundLastBlock(prevBlockHash *bc.Hash) (*state.BlockNode, error) {
+       node := c.blockIndex.GetNode(prevBlockHash)
+       if node == nil {
+               return nil, errNotFoundBlockNode
        }
 
-       nextLeaderTime := time.Unix(int64(nextLeaderTimestamp)/1000, (int64(nextLeaderTimestamp)%1000)*1e6)
-       return &nextLeaderTime, nil
+       for node.Height%consensus.RoundVoteBlockNums != 0 {
+               node = node.Parent
+       }
+       return node, nil
 }
 
-// updateConsensusNodes used to update consensus node after each round of voting
-func (c *consensusNodeManager) updateConsensusNodes(bestBlockHeight uint64) error {
-       defer c.Unlock()
-       c.Lock()
+func (c *consensusNodeManager) getConsensusNodes(prevBlockHash *bc.Hash) (map[string]*state.ConsensusNode, error) {
+       prevBlockNode := c.blockIndex.GetNode(prevBlockHash)
+       if prevBlockNode == nil {
+               return nil, errNotFoundBlockNode
+       }
 
-       consensusNodeMap, err := c.getConsensusNodesByVoteResult(bestBlockHeight)
-       if err != nil && err != errVoteResultIsNotfinalized {
-               return err
+       preSeq := state.CalcVoteSeq(prevBlockNode.Height+1) - 1
+       if bestSeq := state.CalcVoteSeq(c.blockIndex.BestNode().Height); preSeq > bestSeq {
+               preSeq = bestSeq
        }
 
-       if err == errVoteResultIsNotfinalized {
-               return nil
+       lastBlockNode, err := c.getPrevRoundLastBlock(prevBlockHash)
+       if err != nil {
+               return nil, err
        }
 
-       c.consensusNodeMap = consensusNodeMap
-       c.effectiveStartHeight = bestBlockHeight / roundVoteBlockNums * roundVoteBlockNums
-       return nil
-}
+       voteResult, err := c.getVoteResult(preSeq, lastBlockNode)
+       if err != nil {
+               return nil, err
+       }
 
-func getLastBlockTimeInTimeRange(startTimestamp, endTimestamp, order uint64) uint64 {
-       // One round of product block time for all consensus nodes
-       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)
+       return voteResult.ConsensusNodes()
 }
 
-func (c *consensusNodeManager) getConsensusNodesByVoteResult(blockHeight uint64) (map[string]*consensusNode, error) {
-       defer c.RUnlock()
-       c.RLock()
-       if blockHeight >= c.effectiveStartHeight+roundVoteBlockNums {
-               return nil, errors.New("the given block height is greater than current vote start height")
-       }
+func (c *consensusNodeManager) getBestVoteResult() (*state.VoteResult, error) {
+       blockNode := c.blockIndex.BestNode()
+       seq := state.CalcVoteSeq(blockNode.Height)
+       return c.getVoteResult(seq, blockNode)
+}
 
-       if blockHeight >= c.effectiveStartHeight {
-               return c.consensusNodeMap, nil
+// getVoteResult return the vote result
+// seq represent the sequence of vote
+// blockNode represent the chain in which the result of the vote is located
+// Voting results need to be adjusted according to the chain 
+func (c *consensusNodeManager) getVoteResult(seq uint64, blockNode *state.BlockNode) (*state.VoteResult, error) {
+       voteResult, err := c.store.GetVoteResult(seq)
+       if err != nil {
+               return nil, err
        }
 
-       voteResult, err := c.store.GetVoteResult(blockHeight / roundVoteBlockNums)
-       if err != nil {
+       if err := c.reorganizeVoteResult(voteResult, blockNode); err != nil {
                return nil, err
        }
 
-       if !voteResult.Finalized {
-               return nil, errVoteResultIsNotfinalized
+       return voteResult, nil
+}
+
+func (c *consensusNodeManager) reorganizeVoteResult(voteResult *state.VoteResult, node *state.BlockNode) error {
+       mainChainNode := c.blockIndex.GetNode(&voteResult.BlockHash)
+       var attachNodes []*state.BlockNode
+       var detachNodes []*state.BlockNode
+       for forkChainNode := node; mainChainNode != forkChainNode; {
+               var forChainRollback, mainChainRollBack bool
+               if forChainRollback = forkChainNode.Height >= mainChainNode.Height; forChainRollback {
+                       attachNodes = append([]*state.BlockNode{forkChainNode}, attachNodes...)
+               } 
+               if mainChainRollBack = forkChainNode.Height <= mainChainNode.Height; mainChainRollBack {
+                       detachNodes = append(detachNodes, mainChainNode)
+               }
+               if forChainRollback {
+                       forkChainNode = forkChainNode.Parent
+               }
+               if mainChainRollBack {
+                       mainChainNode = mainChainNode.Parent
+               }
        }
 
-       var nodes []*consensusNode
-       for pubkey, voteNum := range voteResult.NumOfVote {
-               nodes = append(nodes, &consensusNode{
-                       pubkey:  pubkey,
-                       voteNum: voteNum,
-               })
+       for _, node := range detachNodes {
+               block, err := c.store.GetBlock(&node.Hash)
+               if err != nil {
+                       return err
+               }
+
+               if err := voteResult.DetachBlock(block); err != nil {
+                       return err
+               }
        }
-       // In principle, there is no need to sort all voting nodes.
-       // if there is a performance problem, consider the optimization later.
-       // TODO not consider the same number of votes
-       sort.Sort(consensusNodeSlice(nodes))
 
-       result := make(map[string]*consensusNode)
-       for i := 0; i < numOfConsensusNode; i++ {
-               node := nodes[i]
-               node.order = uint64(i)
-               result[node.pubkey] = node
+       for _, node := range attachNodes {
+               block, err := c.store.GetBlock(&node.Hash)
+               if err != nil {
+                       return err
+               }
+
+               if err := voteResult.ApplyBlock(block); err != nil {
+                       return err
+               }
        }
-       return result, nil
+       return nil
 }