-
Notifications
You must be signed in to change notification settings - Fork 46
/
Copy pathclient.go
481 lines (417 loc) · 10.4 KB
/
client.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
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
package goar
import (
"bytes"
"encoding/json"
"errors"
"fmt"
"github.com/inconshreveable/log15"
"io/ioutil"
"math/big"
"net/http"
"net/url"
"path"
"strconv"
"strings"
"github.com/everFinance/goar/types"
"github.com/everFinance/goar/utils"
)
var log = log15.New("module", "goar")
// arweave HTTP API: https://docs.arweave.org/developers/server/http-api
type Client struct {
client *http.Client
url string
}
func NewClient(nodeUrl string, proxyUrl ...string) *Client {
httpClient := http.DefaultClient
// if exist proxy url
if len(proxyUrl) > 0 {
pUrl := proxyUrl[0]
proxyUrl, err := url.Parse(pUrl)
if err != nil {
log.Error("url parse", "error", err)
panic(err)
}
tr := &http.Transport{Proxy: http.ProxyURL(proxyUrl)}
httpClient = &http.Client{Transport: tr}
}
return &Client{client: httpClient, url: nodeUrl}
}
func NewShortConn() *Client {
transport := http.Transport{DisableKeepAlives: true}
cli := &http.Client{Transport: &transport}
return &Client{client: cli}
}
func (c *Client) SetShortConnUrl(url string) {
c.url = url
}
func (c *Client) GetInfo() (info *types.NetworkInfo, err error) {
body, _, err := c.httpGet("info")
if err != nil {
return nil, ErrBadGateway
}
info = &types.NetworkInfo{}
err = json.Unmarshal(body, info)
return
}
func (c *Client) GetPeers() ([]string, error) {
body, _, err := c.httpGet("peers")
if err != nil {
return nil, ErrBadGateway
}
peers := make([]string, 0)
err = json.Unmarshal(body, &peers)
if err != nil {
return nil, err
}
// filter local
fpeers := make([]string, 0)
for _, p := range peers {
if strings.Contains(p, "127.0.0.") {
continue
}
fpeers = append(fpeers, p)
}
return fpeers, nil
}
// GetTransactionByID status: Pending/Invalid hash/overspend
func (c *Client) GetTransactionByID(id string) (tx *types.Transaction, err error) {
body, statusCode, err := c.httpGet(fmt.Sprintf("tx/%s", id))
if err != nil {
return nil, ErrBadGateway
}
switch statusCode {
case 200:
// json unmarshal
tx = &types.Transaction{}
err = json.Unmarshal(body, tx)
return
case 202:
return nil, ErrPendingTx
case 400:
return nil, ErrInvalidId
case 404:
return nil, ErrNotFound
default:
return nil, ErrBadGateway
}
}
// GetTransactionStatus
func (c *Client) GetTransactionStatus(id string) (*types.TxStatus, error) {
body, code, err := c.httpGet(fmt.Sprintf("tx/%s/status", id))
if err != nil {
return nil, ErrBadGateway
}
switch code {
case 200:
// json unmarshal
txStatus := &types.TxStatus{}
err = json.Unmarshal(body, txStatus)
return txStatus, err
case 202:
return nil, ErrPendingTx
case 404:
return nil, ErrNotFound
default:
return nil, ErrBadGateway
}
}
func (c *Client) GetTransactionField(id string, field string) (string, error) {
body, statusCode, err := c.httpGet(fmt.Sprintf("tx/%v/%v", id, field))
if err != nil {
return "", ErrBadGateway
}
switch statusCode {
case 200:
return string(body), nil
case 202:
return "", ErrPendingTx
case 400:
return "", ErrInvalidId
case 404:
return "", ErrNotFound
default:
return "", ErrBadGateway
}
}
func (c *Client) GetTransactionTags(id string) ([]types.Tag, error) {
jsTags, err := c.GetTransactionField(id, "tags")
if err != nil {
return nil, err
}
tags := make([]types.Tag, 0)
if err := json.Unmarshal([]byte(jsTags), &tags); err != nil {
return nil, err
}
tags, err = utils.TagsDecode(tags)
if err != nil {
return nil, err
}
return tags, nil
}
func (c *Client) GetTransactionData(id string, extension ...string) (body []byte, err error) {
urlPath := fmt.Sprintf("tx/%v/%v", id, "data")
if extension != nil {
urlPath = urlPath + "." + extension[0]
}
body, statusCode, err := c.httpGet(urlPath)
// When data is bigger than 12MiB statusCode == 400 NOTE: Data bigger than that has to be downloaded chunk by chunk.
if statusCode == 400 {
body, err = c.DownloadChunkData(id)
return
} else if statusCode == 200 {
if len(body) == 0 {
return c.DownloadChunkData(id)
}
return body, nil
} else if statusCode == 202 {
return nil, ErrPendingTx
} else if statusCode == 404 {
return nil, ErrNotFound
} else {
return nil, ErrBadGateway
}
}
// GetTransactionDataByGateway
func (c *Client) GetTransactionDataByGateway(id string) (body []byte, err error) {
urlPath := fmt.Sprintf("/%v/%v", id, "data")
body, statusCode, err := c.httpGet(urlPath)
switch statusCode {
case 200:
if len(body) == 0 {
return c.DownloadChunkData(id)
}
return body, nil
case 400:
return c.DownloadChunkData(id)
case 202:
return nil, ErrPendingTx
case 404:
return nil, ErrNotFound
case 410:
return nil, ErrInvalidId
default:
return nil, ErrBadGateway
}
}
func (c *Client) GetTransactionPrice(data []byte, target *string) (reward int64, err error) {
url := fmt.Sprintf("price/%d", len(data))
if target != nil {
url = fmt.Sprintf("%v/%v", url, *target)
}
body, _, err := c.httpGet(url)
if err != nil {
return
}
return strconv.ParseInt(string(body), 10, 64)
}
func (c *Client) GetTransactionAnchor() (anchor string, err error) {
body, _, err := c.httpGet("tx_anchor")
if err != nil {
return
}
anchor = string(body)
return
}
func (c *Client) SubmitTransaction(tx *types.Transaction) (status string, code int, err error) {
by, err := json.Marshal(tx)
if err != nil {
return
}
body, statusCode, err := c.httpPost("tx", by)
status = string(body)
code = statusCode
return
}
func (c *Client) SubmitChunks(gc *types.GetChunk) (status string, code int, err error) {
byteGc, err := gc.Marshal()
if err != nil {
return
}
var body []byte
body, code, err = c.httpPost("chunk", byteGc)
status = string(body)
return
}
// Arql is Deprecated, recommended to use GraphQL
func (c *Client) Arql(arql string) (ids []string, err error) {
body, _, err := c.httpPost("arql", []byte(arql))
err = json.Unmarshal(body, &ids)
return
}
func (c *Client) GraphQL(query string) ([]byte, error) {
// generate query
graQuery := struct {
Query string `json:"query"`
}{query}
byQuery, err := json.Marshal(graQuery)
if err != nil {
return nil, err
}
// query from http client
data, statusCode, err := c.httpPost("graphql", byQuery)
if err != nil {
return nil, err
}
if statusCode != http.StatusOK {
return nil, fmt.Errorf(string(data))
}
// unwrap data
res := struct {
Data interface{}
}{}
if err := json.Unmarshal(data, &res); err != nil {
return nil, err
}
return json.Marshal(res.Data)
}
// Wallet
func (c *Client) GetWalletBalance(address string) (arAmount *big.Float, err error) {
body, _, err := c.httpGet(fmt.Sprintf("wallet/%s/balance", address))
if err != nil {
return
}
winstomStr := string(body)
winstom, ok := new(big.Int).SetString(winstomStr, 10)
if !ok {
err = fmt.Errorf("invalid balance: %v", winstomStr)
return
}
arAmount = utils.WinstonToAR(winstom)
return
}
func (c *Client) GetLastTransactionID(address string) (id string, err error) {
body, _, err := c.httpGet(fmt.Sprintf("wallet/%s/last_tx", address))
if err != nil {
return
}
id = string(body)
return
}
// Block
func (c *Client) GetBlockByID(id string) (block *types.Block, err error) {
body, _, err := c.httpGet(fmt.Sprintf("block/hash/%s", id))
if err != nil {
return
}
block = &types.Block{}
err = json.Unmarshal(body, block)
return
}
func (c *Client) GetBlockByHeight(height int64) (block *types.Block, err error) {
body, _, err := c.httpGet(fmt.Sprintf("block/height/%d", height))
if err != nil {
return
}
block = &types.Block{}
err = json.Unmarshal(body, block)
return
}
func (c *Client) httpGet(_path string) (body []byte, statusCode int, err error) {
u, err := url.Parse(c.url)
if err != nil {
return
}
u.Path = path.Join(u.Path, _path)
resp, err := c.client.Get(u.String())
if err != nil {
return
}
defer resp.Body.Close()
statusCode = resp.StatusCode
body, err = ioutil.ReadAll(resp.Body)
return
}
func (c *Client) httpPost(_path string, payload []byte) (body []byte, statusCode int, err error) {
u, err := url.Parse(c.url)
if err != nil {
return
}
u.Path = path.Join(u.Path, _path)
resp, err := c.client.Post(u.String(), "application/json", bytes.NewReader(payload))
if err != nil {
return
}
defer resp.Body.Close()
statusCode = resp.StatusCode
body, err = ioutil.ReadAll(resp.Body)
return
}
// about chunk
func (c *Client) getChunk(offset int64) (*types.TransactionChunk, error) {
_path := "chunk/" + strconv.FormatInt(offset, 10)
body, statusCode, err := c.httpGet(_path)
if statusCode != 200 {
return nil, errors.New("not found chunk data")
}
if err != nil {
return nil, err
}
txChunk := &types.TransactionChunk{}
if err := json.Unmarshal(body, txChunk); err != nil {
return nil, err
}
return txChunk, nil
}
func (c *Client) getChunkData(offset int64) ([]byte, error) {
chunk, err := c.getChunk(offset)
if err != nil {
return nil, err
}
return utils.Base64Decode(chunk.Chunk)
}
func (c *Client) getTransactionOffset(id string) (*types.TransactionOffset, error) {
_path := fmt.Sprintf("tx/%s/offset", id)
body, statusCode, err := c.httpGet(_path)
if statusCode != 200 {
return nil, errors.New("not found tx offset")
}
if err != nil {
return nil, err
}
txOffset := &types.TransactionOffset{}
if err := json.Unmarshal(body, txOffset); err != nil {
return nil, err
}
return txOffset, nil
}
func (c *Client) DownloadChunkData(id string) ([]byte, error) {
offsetResponse, err := c.getTransactionOffset(id)
if err != nil {
return nil, err
}
size, err := strconv.ParseInt(offsetResponse.Size, 10, 64)
if err != nil {
return nil, err
}
endOffset, err := strconv.ParseInt(offsetResponse.Offset, 10, 64)
if err != nil {
return nil, err
}
startOffset := endOffset - size + 1
data := make([]byte, 0, size)
for i := 0; int64(i)+startOffset < endOffset; {
chunkData, err := c.getChunkData(int64(i) + startOffset)
if err != nil {
return nil, err
}
data = append(data, chunkData...)
fmt.Printf("download chunk data; offset: %d/%d; size: %d/%d \n", int64(i)+startOffset, endOffset, len(data), size)
i += len(chunkData)
}
return data, nil
}
func (c *Client) GetUnconfirmedTx(arId string) (*types.Transaction, error) {
_path := fmt.Sprintf("unconfirmed_tx/%s", arId)
body, statusCode, err := c.httpGet(_path)
if statusCode != 200 {
return nil, errors.New("not found unconfirmed tx")
}
if err != nil {
return nil, err
}
tx := &types.Transaction{}
if err := json.Unmarshal(body, tx); err != nil {
return nil, err
}
return tx, nil
}