OSDN Git Service

upload (#570)
[bytom/vapor.git] / toolbar / apinode / block.go
1 package apinode
2
3 import (
4         "encoding/json"
5
6         "github.com/bytom/vapor/api"
7         "github.com/bytom/vapor/errors"
8         "github.com/bytom/vapor/protocol/bc/types"
9 )
10
11 func (n *Node) GetBlockByHash(hash string) (*types.Block, error) {
12         return n.getRawBlock(&getRawBlockReq{BlockHash: hash})
13 }
14
15 func (n *Node) GetBlockByHeight(height uint64) (*types.Block, error) {
16         return n.getRawBlock(&getRawBlockReq{BlockHeight: height})
17 }
18
19 type getBlockCountResp struct {
20         BlockCount uint64 `json:"block_count"`
21 }
22
23 func (n *Node) GetBlockCount() (uint64, error) {
24         url := "/get-block-count"
25         res := &getBlockCountResp{}
26         return res.BlockCount, n.request(url, nil, res)
27 }
28
29 type getRawBlockReq struct {
30         BlockHeight uint64 `json:"block_height"`
31         BlockHash   string `json:"block_hash"`
32 }
33
34 func (n *Node) getRawBlock(req *getRawBlockReq) (*types.Block, error) {
35         url := "/get-raw-block"
36         payload, err := json.Marshal(req)
37         if err != nil {
38                 return nil, errors.Wrap(err, "json marshal")
39         }
40         resp := &api.GetRawBlockResp{}
41         return resp.RawBlock, n.request(url, payload, resp)
42 }
43
44 func (n *Node) GetVoteByHash(hash string) ([]*api.VoteInfo, error) {
45         return n.getVoteResult(&getVoteResultReq{BlockHash: hash})
46 }
47
48 func (n *Node) GetVoteByHeight(height uint64) ([]*api.VoteInfo, error) {
49         return n.getVoteResult(&getVoteResultReq{BlockHeight: height})
50 }
51
52 type getVoteResultReq struct {
53         BlockHeight uint64 `json:"block_height"`
54         BlockHash   string `json:"block_hash"`
55 }
56
57 func (n *Node) getVoteResult(req *getVoteResultReq) ([]*api.VoteInfo, error) {
58         url := "/get-vote-result"
59         payload, err := json.Marshal(req)
60         if err != nil {
61                 return nil, errors.Wrap(err, "json marshal")
62         }
63         resp := []*api.VoteInfo{}
64         return resp, n.request(url, payload, &resp)
65 }