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"
12 // Node can invoke the api which provide by the full node server
17 // NewNode create a api client with target server
18 func NewNode(hostPort string) *Node {
19 return &Node{hostPort: hostPort}
22 func (n *Node) GetBlockByHash(hash string) (string, *bc.TransactionStatus, error) {
23 return n.getRawBlock(&getRawBlockReq{BlockHash: hash})
26 func (n *Node) GetBlockByHeight(height uint64) (string, *bc.TransactionStatus, error) {
27 return n.getRawBlock(&getRawBlockReq{BlockHeight: height})
30 type getBlockCountResp struct {
31 BlockCount uint64 `json:"block_count"`
34 func (n *Node) GetBlockCount() (uint64, error) {
35 url := "/get-block-count"
36 res := &getBlockCountResp{}
37 return res.BlockCount, n.request(url, nil, res)
40 func (n *Node) GetNetInfo() (*api.NetInfo, error) {
43 return res, n.request(url, nil, res)
46 type getRawBlockReq struct {
47 BlockHeight uint64 `json:"block_height"`
48 BlockHash string `json:"block_hash"`
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"`
57 func (n *Node) getRawBlock(req *getRawBlockReq) (string, *bc.TransactionStatus, error) {
58 url := "/get-raw-block"
59 payload, err := json.Marshal(req)
61 return "", nil, errors.Wrap(err, "json marshal")
64 res := &getRawBlockResp{}
65 return res.RawBlock, res.TransactionStatus, n.request(url, payload, res)
68 type response struct {
69 Status string `json:"status"`
70 Data json.RawMessage `json:"data"`
71 ErrDetail string `json:"error_detail"`
74 func (n *Node) request(path string, payload []byte, respData interface{}) error {
76 if err := common.Post(n.hostPort+path, payload, resp); err != nil {
80 if resp.Status != "success" {
81 return errors.New(resp.ErrDetail)
84 return json.Unmarshal(resp.Data, respData)