1 // Package rpc implements Chain Core's RPC client.
15 "github.com/bytom/errors"
16 "github.com/bytom/net/http/httperror"
17 "github.com/bytom/net/http/reqid"
20 // Chain-specific header fields
22 HeaderBlockchainID = "Blockchain-ID"
23 HeaderCoreID = "Chain-Core-ID"
24 HeaderTimeout = "RPC-Timeout"
27 // ErrWrongNetwork is returned when a peer's blockchain ID differs from
28 // the RPC client's blockchain ID.
29 var ErrWrongNetwork = errors.New("connected to a peer on a different network")
31 // A Client is a Chain RPC client. It performs RPCs over HTTP using JSON
32 // request and responses. A Client must be configured with a secret token
33 // to authenticate with other Cores on the network.
42 // If set, Client is used for outgoing requests.
43 // TODO(kr): make this required (crash on nil)
47 func (c Client) userAgent() string {
48 return fmt.Sprintf("Chain; process=%s; buildtag=%s; blockchainID=%s",
49 c.Username, c.BuildTag, c.BlockchainID)
52 // ErrStatusCode is an error returned when an rpc fails with a non-200
54 type ErrStatusCode struct {
57 ErrorData *httperror.Response
60 func (e ErrStatusCode) Error() string {
61 return fmt.Sprintf("Request to `%s` responded with %d %s",
62 e.URL, e.StatusCode, http.StatusText(e.StatusCode))
65 // Call calls a remote procedure on another node, specified by the path.
66 func (c *Client) Call(ctx context.Context, path string, request, response interface{}) error {
67 r, err := c.CallRaw(ctx, path, request)
73 err = errors.Wrap(json.NewDecoder(r).Decode(response))
78 // CallRaw calls a remote procedure on another node, specified by the path. It
79 // returns a io.ReadCloser of the raw response body.
80 func (c *Client) CallRaw(ctx context.Context, path string, request interface{}) (io.ReadCloser, error) {
81 u, err := url.Parse(c.BaseURL)
83 return nil, errors.Wrap(err)
87 var bodyReader io.Reader
89 var jsonBody bytes.Buffer
90 if err := json.NewEncoder(&jsonBody).Encode(request); err != nil {
91 return nil, errors.Wrap(err)
93 bodyReader = &jsonBody
96 req, err := http.NewRequest("POST", u.String(), bodyReader)
98 return nil, errors.Wrap(err)
101 if c.AccessToken != "" {
102 var username, password string
103 toks := strings.SplitN(c.AccessToken, ":", 2)
110 req.SetBasicAuth(username, password)
113 // Propagate our request ID so that we can trace a request across nodes.
114 req.Header.Add("Request-ID", reqid.FromContext(ctx))
115 req.Header.Set("Content-Type", "application/json")
116 req.Header.Set("User-Agent", c.userAgent())
117 req.Header.Set(HeaderBlockchainID, c.BlockchainID)
118 req.Header.Set(HeaderCoreID, c.CoreID)
120 // Propagate our deadline if we have one.
121 deadline, ok := ctx.Deadline()
123 req.Header.Set(HeaderTimeout, deadline.Sub(time.Now()).String())
128 client = http.DefaultClient
130 resp, err := client.Do(req.WithContext(ctx))
131 if err != nil && ctx.Err() != nil { // check if it timed out
132 return nil, errors.Wrap(ctx.Err())
133 } else if err != nil {
134 return nil, errors.Wrap(err)
137 if id := resp.Header.Get(HeaderBlockchainID); c.BlockchainID != "" && id != "" && c.BlockchainID != id {
139 return nil, errors.Wrap(ErrWrongNetwork)
142 if resp.StatusCode < 200 || resp.StatusCode >= 300 {
143 defer resp.Body.Close()
145 resErr := ErrStatusCode{
146 URL: cleanedURLString(u),
147 StatusCode: resp.StatusCode,
150 // Attach formatted error message, if available
151 var errData httperror.Response
152 err := json.NewDecoder(resp.Body).Decode(&errData)
153 if err == nil && errData.ChainCode != "" {
154 resErr.ErrorData = &errData
160 return resp.Body, nil
163 func cleanedURLString(u *url.URL) string {