-
Notifications
You must be signed in to change notification settings - Fork 45
/
client.go
1156 lines (1036 loc) · 27.3 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
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package goar
import (
"bytes"
"encoding/json"
"errors"
"fmt"
"io"
"math"
"math/big"
"net/http"
"net/url"
"os"
"path"
"strconv"
"strings"
"sync"
"time"
"github.com/inconshreveable/log15"
"github.com/panjf2000/ants/v2"
"github.com/tidwall/gjson"
"gopkg.in/h2non/gentleman.v2"
"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 NewTempConn() *Client {
transport := http.Transport{DisableKeepAlives: true}
cli := &http.Client{Transport: &transport}
return &Client{client: cli}
}
func (c *Client) SetTempConnUrl(url string) {
c.url = url
}
func (c *Client) SetTimeout(timeout time.Duration) {
c.client.Timeout = timeout
}
func (c *Client) GetInfo() (info *types.NetworkInfo, err error) {
body, code, err := c.httpGet("info")
if code == 429 {
return nil, ErrRequestLimit
}
if err != nil {
return nil, ErrBadGateway
}
if code != 200 {
return nil, fmt.Errorf("get info error: %s", string(body))
}
info = &types.NetworkInfo{}
err = json.Unmarshal(body, info)
return
}
func (c *Client) GetPeers() ([]string, error) {
body, code, err := c.httpGet("peers")
if code == 429 {
return nil, ErrRequestLimit
}
if err != nil {
return nil, ErrBadGateway
}
if code != 200 {
return nil, fmt.Errorf("get peers error: %s", string(body))
}
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
case 429:
return nil, ErrRequestLimit
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
case 429:
return nil, ErrRequestLimit
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
case 429:
return "", ErrRequestLimit
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) ([]byte, error) {
urlPath := fmt.Sprintf("tx/%v/%v", id, "data")
if extension != nil {
urlPath = urlPath + "." + extension[0]
}
data, statusCode, err := c.httpGet(urlPath)
if err != nil {
return nil, fmt.Errorf("httpGet error: %v", err)
}
// When data is bigger than 12MiB statusCode == 400 NOTE: Data bigger than that has to be downloaded chunk by chunk.
switch statusCode {
case 200:
if len(data) == 0 {
return c.DownloadChunkData(id)
}
return data, nil
case 400:
return c.DownloadChunkData(id)
case 202:
return nil, ErrPendingTx
case 404:
return nil, ErrNotFound
case 429:
return nil, ErrRequestLimit
default:
return nil, ErrBadGateway
}
}
func (c *Client) GetTransactionDataStream(id string, extension ...string) (*os.File, error) {
urlPath := fmt.Sprintf("tx/%v/%v", id, "data")
if extension != nil {
urlPath = urlPath + "." + extension[0]
}
data, statusCode, err := c.httpGet(urlPath)
if err != nil {
return nil, fmt.Errorf("httpGet error: %v", err)
}
// When data is bigger than 12MiB statusCode == 400 NOTE: Data bigger than that has to be downloaded chunk by chunk.
switch statusCode {
case 200:
if len(data) == 0 {
return c.DownloadChunkDataStream(id)
}
dataFile, err := os.CreateTemp(".", "arTxData-")
if err != nil {
return nil, err
}
_, err = dataFile.Write(data)
return dataFile, err
case 400:
return c.DownloadChunkDataStream(id)
case 202:
return nil, ErrPendingTx
case 404:
return nil, ErrNotFound
case 429:
return nil, ErrRequestLimit
default:
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)
if err != nil {
return nil, fmt.Errorf("httpGet error: %v", err)
}
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
case 429:
return nil, ErrRequestLimit
default:
return nil, ErrBadGateway
}
}
func (c *Client) GetTransactionDataStreamByGateway(id string) (*os.File, error) {
urlPath := fmt.Sprintf("/%v/%v", id, "data")
body, statusCode, err := c.httpGet(urlPath)
if err != nil {
return nil, fmt.Errorf("httpGet error: %v", err)
}
switch statusCode {
case 200:
if len(body) == 0 {
return c.DownloadChunkDataStream(id)
}
dataFile, err := os.CreateTemp(".", "arTxData-")
if err != nil {
return nil, err
}
_, err = dataFile.Write(body)
return dataFile, err
case 400:
return c.DownloadChunkDataStream(id)
case 202:
return nil, ErrPendingTx
case 404:
return nil, ErrNotFound
case 410:
return nil, ErrInvalidId
case 429:
return nil, ErrRequestLimit
default:
return nil, ErrBadGateway
}
}
func (c *Client) GetTransactionPrice(dataSize int, target *string) (reward int64, err error) {
url := fmt.Sprintf("price/%d", dataSize)
if target != nil {
url = fmt.Sprintf("%v/%v", url, *target)
}
body, code, err := c.httpGet(url)
if code == 429 {
return 0, ErrRequestLimit
}
if err != nil {
return
}
if code != 200 {
return 0, fmt.Errorf("get reward error: %s", string(body))
}
reward, err = strconv.ParseInt(string(body), 10, 64)
if err != nil {
return
}
// reward can not be 0
if reward <= 0 {
err = errors.New("reward must more than 0")
}
return
}
func (c *Client) GetTransactionAnchor() (anchor string, err error) {
body, code, err := c.httpGet("tx_anchor")
if code == 429 {
return "", ErrRequestLimit
}
if err != nil {
return
}
if code != 200 {
return "", fmt.Errorf("get tx anchor err: %s", string(body))
}
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 statusCode == 429 {
return nil, ErrRequestLimit
}
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) {
winstonAmt, err := c.GetWalletWinstonBalance(address)
if err != nil {
return nil, err
}
arAmount = utils.WinstonToAR(winstonAmt)
return
}
func (c *Client) GetWalletWinstonBalance(address string) (arAmount *big.Int, err error) {
body, code, err := c.httpGet(fmt.Sprintf("wallet/%s/balance", address))
if code == 429 {
return nil, ErrRequestLimit
}
if err != nil {
return
}
if code != 200 {
return nil, fmt.Errorf("get balance error: %s", string(body))
}
winstomStr := string(body)
winstom, ok := new(big.Int).SetString(winstomStr, 10)
if !ok {
err = fmt.Errorf("invalid balance: %v", winstomStr)
return
}
arAmount = winstom
return
}
func (c *Client) GetLastTransactionID(address string) (id string, err error) {
body, code, err := c.httpGet(fmt.Sprintf("wallet/%s/last_tx", address))
if code == 429 {
return "", ErrRequestLimit
}
if err != nil {
return
}
if code != 200 {
return "", fmt.Errorf("get last id error: %s", string(body))
}
id = string(body)
return
}
// Block
func (c *Client) GetBlockByID(id string) (block *types.Block, err error) {
body, code, err := c.httpGet(fmt.Sprintf("block/hash/%s", id))
if err != nil {
return
}
if code == 429 {
return nil, ErrRequestLimit
}
if code != 200 {
return nil, fmt.Errorf("get block by id error: %s", string(body))
}
block, err = utils.DecodeBlock(string(body))
return
}
func (c *Client) GetBlockByHeight(height int64) (block *types.Block, err error) {
body, code, err := c.httpGet(fmt.Sprintf("block/height/%d", height))
if err != nil {
return
}
if code == 429 {
return nil, ErrRequestLimit
}
if code != 200 {
return nil, fmt.Errorf("get block by height error: %s", string(body))
}
block, err = utils.DecodeBlock(string(body))
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 = io.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 = io.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 err != nil {
return nil, fmt.Errorf("httpGet getChunk error: %v", err)
}
switch statusCode {
case 200:
txChunk := &types.TransactionChunk{}
if err := json.Unmarshal(body, txChunk); err != nil {
return nil, err
}
return txChunk, nil
case 404:
return nil, ErrNotFound
case 429:
return nil, ErrRequestLimit
default:
return nil, ErrBadGateway
}
}
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 == 429 {
return nil, ErrRequestLimit
}
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
}
// it's caller's responsibility to reserve or delete the tmp file created by this method
func (c *Client) DownloadChunkDataStream(id string) (*os.File, 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
dataFile, err := os.CreateTemp(".", "chunkData-")
if err != nil {
return nil, err
}
downloadSize := 0
n := 0
for i := 0; int64(i)+startOffset < endOffset; {
chunkData, err := c.getChunkData(int64(i) + startOffset)
if err != nil {
return nil, err
}
downloadSize += len(chunkData)
n, err = dataFile.Write(chunkData)
if err != nil || n < len(chunkData) {
return nil, fmt.Errorf("write chunkData to dataFile failed")
}
fmt.Printf("download chunk data; offset: %d/%d; size: %d/%d \n", int64(i)+startOffset, endOffset, downloadSize, size)
i += len(chunkData)
}
return dataFile, nil
}
func (c *Client) ConcurrentDownloadChunkData(id string, concurrentNum int) ([]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
offsetArr := make([]int64, 0, 5)
for i := 0; int64(i)+startOffset < endOffset; {
offsetArr = append(offsetArr, int64(i)+startOffset)
i += types.MAX_CHUNK_SIZE
}
if len(offsetArr) <= 3 { // not need concurrent get chunks
return c.DownloadChunkData(id)
}
log.Debug("need download chunks length", "length", len(offsetArr))
// concurrent get chunks
type OffsetSort struct {
Idx int
Offset int64
}
chunkArr := make([][]byte, len(offsetArr)-2)
var (
lock sync.Mutex
wg sync.WaitGroup
)
if concurrentNum <= 0 {
concurrentNum = types.DEFAULT_CHUNK_CONCURRENT_NUM
}
p, _ := ants.NewPoolWithFunc(concurrentNum, func(i interface{}) {
defer wg.Done()
oss := i.(OffsetSort)
chunkData, err := c.getChunkData(oss.Offset)
if err != nil {
count := 0
for count < 2 {
time.Sleep(1 * time.Second)
chunkData, err = c.getChunkData(oss.Offset)
if err == nil {
break
}
log.Error("retry getChunkData failed and try again...", "err", err, "idx", oss.Idx, "offset", oss.Offset, "retryCount", count, "arId", id)
if err != ErrRequestLimit {
count++
}
}
}
lock.Lock()
chunkArr[oss.Idx] = chunkData
lock.Unlock()
})
defer p.Release()
for i, offset := range offsetArr[:len(offsetArr)-2] {
wg.Add(1)
if err := p.Invoke(OffsetSort{Idx: i, Offset: offset}); err != nil {
log.Error("p.Invoke(i)", "err", err, "i", i)
return nil, err
}
}
wg.Wait()
// add latest 2 chunks
start := offsetArr[len(offsetArr)-3] + types.MAX_CHUNK_SIZE
for i := 0; int64(i)+start < endOffset; {
chunkData, err := c.getChunkData(int64(i) + start)
if err != nil {
count := 0
for count < 2 {
time.Sleep(1 * time.Second)
chunkData, err = c.getChunkData(int64(i) + start)
if err == nil {
break
}
log.Error("latest two chunks retry getChunkData failed and try again...", "err", err, "offset", int64(i)+start, "retryCount", count, "arId", id)
if err != ErrRequestLimit {
count++
}
}
}
if err != nil {
return nil, errors.New("concurrent get latest two chunks failed")
}
chunkArr = append(chunkArr, chunkData)
i += len(chunkData)
}
// assemble data
data := make([]byte, 0, size)
for _, chunk := range chunkArr {
if chunk == nil {
return nil, errors.New("concurrent get chunk failed")
}
data = append(data, chunk...)
}
return data, nil
}
// it's caller's responsibility to reserve or delete the tmp file created by this method
func (c *Client) ConcurrentDownloadChunkDataStream(id string, concurrentNum int) (dataFile *os.File, err 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
offsetArr := make([]int64, 0, 5)
for i := 0; int64(i)+startOffset < endOffset; {
offsetArr = append(offsetArr, int64(i))
i += types.MAX_CHUNK_SIZE
}
log.Debug("need download chunks length", "length", len(offsetArr))
dataFile, err = os.CreateTemp(".", "concurrent-load-data-")
if err != nil {
return nil, err
}
defer func() {
if err != nil {
dataFile.Close()
os.Remove(dataFile.Name())
}
}()
if len(offsetArr) <= 3 { // not need concurrent get chunks
var data []byte
data, err = c.DownloadChunkData(id)
if err != nil {
return
}
_, err = dataFile.Write(data)
return dataFile, err
}
type Offset struct {
fileOffset int64
chunkOffset int64
}
var (
lock sync.Mutex
wg sync.WaitGroup
)
if concurrentNum <= 0 {
concurrentNum = types.DEFAULT_CHUNK_CONCURRENT_NUM
}
p, _ := ants.NewPoolWithFunc(concurrentNum, func(i interface{}) {
defer wg.Done()
oss := i.(Offset)
chunkData, err := c.getChunkData(oss.chunkOffset)
if err != nil {
count := 0
for count < 5 {
time.Sleep(1 * time.Second)
chunkData, err = c.getChunkData(oss.chunkOffset)
if err == nil {
break
}
log.Warn("retry getChunkData failed and try again...", "err", err, "idx", oss.fileOffset/types.MAX_CHUNK_SIZE, "offset", oss.chunkOffset, "retryCount", count, "arId", id)
if err != ErrRequestLimit {
count++
}
}
}
if err != nil {
log.Error("getChunkData failed", "err", err, "arId", id, "idx", oss.fileOffset/types.MAX_CHUNK_SIZE, "offset", oss.chunkOffset)
return
}
var n int
lock.Lock()
n, err = dataFile.WriteAt(chunkData, oss.fileOffset)
if err != nil || n < len(chunkData) {
log.Error("write dataFile error")
}
lock.Unlock()
})
defer p.Release()
for i, offset := range offsetArr[:len(offsetArr)-2] {
wg.Add(1)
if err = p.Invoke(Offset{fileOffset: offset, chunkOffset: offset + startOffset}); err != nil {
log.Error("p.Invoke(i)", "err", err, "i", i)
return
}
}
wg.Wait()
_, err = dataFile.Seek(0, 2)
if err != nil {
return
}
// add latest 2 chunks
start := offsetArr[len(offsetArr)-3] + startOffset + types.MAX_CHUNK_SIZE
for i := 0; int64(i)+start < endOffset; {
var chunkData []byte
chunkData, err = c.getChunkData(int64(i) + start)
if err != nil {
count := 0
for count < 5 {
time.Sleep(1 * time.Second)
chunkData, err = c.getChunkData(int64(i) + start)
if err == nil {
break
}
log.Error("latest two chunks retry getChunkData failed and try again...", "err", err, "offset", int64(i)+start, "retryCount", count, "arId", id)
if err != ErrRequestLimit {
count++
}
}
}
if err != nil {
err = errors.New(fmt.Sprintf("concurrent get latest two chunks failed,err:%v", err))
return
}
n := 0
n, err = dataFile.Write(chunkData)
if err != nil || n < len(chunkData) {
err = fmt.Errorf("write dataFile error writeSize:%d, expectSize:%d", n, len(chunkData))
return
}
i += len(chunkData)
}
return dataFile, 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
}
func (c *Client) GetPendingTxIds() ([]string, error) {
body, statusCode, err := c.httpGet("/tx/pending")
if statusCode != 200 {
return nil, errors.New("get pending txIds failed")
}
if err != nil {
return nil, err
}
res := make([]string, 0)
if err := json.Unmarshal(body, &res); err != nil {
return nil, err
}
return res, nil
}
func (c *Client) GetBlockHashList(from, to int) ([]string, error) {
if from > to {
return nil, errors.New("from must <= to")
}
body, statusCode, err := c.httpGet("/hash_list/" + strconv.Itoa(from) + "/" + strconv.Itoa(to))
if statusCode != 200 {
return nil, errors.New("get block hash list failed")
}
if err != nil {
return nil, err
}
res := make([]string, 0)
if err := json.Unmarshal(body, &res); err != nil {
return nil, err
}
return res, nil
}
func (c *Client) ExistTxData(arId string) (bool, error) {
offsetResponse, err := c.getTransactionOffset(arId)
if err != nil {
return false, err
}
endOffset := offsetResponse.Offset
records, err := c.DataSyncRecord(endOffset, 1)
if err != nil {
return false, err
}
if len(records) == 0 {
return false, errors.New("c.DataSyncRecord(endOffset,1) is null")
}
record := records[0]
// if tx data has end offset 145 and size 10 (you can see it in GET /tx/<id>/offset),
// you can query GET /data_sync_record/145/1
// - you will receive {"<end>": "<start>"} => the node has the tx data if start =< 145 - 10
mmp := gjson.Parse(record).Map()
start := ""
for _, val := range mmp {
start = val.String()
break
}
startNum, err := strconv.Atoi(start)
if err != nil {