OSDN Git Service

try to fix ban peer bug (#273)
[bytom/vapor.git] / api / bbft.go
1 package api
2
3 import (
4         "sort"
5
6         chainjson "github.com/vapor/encoding/json"
7 )
8
9 type voteInfo struct {
10         Vote    string `json:"vote"`
11         VoteNum uint64 `json:"vote_number"`
12 }
13
14 type voteInfoSlice []*voteInfo
15
16 func (v voteInfoSlice) Len() int           { return len(v) }
17 func (v voteInfoSlice) Less(i, j int) bool { return v[i].VoteNum > v[j].VoteNum }
18 func (v voteInfoSlice) Swap(i, j int)      { v[i], v[j] = v[j], v[i] }
19
20 func (a *API) getVoteResult(req struct {
21         BlockHash   chainjson.HexBytes `json:"block_hash"`
22         BlockHeight uint64             `json:"block_height"`
23 }) Response {
24         blockHash := hexBytesToHash(req.BlockHash)
25         if len(req.BlockHash) != 32 {
26                 blockHeader, err := a.chain.GetHeaderByHeight(req.BlockHeight)
27                 if err != nil {
28                         return NewErrorResponse(err)
29                 }
30
31                 blockHash = blockHeader.Hash()
32         }
33
34         consensusResult, err := a.chain.GetConsensusResultByHash(&blockHash)
35         if err != nil {
36                 return NewErrorResponse(err)
37         }
38
39         voteInfos := []*voteInfo{}
40         for pubKey, voteNum := range consensusResult.NumOfVote {
41                 voteInfos = append(voteInfos, &voteInfo{
42                         Vote:    pubKey,
43                         VoteNum: voteNum,
44                 })
45         }
46         sort.Sort(voteInfoSlice(voteInfos))
47         return NewSuccessResponse(voteInfos)
48 }