-
Notifications
You must be signed in to change notification settings - Fork 19
/
jsonrpc.go
383 lines (324 loc) · 9.37 KB
/
jsonrpc.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
// Copyright 2016 Factom Foundation
// Use of this source code is governed by the MIT
// license that can be found in the LICENSE file.
package factom
import (
"bytes"
"crypto/tls"
"crypto/x509"
"encoding/json"
"fmt"
"io/ioutil"
"net/http"
"net/http/cookiejar"
"strings"
"sync/atomic"
"time"
"golang.org/x/net/publicsuffix"
)
// RPCConfig is the configuration for the API handler
type RPCConfig struct {
WalletTLSEnable bool
WalletTLSKeyFile string
WalletTLSCertFile string
WalletRPCUser string
WalletRPCPassword string
WalletServer string
WalletTimeout time.Duration
WalletCORSDomains string
FactomdTLSEnable bool
FactomdTLSCertFile string
FactomdRPCUser string
FactomdRPCPassword string
FactomdServer string
FactomdTimeout time.Duration
}
func EncodeJSON(data interface{}) ([]byte, error) {
encoded, err := json.Marshal(data)
if err != nil {
return nil, err
}
return encoded, nil
}
func EncodeJSONString(data interface{}) (string, error) {
encoded, err := EncodeJSON(data)
if err != nil {
return "", err
}
return string(encoded), err
}
type JSONError struct {
Code int `json:"code"`
Message string `json:"message"`
Data interface{} `json:"data,omitempty"`
}
func NewJSONError(code int, message string, data interface{}) *JSONError {
j := new(JSONError)
j.Code = code
j.Message = message
j.Data = data
return j
}
func (e *JSONError) Error() string {
s := fmt.Sprint(e.Message)
if e.Data != nil {
s += fmt.Sprint(": ", e.Data)
}
return s
}
type JSON2Request struct {
JSONRPC string `json:"jsonrpc"`
ID interface{} `json:"id"`
Params json.RawMessage `json:"params,omitempty"`
Method string `json:"method,omitempty"`
}
func NewJSON2Request(method string, id, params interface{}) *JSON2Request {
j := new(JSON2Request)
j.JSONRPC = "2.0"
j.ID = id
if b, err := json.Marshal(params); err == nil {
j.Params = b
}
j.Method = method
return j
}
func ParseJSON2Request(request string) (*JSON2Request, error) {
j := new(JSON2Request)
err := json.Unmarshal([]byte(request), j)
if err != nil {
return nil, err
}
if j.JSONRPC != "2.0" {
return nil, fmt.Errorf("Invalid JSON RPC version - `%v`, should be `2.0`", j.JSONRPC)
}
return j, nil
}
func (j *JSON2Request) JSONString() (string, error) {
return EncodeJSONString(j)
}
func (j *JSON2Request) String() string {
str, _ := j.JSONString()
return str
}
type JSON2Response struct {
JSONRPC string `json:"jsonrpc"`
ID interface{} `json:"id"`
Error *JSONError `json:"error,omitempty"`
Result json.RawMessage `json:"result,omitempty"`
}
func NewJSON2Response() *JSON2Response {
j := new(JSON2Response)
j.JSONRPC = "2.0"
return j
}
func (j *JSON2Response) JSONString() (string, error) {
return EncodeJSONString(j)
}
func (j *JSON2Response) JSONResult() []byte {
return j.Result
}
func (j *JSON2Response) String() string {
str, _ := j.JSONString()
return str
}
func SetFactomdRpcConfig(user string, password string) {
RpcConfig.FactomdRPCUser = user
RpcConfig.FactomdRPCPassword = password
}
func GetFactomdRpcConfig() (string, string) {
return RpcConfig.FactomdRPCUser, RpcConfig.FactomdRPCPassword
}
func SetFactomdEncryption(tls bool, certFile string) {
RpcConfig.FactomdTLSEnable = tls
RpcConfig.FactomdTLSCertFile = certFile
}
func GetFactomdEncryption() (bool, string) {
return RpcConfig.FactomdTLSEnable, RpcConfig.FactomdTLSCertFile
}
func SetFactomdTimeout(timeout time.Duration) {
RpcConfig.FactomdTimeout = timeout
}
func GetFactomdTimeout() time.Duration {
return RpcConfig.FactomdTimeout
}
func SetWalletTimeout(timeout time.Duration) {
RpcConfig.WalletTimeout = timeout
}
func GetWalletTimeout() time.Duration {
return RpcConfig.WalletTimeout
}
func SetWalletRpcConfig(user string, password string) {
RpcConfig.WalletRPCUser = user
RpcConfig.WalletRPCPassword = password
}
func GetWalletRpcConfig() (string, string) {
return RpcConfig.WalletRPCUser, RpcConfig.WalletRPCPassword
}
func SetWalletEncryption(tls bool, certFile string) {
RpcConfig.WalletTLSEnable = tls
RpcConfig.WalletTLSCertFile = certFile
}
func GetWalletEncryption() (bool, string) {
return RpcConfig.WalletTLSEnable, RpcConfig.WalletTLSCertFile
}
// SetOpenNode points the Factomd server to the open node API and enables cookies
func SetOpenNode() {
EnableCookies()
RpcConfig.FactomdServer = OpenNode
}
// EnableCookies will accept and manage cookies from the API server
func EnableCookies() {
// cookiejar.New never returns an error
cookieJar, _ = cookiejar.New(&cookiejar.Options{PublicSuffixList: publicsuffix.List})
}
// SetFactomdServer sets where to find the factomd server, and tells the server its public ip
func SetFactomdServer(s string) {
RpcConfig.FactomdServer = s
}
// SetWalletServer sets where to find the fctwallet server, and tells the server its public ip
func SetWalletServer(s string) {
RpcConfig.WalletServer = s
}
// FactomdServer returns where to find the factomd server, and tells the server its public ip
func FactomdServer() string {
return RpcConfig.FactomdServer
}
// FactomdServer returns where to find the fctwallet server, and tells the server its public ip
func WalletServer() string {
return RpcConfig.WalletServer
}
// SendFactomdRequest sends a json object to factomd
func SendFactomdRequest(req *JSON2Request) (*JSON2Response, error) {
return factomdRequest(req)
}
// factomdRequest sends a JSON RPC request to the factomd API server and returns
// the corresponding API response.
func factomdRequest(req *JSON2Request) (*JSON2Response, error) {
j, err := json.Marshal(req)
if err != nil {
return nil, err
}
factomdTls, factomdCertPath := GetFactomdEncryption()
var client *http.Client
var scheme, host string
if factomdTls == true {
caCert, err := ioutil.ReadFile(factomdCertPath)
if err != nil {
return nil, err
}
caCertPool := x509.NewCertPool()
caCertPool.AppendCertsFromPEM(caCert)
tr := &http.Transport{TLSClientConfig: &tls.Config{RootCAs: caCertPool}}
client = &http.Client{Transport: tr, Timeout: GetFactomdTimeout()}
scheme = "https"
host = RpcConfig.FactomdServer
} else {
client = &http.Client{Timeout: GetFactomdTimeout()}
if index := strings.Index(RpcConfig.FactomdServer, "://"); index != -1 {
scheme = RpcConfig.FactomdServer[0:index]
host = RpcConfig.FactomdServer[index+3:]
} else {
scheme = "http"
host = RpcConfig.FactomdServer
}
}
// no effect if nil
client.Jar = cookieJar
re, err := http.NewRequest(
"POST",
fmt.Sprintf("%s://%s/v2", scheme, host),
bytes.NewBuffer(j),
)
if err != nil {
return nil, err
}
user, pass := GetFactomdRpcConfig()
re.SetBasicAuth(user, pass)
re.Header.Add("Content-Type", "application/json")
resp, err := client.Do(re)
if err != nil {
errs := fmt.Sprintf("%s", err)
if strings.Contains(errs, "\\x15\\x03\\x01\\x00\\x02\\x02\\x16") {
err = fmt.Errorf("Factomd API connection is encrypted. Please specify -factomdtls=true and -factomdcert=factomdAPIpub.cert (%v)", err.Error())
}
return nil, err
}
defer resp.Body.Close()
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
return nil, err
}
if resp.StatusCode == http.StatusUnauthorized {
return nil, fmt.Errorf("Factomd username/password incorrect. Edit factomd.conf or\ncall factom-cli with -factomduser=<user> -factomdpassword=<pass>")
}
r := NewJSON2Response()
if err := json.Unmarshal(body, r); err != nil {
return nil, err
}
return r, nil
}
// walletRequest sends a JSON RPC request to the factom wallet API server and
// returns the corresponding API response.
func walletRequest(req *JSON2Request) (*JSON2Response, error) {
j, err := json.Marshal(req)
if err != nil {
return nil, err
}
walletTls, walletCertPath := GetWalletEncryption()
var client *http.Client
var httpx string
if walletTls == true {
caCert, err := ioutil.ReadFile(walletCertPath)
if err != nil {
return nil, err
}
caCertPool := x509.NewCertPool()
caCertPool.AppendCertsFromPEM(caCert)
tr := &http.Transport{TLSClientConfig: &tls.Config{RootCAs: caCertPool}}
client = &http.Client{Transport: tr, Timeout: GetWalletTimeout()}
httpx = "https"
} else {
client = &http.Client{Timeout: GetWalletTimeout()}
httpx = "http"
}
re, err := http.NewRequest(
"POST",
fmt.Sprintf("%s://%s/v2", httpx, RpcConfig.WalletServer),
bytes.NewBuffer(j),
)
if err != nil {
return nil, err
}
user, pass := GetWalletRpcConfig()
re.SetBasicAuth(user, pass)
re.Header.Add("Content-Type", "application/json")
resp, err := client.Do(re)
if err != nil {
errs := fmt.Sprintf("%s", err)
if strings.Contains(errs, "\\x15\\x03\\x01\\x00\\x02\\x02\\x16") {
err = fmt.Errorf("Factom-walletd API connection is encrypted. Please specify -wallettls=true and -walletcert=walletAPIpub.cert (%v)", err.Error())
}
return nil, err
}
defer resp.Body.Close()
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
return nil, err
}
if resp.StatusCode == http.StatusUnauthorized {
return nil, fmt.Errorf("Wallet username/password incorrect. Edit factomd.conf or\ncall factom-cli with -walletuser=<user> -walletpassword=<pass>")
}
r := NewJSON2Response()
if err := json.Unmarshal(body, r); err != nil {
return nil, err
}
return r, nil
}
// newCounter is used to generate the ID field for the JSON2Request
func newCounter() func() uint32 {
var count uint32
return func() uint32 {
return atomic.AddUint32(&count, 1)
}
}
var APICounter = newCounter()