OSDN Git Service

rename (#465)
[bytom/vapor.git] / blockchain / rpc / rpc.go
1 package rpc
2
3 import (
4         "bytes"
5         "context"
6         "encoding/json"
7         "fmt"
8         "io"
9         "net/http"
10         "net/url"
11         "strings"
12         "time"
13
14         "github.com/bytom/vapor/errors"
15         "github.com/bytom/vapor/net/http/httperror"
16 )
17
18 // Bytom-specific header fields
19 const (
20         HeaderBlockchainID = "Blockchain-ID"
21         HeaderCoreID       = "Bytom-Core-ID"
22         HeaderTimeout      = "RPC-Timeout"
23 )
24
25 // ErrWrongNetwork is returned when a peer's blockchain ID differs from
26 // the RPC client's blockchain ID.
27 var ErrWrongNetwork = errors.New("connected to a peer on a different network")
28
29 // A Client is a Bytom RPC client. It performs RPCs over HTTP using JSON
30 // request and responses. A Client must be configured with a secret token
31 // to authenticate with other Cores on the network.
32 type Client struct {
33         BaseURL      string
34         AccessToken  string
35         Username     string
36         BuildTag     string
37         BlockchainID string
38         CoreID       string
39
40         // If set, Client is used for outgoing requests.
41         // TODO(kr): make this required (crash on nil)
42         Client *http.Client
43 }
44
45 func (c Client) userAgent() string {
46         return fmt.Sprintf("Bytom; process=%s; buildtag=%s; blockchainID=%s",
47                 c.Username, c.BuildTag, c.BlockchainID)
48 }
49
50 // ErrStatusCode is an error returned when an rpc fails with a non-200
51 // response code.
52 type ErrStatusCode struct {
53         URL        string
54         StatusCode int
55         ErrorData  *httperror.Response
56 }
57
58 func (e ErrStatusCode) Error() string {
59         return fmt.Sprintf("Request to `%s` responded with %d %s",
60                 e.URL, e.StatusCode, http.StatusText(e.StatusCode))
61 }
62
63 // Call calls a remote procedure on another node, specified by the path.
64 func (c *Client) Call(ctx context.Context, path string, request, response interface{}) error {
65         r, err := c.CallRaw(ctx, path, request)
66         if err != nil {
67                 return err
68         }
69         defer r.Close()
70         if response != nil {
71                 decoder := json.NewDecoder(r)
72                 decoder.UseNumber()
73                 err = errors.Wrap(decoder.Decode(response))
74         }
75         return err
76 }
77
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)
82         if err != nil {
83                 return nil, errors.Wrap(err)
84         }
85         u.Path = path
86
87         var bodyReader io.Reader
88         if request != nil {
89                 var jsonBody bytes.Buffer
90                 if err := json.NewEncoder(&jsonBody).Encode(request); err != nil {
91                         return nil, errors.Wrap(err)
92                 }
93                 bodyReader = &jsonBody
94         }
95
96         req, err := http.NewRequest("POST", u.String(), bodyReader)
97         if err != nil {
98                 return nil, errors.Wrap(err)
99         }
100
101         if c.AccessToken != "" {
102                 var username, password string
103                 toks := strings.SplitN(c.AccessToken, ":", 2)
104                 if len(toks) > 0 {
105                         username = toks[0]
106                 }
107                 if len(toks) > 1 {
108                         password = toks[1]
109                 }
110                 req.SetBasicAuth(username, password)
111         }
112
113         // Propagate our request ID so that we can trace a request across nodes.
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)
118
119         // Propagate our deadline if we have one.
120         deadline, ok := ctx.Deadline()
121         if ok {
122                 req.Header.Set(HeaderTimeout, deadline.Sub(time.Now()).String())
123         }
124
125         client := c.Client
126         if client == nil {
127                 client = http.DefaultClient
128         }
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)
134         }
135
136         if id := resp.Header.Get(HeaderBlockchainID); c.BlockchainID != "" && id != "" && c.BlockchainID != id {
137                 resp.Body.Close()
138                 return nil, errors.Wrap(ErrWrongNetwork)
139         }
140
141         if resp.StatusCode < 200 || resp.StatusCode >= 300 {
142                 defer resp.Body.Close()
143
144                 resErr := ErrStatusCode{
145                         URL:        cleanedURLString(u),
146                         StatusCode: resp.StatusCode,
147                 }
148
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
154                 }
155
156                 return nil, resErr
157         }
158
159         return resp.Body, nil
160 }
161
162 func cleanedURLString(u *url.URL) string {
163         var dup url.URL = *u
164         dup.User = nil
165         return dup.String()
166 }