6 "github.com/bytom/vapor/errors"
7 "github.com/bytom/vapor/protocol/bc"
8 "github.com/bytom/vapor/toolbar/common"
11 // Node can invoke the api which provide by the full node server
16 // NewNode create a api client with target server
17 func NewNode(hostPort string) *Node {
18 return &Node{hostPort: hostPort}
21 func (n *Node) GetBlockByHash(hash string) (string, *bc.TransactionStatus, error) {
22 return n.getRawBlock(&getRawBlockReq{BlockHash: hash})
25 func (n *Node) GetBlockByHeight(height uint64) (string, *bc.TransactionStatus, error) {
26 return n.getRawBlock(&getRawBlockReq{BlockHeight: height})
29 type getBlockCountResp struct {
30 BlockCount uint64 `json:"block_count"`
33 func (n *Node) GetBlockCount() (uint64, error) {
34 url := "/get-block-count"
35 res := &getBlockCountResp{}
36 return res.BlockCount, n.request(url, nil, res)
39 type getRawBlockReq struct {
40 BlockHeight uint64 `json:"block_height"`
41 BlockHash string `json:"block_hash"`
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"`
50 func (n *Node) getRawBlock(req *getRawBlockReq) (string, *bc.TransactionStatus, error) {
51 url := "/get-raw-block"
52 payload, err := json.Marshal(req)
54 return "", nil, errors.Wrap(err, "json marshal")
57 res := &getRawBlockResp{}
58 return res.RawBlock, res.TransactionStatus, n.request(url, payload, res)
61 type response struct {
62 Status string `json:"status"`
63 Data json.RawMessage `json:"data"`
64 ErrDetail string `json:"error_detail"`
67 func (n *Node) request(path string, payload []byte, respData interface{}) error {
69 if err := common.Post(n.hostPort+path, payload, resp); err != nil {
73 if resp.Status != "success" {
74 return errors.New(resp.ErrDetail)
77 return json.Unmarshal(resp.Data, respData)