OSDN Git Service

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