OSDN Git Service

add get-consensus-nodes api (#159)
[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 func (v voteInfoSlice) Len() int { return len(v) }
16 func (v voteInfoSlice) Less(i, j int) bool { return v[i].VoteNum > v[j].VoteNum }
17 func (v voteInfoSlice) Swap(i, j int) { v[i], v[j] = v[j], v[i] }
18
19 func (a *API) getVoteResult(req struct {
20         BlockHash   chainjson.HexBytes `json:"block_hash"`
21         BlockHeight uint64             `json:"block_height"`
22 }) Response {
23         blockHash := hexBytesToHash(req.BlockHash)
24         if len(req.BlockHash) != 32 {
25                 blockHeader, err := a.chain.GetHeaderByHeight(req.BlockHeight)
26                 if err != nil {
27                         return NewErrorResponse(err)
28                 }
29
30                 blockHash = blockHeader.Hash()
31         }
32
33         voteResult, err := a.chain.GetVoteResultByHash(&blockHash)
34         if err != nil {
35                 return NewErrorResponse(err)
36         }
37
38         voteInfos := []*voteInfo{}
39         for pubKey, voteNum := range voteResult.NumOfVote {
40                 voteInfos = append(voteInfos, &voteInfo{
41                         Vote:    pubKey,
42                         VoteNum: voteNum,
43                 })
44         }
45         sort.Sort(voteInfoSlice(voteInfos))
46         return NewSuccessResponse(voteInfos)
47 }