8 "github.com/vapor/config"
9 "github.com/vapor/errors"
10 "github.com/vapor/math/checked"
11 "github.com/vapor/protocol/bc"
12 "github.com/vapor/protocol/bc/types"
13 "github.com/vapor/protocol/state"
17 NumOfConsensusNode = 21
18 roundVoteBlockNums = 1000
20 // BlockTimeInterval indicate product one block per 500 milliseconds
21 BlockTimeInterval = 500
22 // BlockNumEachNode indicate product three blocks per node in succession
27 errNotFoundConsensusNode = errors.New("can not found consensus node")
28 errNotFoundBlockNode = errors.New("can not find block node")
31 type consensusNode struct {
37 type consensusNodeSlice []*consensusNode
39 func (c consensusNodeSlice) Len() int { return len(c) }
40 func (c consensusNodeSlice) Less(i, j int) bool { return c[i].voteNum > c[j].voteNum }
41 func (c consensusNodeSlice) Swap(i, j int) { c[i], c[j] = c[j], c[i] }
43 type consensusNodeManager struct {
45 blockIndex *state.BlockIndex
48 func newConsensusNodeManager(store Store, blockIndex *state.BlockIndex) *consensusNodeManager {
49 return &consensusNodeManager{
51 blockIndex: blockIndex,
55 func (c *consensusNodeManager) getConsensusNode(prevBlockHash *bc.Hash, pubkey string) (*consensusNode, error) {
56 consensusNodeMap, err := c.getConsensusNodesByVoteResult(prevBlockHash)
61 node, exist := consensusNodeMap[pubkey]
63 return nil, errNotFoundConsensusNode
68 func (c *consensusNodeManager) isBlocker(block *types.Block, pubKey string) (bool, error) {
69 consensusNode, err := c.getConsensusNode(&block.PreviousBlockHash, pubKey)
70 if err != nil && err != errNotFoundConsensusNode {
74 if consensusNode == nil {
78 prevVoteRoundLastBlock, err := c.getPrevRoundVoteLastBlock(&block.PreviousBlockHash)
83 startTimestamp := prevVoteRoundLastBlock.Timestamp + BlockTimeInterval
85 begin := getLastBlockTimeInTimeRange(startTimestamp, block.Timestamp, consensusNode.order)
86 end := begin + BlockNumEachNode*BlockTimeInterval
87 return block.Timestamp >= begin && block.Timestamp < end, nil
90 func (c *consensusNodeManager) nextLeaderTimeRange(pubkey []byte, bestBlockHash *bc.Hash) (uint64, uint64, error) {
91 bestBlockNode := c.blockIndex.GetNode(bestBlockHash)
92 if bestBlockNode == nil {
93 return 0, 0, errNotFoundBlockNode
96 consensusNode, err := c.getConsensusNode(&bestBlockNode.Parent.Hash, hex.EncodeToString(pubkey))
101 prevRoundLastBlock, err := c.getPrevRoundVoteLastBlock(&bestBlockNode.Parent.Hash)
106 startTime := prevRoundLastBlock.Timestamp + BlockTimeInterval
108 nextLeaderTime, err := nextLeaderTimeHelper(startTime, uint64(time.Now().UnixNano()/1e6), consensusNode.order)
113 return nextLeaderTime, nextLeaderTime + BlockNumEachNode*BlockTimeInterval, nil
116 func nextLeaderTimeHelper(startTime, now, nodeOrder uint64) (uint64, error) {
117 nextLeaderTimestamp := getLastBlockTimeInTimeRange(startTime, now, nodeOrder)
118 roundBlockTime := uint64(BlockNumEachNode * NumOfConsensusNode * BlockTimeInterval)
120 if now > nextLeaderTimestamp {
121 nextLeaderTimestamp += roundBlockTime
124 return nextLeaderTimestamp, nil
127 func getLastBlockTimeInTimeRange(startTimestamp, endTimestamp, order uint64) uint64 {
128 // One round of product block time for all consensus nodes
129 roundBlockTime := uint64(BlockNumEachNode * NumOfConsensusNode * BlockTimeInterval)
130 // The start time of the last round of product block
131 lastRoundStartTime := startTimestamp + (endTimestamp-startTimestamp)/roundBlockTime*roundBlockTime
132 // The time of product block of the consensus in last round
133 return lastRoundStartTime + order*(BlockNumEachNode*BlockTimeInterval)
136 func (c *consensusNodeManager) getPrevRoundVoteLastBlock(prevBlockHash *bc.Hash) (*state.BlockNode, error) {
137 prevBlockNode := c.blockIndex.GetNode(prevBlockHash)
138 if prevBlockNode == nil {
139 return nil, errNotFoundBlockNode
142 blockHeight := prevBlockNode.Height + 1
144 prevVoteRoundLastBlockHeight := blockHeight/roundVoteBlockNums*roundVoteBlockNums - 1
146 if blockHeight/roundVoteBlockNums == 0 {
147 prevVoteRoundLastBlockHeight = 0
150 lastBlockNode := prevBlockNode.GetParent(prevVoteRoundLastBlockHeight)
151 if lastBlockNode == nil {
152 return nil, errNotFoundBlockNode
154 return lastBlockNode, nil
157 func (c *consensusNodeManager) getConsensusNodesByVoteResult(prevBlockHash *bc.Hash) (map[string]*consensusNode, error) {
158 prevBlockNode := c.blockIndex.GetNode(prevBlockHash)
159 if prevBlockNode == nil {
160 return nil, errNotFoundBlockNode
163 seq := (prevBlockNode.Height + 1) / roundVoteBlockNums
165 return initVoteResult(), nil
168 voteResult, err := c.store.GetVoteResult(seq)
170 // fail to find vote result, try to construct
171 voteResult = &state.VoteResult{
173 NumOfVote: make(map[string]uint64),
178 lastBlockNode, err := c.getPrevRoundVoteLastBlock(prevBlockHash)
183 if err := c.reorganizeVoteResult(voteResult, lastBlockNode); err != nil {
187 var nodes []*consensusNode
188 for pubkey, voteNum := range voteResult.NumOfVote {
189 nodes = append(nodes, &consensusNode{
194 // In principle, there is no need to sort all voting nodes.
195 // if there is a performance problem, consider the optimization later.
196 // TODO not consider the same number of votes
197 sort.Sort(consensusNodeSlice(nodes))
199 result := make(map[string]*consensusNode)
200 for i := 0; i < len(nodes) && i < NumOfConsensusNode; i++ {
202 node.order = uint64(i)
203 result[node.pubkey] = node
208 func (c *consensusNodeManager) reorganizeVoteResult(voteResult *state.VoteResult, forkChainNode *state.BlockNode) error {
209 var mainChainNode *state.BlockNode
210 emptyHash := bc.Hash{}
211 if voteResult.LastBlockHash != emptyHash {
212 mainChainNode = c.blockIndex.GetNode(&voteResult.LastBlockHash)
213 if mainChainNode == nil {
214 return errNotFoundBlockNode
218 var attachNodes []*state.BlockNode
219 var detachNodes []*state.BlockNode
221 for forkChainNode.Hash != mainChainNode.Hash && forkChainNode.Height >= (voteResult.Seq-1)*roundVoteBlockNums {
222 attachNodes = append([]*state.BlockNode{forkChainNode}, attachNodes...)
223 forkChainNode = forkChainNode.Parent
225 if mainChainNode != nil && forkChainNode.Height == mainChainNode.Height {
226 detachNodes = append(detachNodes, mainChainNode)
227 mainChainNode = mainChainNode.Parent
231 for _, node := range detachNodes {
232 block, err := c.store.GetBlock(&node.Hash)
237 if err := c.detachBlock(map[uint64]*state.VoteResult{voteResult.Seq: voteResult}, block); err != nil {
242 for _, node := range attachNodes {
243 block, err := c.store.GetBlock(&node.Hash)
248 if err := c.applyBlock(map[uint64]*state.VoteResult{voteResult.Seq: voteResult}, block); err != nil {
255 func (c *consensusNodeManager) applyBlock(voteResultMap map[uint64]*state.VoteResult, block *types.Block) (err error) {
256 voteSeq := block.Height / roundVoteBlockNums
257 voteResult, err := c.getVoteResult(voteResultMap, voteSeq)
262 emptyHash := bc.Hash{}
263 if voteResult.LastBlockHash != emptyHash && voteResult.LastBlockHash != block.PreviousBlockHash {
264 return errors.New("bbft append block error, the block parent hash is not equals last block hash of vote result")
267 for _, tx := range block.Transactions {
268 for _, input := range tx.Inputs {
269 unVoteInput, ok := input.TypedInput.(*types.UnvoteInput)
274 pubkey := hex.EncodeToString(unVoteInput.Vote)
275 voteResult.NumOfVote[pubkey], ok = checked.SubUint64(voteResult.NumOfVote[pubkey], unVoteInput.Amount)
277 return errVotingOperationOverFlow
280 for _, output := range tx.Outputs {
281 voteOutput, ok := output.TypedOutput.(*types.VoteTxOutput)
286 pubkey := hex.EncodeToString(voteOutput.Vote)
287 voteResult.NumOfVote[pubkey], ok = checked.AddUint64(voteResult.NumOfVote[pubkey], voteOutput.Amount)
289 return errVotingOperationOverFlow
294 voteResult.Finalized = (block.Height+1)%roundVoteBlockNums == 0
298 func (c *consensusNodeManager) getVoteResult(voteResultMap map[uint64]*state.VoteResult, seq uint64) (*state.VoteResult, error) {
300 voteResult := voteResultMap[seq]
301 if voteResult == nil {
302 prevVoteResult := voteResultMap[seq - 1]
303 voteResult = &state.VoteResult {
305 NumOfVote: prevVoteResult.NumOfVote,
310 if voteResult == nil {
311 voteResult, err = c.store.GetVoteResult(seq)
312 if err != nil && err != ErrNotFoundVoteResult {
317 if voteResult == nil {
318 voteResult, err := c.store.GetVoteResult(seq - 1)
319 if err != nil && err != ErrNotFoundVoteResult {
322 // previous round voting must have finalized
323 if !voteResult.Finalized {
324 return nil, errors.New("previous round voting has not finalized")
327 voteResult.Finalized = false
328 voteResult.LastBlockHash = bc.Hash{}
330 voteResultMap[seq] = voteResult
331 return voteResult, nil
334 func (c *consensusNodeManager) detachBlock(voteResultMap map[uint64]*state.VoteResult, block *types.Block) error {
335 voteSeq := block.Height / roundVoteBlockNums
336 voteResult := voteResultMap[voteSeq]
338 if voteResult == nil {
339 voteResult, err := c.store.GetVoteResult(voteSeq)
343 voteResultMap[voteSeq] = voteResult
346 if voteResult.LastBlockHash != block.Hash() {
347 return errors.New("bbft detach block error, the block hash is not equals last block hash of vote result")
350 for _, tx := range block.Transactions {
351 for _, input := range tx.Inputs {
352 unVoteInput, ok := input.TypedInput.(*types.UnvoteInput)
357 pubkey := hex.EncodeToString(unVoteInput.Vote)
358 voteResult.NumOfVote[pubkey], ok = checked.AddUint64(voteResult.NumOfVote[pubkey], unVoteInput.Amount)
360 return errVotingOperationOverFlow
363 for _, output := range tx.Outputs {
364 voteOutput, ok := output.TypedOutput.(*types.VoteTxOutput)
369 pubkey := hex.EncodeToString(voteOutput.Vote)
370 voteResult.NumOfVote[pubkey], ok = checked.SubUint64(voteResult.NumOfVote[pubkey], voteOutput.Amount)
372 return errVotingOperationOverFlow
377 voteResult.Finalized = false
381 func initVoteResult() map[string]*consensusNode {
382 voteResult := map[string]*consensusNode{}
383 for i, pubkey := range config.CommonConfig.Federation.Xpubs {
384 pubkeyStr := pubkey.String()
385 voteResult[pubkeyStr] = &consensusNode{pubkey: pubkeyStr, voteNum: 0, order: uint64(i)}