14 "github.com/bytom/errors"
15 "github.com/bytom/net/http/httperror"
16 "github.com/bytom/net/http/reqid"
19 // Bytom-specific header fields
21 HeaderBlockchainID = "Blockchain-ID"
22 HeaderCoreID = "Bytom-Core-ID"
23 HeaderTimeout = "RPC-Timeout"
26 // ErrWrongNetwork is returned when a peer's blockchain ID differs from
27 // the RPC client's blockchain ID.
28 var ErrWrongNetwork = errors.New("connected to a peer on a different network")
30 // A Client is a Bytom RPC client. It performs RPCs over HTTP using JSON
31 // request and responses. A Client must be configured with a secret token
32 // to authenticate with other Cores on the network.
41 // If set, Client is used for outgoing requests.
42 // TODO(kr): make this required (crash on nil)
46 func (c Client) userAgent() string {
47 return fmt.Sprintf("Bytom; process=%s; buildtag=%s; blockchainID=%s",
48 c.Username, c.BuildTag, c.BlockchainID)
51 // ErrStatusCode is an error returned when an rpc fails with a non-200
53 type ErrStatusCode struct {
56 ErrorData *httperror.Response
59 func (e ErrStatusCode) Error() string {
60 return fmt.Sprintf("Request to `%s` responded with %d %s",
61 e.URL, e.StatusCode, http.StatusText(e.StatusCode))
64 // Call calls a remote procedure on another node, specified by the path.
65 func (c *Client) Call(ctx context.Context, path string, request, response interface{}) error {
66 r, err := c.CallRaw(ctx, path, request)
72 err = errors.Wrap(json.NewDecoder(r).Decode(response))
77 // CallRaw calls a remote procedure on another node, specified by the path. It
78 // returns a io.ReadCloser of the raw response body.
79 func (c *Client) CallRaw(ctx context.Context, path string, request interface{}) (io.ReadCloser, error) {
80 u, err := url.Parse(c.BaseURL)
82 return nil, errors.Wrap(err)
86 var bodyReader io.Reader
88 var jsonBody bytes.Buffer
89 if err := json.NewEncoder(&jsonBody).Encode(request); err != nil {
90 return nil, errors.Wrap(err)
92 bodyReader = &jsonBody
95 req, err := http.NewRequest("POST", u.String(), bodyReader)
97 return nil, errors.Wrap(err)
100 if c.AccessToken != "" {
101 var username, password string
102 toks := strings.SplitN(c.AccessToken, ":", 2)
109 req.SetBasicAuth(username, password)
112 // Propagate our request ID so that we can trace a request across nodes.
113 req.Header.Add("Request-ID", reqid.FromContext(ctx))
114 req.Header.Set("Content-Type", "application/json")
115 req.Header.Set("User-Agent", c.userAgent())
116 req.Header.Set(HeaderBlockchainID, c.BlockchainID)
117 req.Header.Set(HeaderCoreID, c.CoreID)
119 // Propagate our deadline if we have one.
120 deadline, ok := ctx.Deadline()
122 req.Header.Set(HeaderTimeout, deadline.Sub(time.Now()).String())
127 client = http.DefaultClient
129 resp, err := client.Do(req.WithContext(ctx))
130 if err != nil && ctx.Err() != nil { // check if it timed out
131 return nil, errors.Wrap(ctx.Err())
132 } else if err != nil {
133 return nil, errors.Wrap(err)
136 if id := resp.Header.Get(HeaderBlockchainID); c.BlockchainID != "" && id != "" && c.BlockchainID != id {
138 return nil, errors.Wrap(ErrWrongNetwork)
141 if resp.StatusCode < 200 || resp.StatusCode >= 300 {
142 defer resp.Body.Close()
144 resErr := ErrStatusCode{
145 URL: cleanedURLString(u),
146 StatusCode: resp.StatusCode,
149 // Attach formatted error message, if available
150 var errData httperror.Response
151 err := json.NewDecoder(resp.Body).Decode(&errData)
152 if err == nil && errData.ChainCode != "" {
153 resErr.ErrorData = &errData
159 return resp.Body, nil
162 func cleanedURLString(u *url.URL) string {