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, prevBlockHash *bc.Hash) (uint64, uint64, error) {
91 consensusNode, err := c.getConsensusNode(prevBlockHash, hex.EncodeToString(pubkey))
96 prevRoundLastBlock, err := c.getPrevRoundVoteLastBlock(prevBlockHash)
101 startTime := prevRoundLastBlock.Timestamp + BlockTimeInterval
103 nextLeaderTime, err := nextLeaderTimeHelper(startTime, uint64(time.Now().UnixNano()/1e6), consensusNode.order)
108 return nextLeaderTime, nextLeaderTime + BlockNumEachNode*BlockTimeInterval, nil
111 func nextLeaderTimeHelper(startTime, now, nodeOrder uint64) (uint64, error) {
112 nextLeaderTimestamp := getLastBlockTimeInTimeRange(startTime, now, nodeOrder)
113 roundBlockTime := uint64(BlockNumEachNode * NumOfConsensusNode * BlockTimeInterval)
115 if now > nextLeaderTimestamp {
116 nextLeaderTimestamp += roundBlockTime
119 return nextLeaderTimestamp, nil
122 func getLastBlockTimeInTimeRange(startTimestamp, endTimestamp, order uint64) uint64 {
123 // One round of product block time for all consensus nodes
124 roundBlockTime := uint64(BlockNumEachNode * NumOfConsensusNode * BlockTimeInterval)
125 // The start time of the last round of product block
126 lastRoundStartTime := startTimestamp + (endTimestamp-startTimestamp)/roundBlockTime*roundBlockTime
127 // The time of product block of the consensus in last round
128 return lastRoundStartTime + order*(BlockNumEachNode*BlockTimeInterval)
131 func (c *consensusNodeManager) getPrevRoundVoteLastBlock(prevBlockHash *bc.Hash) (*state.BlockNode, error) {
132 prevBlockNode := c.blockIndex.GetNode(prevBlockHash)
133 if prevBlockNode == nil {
134 return nil, errNotFoundBlockNode
137 blockHeight := prevBlockNode.Height + 1
139 prevVoteRoundLastBlockHeight := blockHeight/RoundVoteBlockNums*RoundVoteBlockNums - 1
141 if blockHeight/RoundVoteBlockNums == 0 {
142 prevVoteRoundLastBlockHeight = 0
145 lastBlockNode := prevBlockNode.GetParent(prevVoteRoundLastBlockHeight)
146 if lastBlockNode == nil {
147 return nil, errNotFoundBlockNode
149 return lastBlockNode, nil
152 func (c *consensusNodeManager) getConsensusNodesByVoteResult(prevBlockHash *bc.Hash) (map[string]*consensusNode, error) {
153 prevBlockNode := c.blockIndex.GetNode(prevBlockHash)
154 if prevBlockNode == nil {
155 return nil, errNotFoundBlockNode
158 seq := (prevBlockNode.Height + 1) / RoundVoteBlockNums
159 voteResult, err := c.store.GetVoteResult(seq)
161 // TODO find previous round vote
162 voteResult = &state.VoteResult{
164 NumOfVote: make(map[string]uint64),
169 lastBlockNode, err := c.getPrevRoundVoteLastBlock(prevBlockHash)
174 if err := c.reorganizeVoteResult(voteResult, lastBlockNode); err != nil {
178 if len(voteResult.NumOfVote) == 0 {
179 return initConsensusNodes(), nil
182 var nodes []*consensusNode
183 for pubkey, voteNum := range voteResult.NumOfVote {
184 nodes = append(nodes, &consensusNode{
189 // In principle, there is no need to sort all voting nodes.
190 // if there is a performance problem, consider the optimization later.
191 // TODO not consider the same number of votes
192 sort.Sort(consensusNodeSlice(nodes))
194 result := make(map[string]*consensusNode)
195 for i := 0; i < len(nodes) && i < NumOfConsensusNode; i++ {
197 node.order = uint64(i)
198 result[node.pubkey] = node
203 func (c *consensusNodeManager) reorganizeVoteResult(voteResult *state.VoteResult, forkChainNode *state.BlockNode) error {
204 genesisBlockHash := config.GenesisBlock().Hash()
205 mainChainNode := c.blockIndex.GetNode(&genesisBlockHash)
207 emptyHash := bc.Hash{}
208 if voteResult.LastBlockHash != emptyHash {
209 mainChainNode = c.blockIndex.GetNode(&voteResult.LastBlockHash)
210 if mainChainNode == nil {
211 return errNotFoundBlockNode
215 var attachNodes []*state.BlockNode
216 var detachNodes []*state.BlockNode
218 for forkChainNode != nil && mainChainNode != nil && forkChainNode.Hash != mainChainNode.Hash {
219 if forkChainNode.Height == mainChainNode.Height {
220 detachNodes = append(detachNodes, mainChainNode)
221 mainChainNode = mainChainNode.Parent
223 attachNodes = append([]*state.BlockNode{forkChainNode}, attachNodes...)
224 forkChainNode = forkChainNode.Parent
227 for _, node := range detachNodes {
228 block, err := c.store.GetBlock(&node.Hash)
233 if err := c.detachBlock(map[uint64]*state.VoteResult{voteResult.Seq: voteResult}, block); err != nil {
238 for _, node := range attachNodes {
239 block, err := c.store.GetBlock(&node.Hash)
244 if err := c.applyBlock(map[uint64]*state.VoteResult{voteResult.Seq: voteResult}, block); err != nil {
251 func (c *consensusNodeManager) applyBlock(voteResultMap map[uint64]*state.VoteResult, block *types.Block) (err error) {
252 voteResult, err := c.getVoteResult(voteResultMap, block.Height)
257 emptyHash := bc.Hash{}
258 if voteResult.LastBlockHash != emptyHash && voteResult.LastBlockHash != block.PreviousBlockHash {
259 return errors.New("bbft append block error, the block parent hash is not equals last block hash of vote result")
262 for _, tx := range block.Transactions {
263 for _, input := range tx.Inputs {
264 unVoteInput, ok := input.TypedInput.(*types.UnvoteInput)
269 pubkey := hex.EncodeToString(unVoteInput.Vote)
270 voteResult.NumOfVote[pubkey], ok = checked.SubUint64(voteResult.NumOfVote[pubkey], unVoteInput.Amount)
272 return errVotingOperationOverFlow
275 for _, output := range tx.Outputs {
276 voteOutput, ok := output.TypedOutput.(*types.VoteTxOutput)
281 pubkey := hex.EncodeToString(voteOutput.Vote)
282 voteResult.NumOfVote[pubkey], ok = checked.AddUint64(voteResult.NumOfVote[pubkey], voteOutput.Amount)
284 return errVotingOperationOverFlow
289 voteResult.Finalized = (block.Height+1)%RoundVoteBlockNums == 0
293 func (c *consensusNodeManager) getVoteResult(voteResultMap map[uint64]*state.VoteResult, blockHeight uint64) (*state.VoteResult, error) {
295 // This round of voting prepares for the next round
296 seq := blockHeight /RoundVoteBlockNums + 1
297 voteResult := voteResultMap[seq]
298 if blockHeight == 0 {
299 voteResult = &state.VoteResult{
301 NumOfVote: make(map[string]uint64),
306 if voteResult == nil {
307 prevVoteResult := voteResultMap[seq-1]
308 if prevVoteResult != nil {
309 voteResult = &state.VoteResult{
311 NumOfVote: prevVoteResult.NumOfVote,
317 if voteResult == nil {
318 voteResult, err = c.store.GetVoteResult(seq)
319 if err != nil && err != ErrNotFoundVoteResult {
324 if voteResult == nil {
325 voteResult, err = c.store.GetVoteResult(seq - 1)
326 if err != nil && err != ErrNotFoundVoteResult {
330 if voteResult != nil {
331 // previous round voting must have finalized
332 if !voteResult.Finalized {
333 return nil, errors.New("previous round voting has not finalized")
337 voteResult.Finalized = false
338 voteResult.LastBlockHash = bc.Hash{}
342 if voteResult == nil {
343 return nil, errors.New("fail to get vote result")
346 voteResultMap[seq] = voteResult
347 return voteResult, nil
350 func (c *consensusNodeManager) detachBlock(voteResultMap map[uint64]*state.VoteResult, block *types.Block) error {
351 voteSeq := block.Height / RoundVoteBlockNums
352 voteResult := voteResultMap[voteSeq]
354 if voteResult == nil {
355 voteResult, err := c.store.GetVoteResult(voteSeq)
359 voteResultMap[voteSeq] = voteResult
362 if voteResult.LastBlockHash != block.Hash() {
363 return errors.New("bbft detach block error, the block hash is not equals last block hash of vote result")
366 for _, tx := range block.Transactions {
367 for _, input := range tx.Inputs {
368 unVoteInput, ok := input.TypedInput.(*types.UnvoteInput)
373 pubkey := hex.EncodeToString(unVoteInput.Vote)
374 voteResult.NumOfVote[pubkey], ok = checked.AddUint64(voteResult.NumOfVote[pubkey], unVoteInput.Amount)
376 return errVotingOperationOverFlow
379 for _, output := range tx.Outputs {
380 voteOutput, ok := output.TypedOutput.(*types.VoteTxOutput)
385 pubkey := hex.EncodeToString(voteOutput.Vote)
386 voteResult.NumOfVote[pubkey], ok = checked.SubUint64(voteResult.NumOfVote[pubkey], voteOutput.Amount)
388 return errVotingOperationOverFlow
393 voteResult.Finalized = false
397 func initConsensusNodes() map[string]*consensusNode {
398 voteResult := map[string]*consensusNode{}
399 for i, pubkey := range config.CommonConfig.Federation.Xpubs {
400 pubkeyStr := pubkey.String()
401 voteResult[pubkeyStr] = &consensusNode{pubkey: pubkeyStr, voteNum: 0, order: uint64(i)}