OSDN Git Service

versoin1.1.9 (#594)
[bytom/vapor.git] / toolbar / federation / service / node.go
1 package service
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"
9         "github.com/bytom/vapor/toolbar/common"
10 )
11
12 // Node can invoke the api which provide by the full node server
13 type Node struct {
14         hostPort string
15 }
16
17 // NewNode create a api client with target server
18 func NewNode(hostPort string) *Node {
19         return &Node{hostPort: hostPort}
20 }
21
22 func (n *Node) GetBlockByHash(hash string) (string, *bc.TransactionStatus, error) {
23         return n.getRawBlock(&getRawBlockReq{BlockHash: hash})
24 }
25
26 func (n *Node) GetBlockByHeight(height uint64) (string, *bc.TransactionStatus, error) {
27         return n.getRawBlock(&getRawBlockReq{BlockHeight: height})
28 }
29
30 type getBlockCountResp struct {
31         BlockCount uint64 `json:"block_count"`
32 }
33
34 func (n *Node) GetBlockCount() (uint64, error) {
35         url := "/get-block-count"
36         res := &getBlockCountResp{}
37         return res.BlockCount, n.request(url, nil, res)
38 }
39
40 func (n *Node) GetNetInfo() (*api.NetInfo, error) {
41         url := "/net-info"
42         res := &api.NetInfo{}
43         return res, n.request(url, nil, res)
44 }
45
46 type getRawBlockReq struct {
47         BlockHeight uint64 `json:"block_height"`
48         BlockHash   string `json:"block_hash"`
49 }
50
51 type getRawBlockResp struct {
52         RawBlock string `json:"raw_block"`
53         // TransactionStatus has same marshalling rule for both bytom and vapor
54         TransactionStatus *bc.TransactionStatus `json:"transaction_status"`
55 }
56
57 func (n *Node) getRawBlock(req *getRawBlockReq) (string, *bc.TransactionStatus, error) {
58         url := "/get-raw-block"
59         payload, err := json.Marshal(req)
60         if err != nil {
61                 return "", nil, errors.Wrap(err, "json marshal")
62         }
63
64         res := &getRawBlockResp{}
65         return res.RawBlock, res.TransactionStatus, n.request(url, payload, res)
66 }
67
68 type response struct {
69         Status    string          `json:"status"`
70         Data      json.RawMessage `json:"data"`
71         ErrDetail string          `json:"error_detail"`
72 }
73
74 func (n *Node) request(path string, payload []byte, respData interface{}) error {
75         resp := &response{}
76         if err := common.Post(n.hostPort+path, payload, resp); err != nil {
77                 return err
78         }
79
80         if resp.Status != "success" {
81                 return errors.New(resp.ErrDetail)
82         }
83
84         return json.Unmarshal(resp.Data, respData)
85 }