-
Notifications
You must be signed in to change notification settings - Fork 9
/
data_transfer.go
1341 lines (1129 loc) · 46.4 KB
/
data_transfer.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 rpc
import (
"bytes"
"context"
"encoding/json"
"errors"
"fmt"
"math/big"
"math/rand"
"net/http"
"os"
"path/filepath"
"sort"
"strconv"
"strings"
"sync"
"time"
"github.com/filefilego/filefilego/block"
"github.com/filefilego/filefilego/common"
"github.com/filefilego/filefilego/common/currency"
"github.com/filefilego/filefilego/common/hexutil"
"github.com/filefilego/filefilego/contract"
ffgcrypto "github.com/filefilego/filefilego/crypto"
"github.com/filefilego/filefilego/keystore"
dataquery "github.com/filefilego/filefilego/node/protocols/data_query"
dataverification "github.com/filefilego/filefilego/node/protocols/data_verification"
"github.com/filefilego/filefilego/node/protocols/messages"
"github.com/filefilego/filefilego/transaction"
"github.com/libp2p/go-libp2p/core/host"
"github.com/libp2p/go-libp2p/core/peer"
log "github.com/sirupsen/logrus"
"google.golang.org/protobuf/proto"
)
// PublisherNodesFinder is an interface that specifies finding nodes and publishing a message to the network functionalities.
type PublisherNodesFinder interface {
NetworkMessagePublisher
FindPeers(ctx context.Context, peerIDs []peer.ID) []peer.AddrInfo
}
// DataTransferAPI represents the data transfer rpc service which includes data query and verification protocols.
type DataTransferAPI struct {
host host.Host
dataQueryProtocol dataquery.Interface
dataVerificationProtocol dataverification.Interface
publisherNodesFinder PublisherNodesFinder
contractStore contract.Interface
keystore keystore.KeyAuthorizer
}
// NewDataTransferAPI creates a new data transfer API to be served using JSONRPC.
func NewDataTransferAPI(host host.Host, dataQueryProtocol dataquery.Interface, dataVerificationProtocol dataverification.Interface, publisherNodeFinder PublisherNodesFinder, contractStore contract.Interface, keystore keystore.KeyAuthorizer) (*DataTransferAPI, error) {
if host == nil {
return nil, errors.New("host is nil")
}
if dataQueryProtocol == nil {
return nil, errors.New("data query protocol is nil")
}
if dataVerificationProtocol == nil {
return nil, errors.New("data verification protocol is nil")
}
if publisherNodeFinder == nil {
return nil, errors.New("publisherNodeFinder is nil")
}
if contractStore == nil {
return nil, errors.New("contractStore is nil")
}
if keystore == nil {
return nil, errors.New("keystore is nil")
}
return &DataTransferAPI{
host: host,
dataQueryProtocol: dataQueryProtocol,
dataVerificationProtocol: dataVerificationProtocol,
publisherNodesFinder: publisherNodeFinder,
contractStore: contractStore,
keystore: keystore,
}, nil
}
// SendDataQueryRequestArgs is a data query request argument.
type SendDataQueryRequestArgs struct {
// FileHashes is a list of comma-separated file hashes.
FileHashes string `json:"file_hashes"`
}
// SendDataQueryRequestResponse is a data query hash response.
type SendDataQueryRequestResponse struct {
Hash string `json:"hash"`
}
// SendDataQueryRequest sends a data query request to the network.
func (api *DataTransferAPI) SendDataQueryRequest(r *http.Request, args *SendDataQueryRequestArgs, response *SendDataQueryRequestResponse) error {
if args.FileHashes == "" {
return errors.New("no file's in the request")
}
list := strings.Split(args.FileHashes, ",")
request := messages.DataQueryRequest{
FileHashes: make([][]byte, 0),
FromPeerAddr: api.host.ID().String(),
Timestamp: time.Now().Unix(),
}
for _, v := range list {
trimmed := strings.TrimSpace(v)
if trimmed == "" {
continue
}
fileHash, err := hexutil.DecodeNoPrefix(trimmed)
if err != nil {
return fmt.Errorf("failed to decode file hash: %w", err)
}
request.FileHashes = append(request.FileHashes, fileHash)
}
requestHash := request.GetHash()
request.Hash = make([]byte, len(requestHash))
copy(request.Hash, requestHash)
err := request.Validate()
if err != nil {
return fmt.Errorf("failed to validate data query request: %w", err)
}
requestHashHex := hexutil.Encode(requestHash)
err = api.dataQueryProtocol.PutQueryHistory(requestHashHex, request)
if err != nil {
return fmt.Errorf("failed to insert data query request: %w", err)
}
requestProto := messages.ToDataQueryRequestProto(request)
payload := messages.GossipPayload{
Message: &messages.GossipPayload_Query{
Query: requestProto,
},
}
payloadBytes, err := proto.Marshal(&payload)
if err != nil {
return fmt.Errorf("failed to marshal data query gossip payload: %w", err)
}
if err := api.publisherNodesFinder.PublishMessageToNetwork(r.Context(), payloadBytes); err != nil {
return fmt.Errorf("failed to publish data query to network: %w", err)
}
response.Hash = requestHashHex
return nil
}
// GetDownloadContractArgs represent the args.
type GetDownloadContractArgs struct {
ContractHash string `json:"contract_hash"`
}
// DownloadContractJSON is a download contract in JSON.
type DownloadContractJSON struct {
FileHosterResponse DataQueryResponseJSON `json:"file_hoster_response"`
FileRequesterNodePublicKey string `json:"file_requester_node_public_key"`
FileHashesNeeded []string `json:"file_hashes_needed"`
FileHashesNeededSizes []uint64 `json:"file_hashes_needed_sizes"`
VerifierPublicKey string `json:"verifier_public_key"`
VerifierFees string `json:"verifier_fees"`
ContractHash string `json:"contract_hash"`
VerifierSignature string `json:"verifier_signature"`
}
// GetDownloadContractResponse represents the response.
type GetDownloadContractResponse struct {
Contract DownloadContractJSON `json:"contract"`
}
// GetDownloadContract returns a contract from the memmory.
func (api *DataTransferAPI) GetDownloadContract(r *http.Request, args *GetDownloadContractArgs, response *GetDownloadContractResponse) error {
if args.ContractHash == "" {
return errors.New("contract hash is empty")
}
downloadContract, err := api.contractStore.GetContract(args.ContractHash)
if err != nil {
return fmt.Errorf("failed to get contract: %w", err)
}
dqrJSON := DataQueryResponseJSON{
FromPeerAddr: downloadContract.FileHosterResponse.FromPeerAddr,
FeesPerByte: downloadContract.FileHosterResponse.FeesPerByte,
HashDataQueryRequest: hexutil.Encode(downloadContract.FileHosterResponse.HashDataQueryRequest),
PublicKey: hexutil.Encode(downloadContract.FileHosterResponse.PublicKey),
Signature: hexutil.Encode(downloadContract.FileHosterResponse.Signature),
FileHashes: make([]string, len(downloadContract.FileHosterResponse.FileHashes)),
FileHashesSizes: downloadContract.FileHosterResponse.FileHashesSizes,
UnavailableFileHashes: make([]string, len(downloadContract.FileHosterResponse.UnavailableFileHashes)),
Timestamp: downloadContract.FileHosterResponse.Timestamp,
}
for i, j := range downloadContract.FileHosterResponse.FileHashes {
dqrJSON.FileHashes[i] = hexutil.EncodeNoPrefix(j)
}
for i, j := range downloadContract.FileHosterResponse.UnavailableFileHashes {
dqrJSON.UnavailableFileHashes[i] = hexutil.EncodeNoPrefix(j)
}
jsonContract := DownloadContractJSON{
FileHosterResponse: dqrJSON,
FileRequesterNodePublicKey: hexutil.Encode(downloadContract.FileRequesterNodePublicKey),
FileHashesNeeded: make([]string, len(downloadContract.FileHashesNeeded)),
FileHashesNeededSizes: make([]uint64, len(downloadContract.FileHashesNeededSizes)),
VerifierPublicKey: hexutil.Encode(downloadContract.VerifierPublicKey),
VerifierFees: downloadContract.VerifierFees,
ContractHash: hexutil.Encode(downloadContract.ContractHash),
VerifierSignature: hexutil.Encode(downloadContract.VerifierSignature),
}
for i, j := range downloadContract.FileHashesNeeded {
jsonContract.FileHashesNeeded[i] = hexutil.EncodeNoPrefix(j)
}
copy(jsonContract.FileHashesNeededSizes, downloadContract.FileHashesNeededSizes)
response.Contract = jsonContract
return nil
}
// CheckDataQueryResponseArgs is a data query response arg.
type CheckDataQueryResponseArgs struct {
DataQueryRequestHash string `json:"data_query_request_hash"`
}
// CheckDataQueryResponse is a data query response payload.
type CheckDataQueryResponse struct {
Responses []DataQueryResponseJSON `json:"responses"`
}
// DataQueryResponseJSON represents a json payload which represents a DataQueryResponse.
type DataQueryResponseJSON struct {
FromPeerAddr string `json:"from_peer_addr"`
FeesPerByte string `json:"fees_per_byte"`
HashDataQueryRequest string `json:"hash_data_query_request"`
PublicKey string `json:"public_key"`
Signature string `json:"signature"`
FileHashes []string `json:"file_hashes"`
FileHashesSizes []uint64 `json:"file_hashes_sizes"`
UnavailableFileHashes []string `json:"unavailable_file_hashes"`
Timestamp int64 `json:"timestamp"`
}
// CheckDataQueryResponse returns a list of data query responses.
func (api *DataTransferAPI) CheckDataQueryResponse(r *http.Request, args *CheckDataQueryResponseArgs, response *CheckDataQueryResponse) error {
if args.DataQueryRequestHash == "" {
return errors.New("data query hash is empty")
}
responses, _ := api.dataQueryProtocol.GetQueryResponse(args.DataQueryRequestHash)
response.Responses = make([]DataQueryResponseJSON, 0)
for _, v := range responses {
dqrJSON := DataQueryResponseJSON{
FromPeerAddr: v.FromPeerAddr,
FeesPerByte: v.FeesPerByte,
HashDataQueryRequest: hexutil.Encode(v.HashDataQueryRequest),
PublicKey: hexutil.Encode(v.PublicKey),
Signature: hexutil.Encode(v.Signature),
FileHashes: make([]string, len(v.FileHashes)),
FileHashesSizes: v.FileHashesSizes,
UnavailableFileHashes: make([]string, len(v.UnavailableFileHashes)),
Timestamp: v.Timestamp,
}
for i, j := range v.FileHashes {
dqrJSON.FileHashes[i] = hexutil.EncodeNoPrefix(j)
}
for i, j := range v.UnavailableFileHashes {
dqrJSON.UnavailableFileHashes[i] = hexutil.EncodeNoPrefix(j)
}
response.Responses = append(response.Responses, dqrJSON)
}
return nil
}
// RequestDataQueryResponseFromVerifiers returns a list of data query responses by contacting the verifiers.
func (api *DataTransferAPI) RequestDataQueryResponseFromVerifiers(r *http.Request, args *CheckDataQueryResponseArgs, response *CheckDataQueryResponse) error {
if args.DataQueryRequestHash == "" {
return errors.New("data query hash is empty")
}
dataQueryRequestHashBytes, err := hexutil.Decode(args.DataQueryRequestHash)
if err != nil {
return fmt.Errorf("failed to decode data query request hash: %w", err)
}
verfiers := block.GetBlockVerifiers()
peerIDs := make([]peer.ID, 0)
for _, v := range verfiers {
publicKey, err := ffgcrypto.PublicKeyFromHex(v.PublicKey)
if err != nil {
continue
}
peerID, err := peer.IDFromPublicKey(publicKey)
if err != nil {
continue
}
peerIDs = append(peerIDs, peerID)
}
addrsInfos := api.publisherNodesFinder.FindPeers(r.Context(), peerIDs)
dqrTransferRequest := &messages.DataQueryResponseTransferProto{Hash: dataQueryRequestHashBytes}
if len(addrsInfos) > 0 {
var wg sync.WaitGroup
for _, addInfo := range addrsInfos {
wg.Add(1)
go func(peerID peer.ID) {
defer wg.Done()
_ = api.dataQueryProtocol.RequestDataQueryResponseTransfer(r.Context(), peerID, dqrTransferRequest)
}(addInfo.ID)
}
wg.Wait()
}
// query again the inmem store to check if data query response from verifiers populated the store
responses, _ := api.dataQueryProtocol.GetQueryResponse(args.DataQueryRequestHash)
response.Responses = make([]DataQueryResponseJSON, 0)
for _, v := range responses {
dqrJSON := DataQueryResponseJSON{
FromPeerAddr: v.FromPeerAddr,
FeesPerByte: v.FeesPerByte,
HashDataQueryRequest: hexutil.Encode(v.HashDataQueryRequest),
PublicKey: hexutil.Encode(v.PublicKey),
Signature: hexutil.Encode(v.Signature),
FileHashes: make([]string, len(v.FileHashes)),
FileHashesSizes: v.FileHashesSizes,
UnavailableFileHashes: make([]string, len(v.UnavailableFileHashes)),
Timestamp: v.Timestamp,
}
for i, j := range v.FileHashes {
dqrJSON.FileHashes[i] = hexutil.EncodeNoPrefix(j)
}
for i, j := range v.UnavailableFileHashes {
dqrJSON.UnavailableFileHashes[i] = hexutil.EncodeNoPrefix(j)
}
response.Responses = append(response.Responses, dqrJSON)
}
return nil
}
// PauseFileDownloadArgs represent args.
type PauseFileDownloadArgs struct {
ContractHash string `json:"contract_hash"`
FileHash string `json:"file_hash"`
}
// PauseFileDownloadResponse represent response.
type PauseFileDownloadResponse struct{}
// PauseFileDownload pauses a file download.
func (api *DataTransferAPI) PauseFileDownload(r *http.Request, args *PauseFileDownloadArgs, response *PauseFileDownloadResponse) error {
_, err := api.contractStore.GetContract(args.ContractHash)
if err != nil {
return fmt.Errorf("contract not found: %w", err)
}
_, err = hexutil.DecodeNoPrefix(args.FileHash)
if err != nil {
return fmt.Errorf("failed to decode file hash: %w", err)
}
err = api.contractStore.CancelContractFileDownloadContexts(args.ContractHash + args.FileHash)
if err != nil {
return fmt.Errorf("failed to cancel download contexts: %w", err)
}
return nil
}
// DownloadFileArgs represent args.
type DownloadFileArgs struct {
ContractHash string `json:"contract_hash"`
FileHash string `json:"file_hash"`
ReDownload bool `json:"re_download"`
}
// DownloadFileArgs represents a response.
type DownloadFileResponse struct {
Status string `json:"status"`
}
// DownloadFile downloads a file from a contract.
func (api *DataTransferAPI) DownloadFile(r *http.Request, args *DownloadFileArgs, response *DownloadFileResponse) error {
downloadContract, err := api.contractStore.GetContract(args.ContractHash)
if err != nil {
return fmt.Errorf("contract not found: %w", err)
}
fileHash, err := hexutil.DecodeNoPrefix(args.FileHash)
if err != nil {
return fmt.Errorf("failed to decode file hash: %w", err)
}
fileHoster, err := peer.Decode(downloadContract.FileHosterResponse.FromPeerAddr)
if err != nil {
return fmt.Errorf("failed to decode file hoster's peer id: %w", err)
}
fileSize := uint64(0)
for i, v := range downloadContract.FileHashesNeeded {
if bytes.Equal(v, fileHash) {
fileSize = downloadContract.FileHashesNeededSizes[i]
}
}
if fileSize == 0 {
return fmt.Errorf("file size is zero")
}
// trigger a file initialization by seting the size of the file
api.contractStore.SetFileSize(args.ContractHash, fileHash, fileSize)
go func() {
if args.ReDownload {
// cancel all pending contexts
_ = api.contractStore.CancelContractFileDownloadContexts(args.ContractHash + args.FileHash)
// delete all the downloaded file parts
fileParts := api.contractStore.GetDownoadedFilePartInfos(args.ContractHash, fileHash)
for _, v := range fileParts {
err := os.Remove(v.DestinationFilePath)
if err != nil {
log.Warnf("failed to remove old downloaded file part %s : %v", v.DestinationFilePath, err)
}
}
// reset the file bytes transfered
err := api.contractStore.ResetTransferedBytes(args.ContractHash, fileHash)
if err != nil {
log.Warnf("failed to rest file transfered bytes: %v", err)
}
}
// create initial file ranges
fileRanges := createFileRanges(int64(fileSize))
// create file ranges from downloaded file parts
fileRangesFromDownloadedParts, err := getDownloadedPartsInfo(filepath.Join(api.dataVerificationProtocol.GetDownloadDirectory(), args.ContractHash))
if err == nil && len(fileRanges) == len(fileRangesFromDownloadedParts) {
// if no error
for i, v := range fileRanges {
for _, fr := range fileRangesFromDownloadedParts {
if v.from == fr.from && v.to == fr.to {
fileRanges[i].availableSize = fr.availableSize
}
}
}
}
wg := sync.WaitGroup{}
for _, v := range fileRanges {
v := v
// skip the parts which are already downloaded
if v.to-v.from+1 == v.availableSize {
continue
}
wg.Add(1)
go func(fileRange FileRanges) {
request := &messages.FileTransferInfoProto{
ContractHash: downloadContract.ContractHash,
FileHash: fileHash,
FileSize: fileSize,
From: fileRange.from + fileRange.availableSize,
To: fileRange.to,
}
ctxWithCancel, cancel := context.WithCancel(context.Background())
api.contractStore.SetContractFileDownloadContexts(args.ContractHash+args.FileHash, contract.ContextFileDownloadData{
From: fileRange.from + fileRange.availableSize,
To: fileRange.to,
Ctx: ctxWithCancel,
Cancel: cancel,
})
fileHashHex := hexutil.EncodeNoPrefix(request.FileHash)
fileNameWithPart := fmt.Sprintf("%s_part_%d_%d", fileHashHex, fileRange.from, fileRange.to)
destinationFilePath := filepath.Join(api.dataVerificationProtocol.GetDownloadDirectory(), hexutil.Encode(request.ContractHash), fileNameWithPart)
_, err := api.dataVerificationProtocol.RequestFileTransfer(ctxWithCancel, destinationFilePath, fileNameWithPart, fileHoster, request)
// if the context wasnt canceled set the error
if err != nil && !errors.Is(err, context.Canceled) {
fileHashHex := hexutil.EncodeNoPrefix(fileHash)
fileNameWithPart := fmt.Sprintf("%s_part_%d_%d", fileHashHex, fileRange.from, fileRange.to)
api.contractStore.SetFilePartDownloadError(args.ContractHash, fileHash, fileNameWithPart, err.Error())
}
wg.Done()
}(v)
}
wg.Wait()
// check if all file parts have been downloaded
totalDownloaded := api.contractStore.GetTransferedBytes(args.ContractHash, fileHash)
if totalDownloaded != fileSize {
api.contractStore.SetError(args.ContractHash, fileHash, fmt.Sprintf("total downloaded parts size (%d) is not equal to the file size (%d)", totalDownloaded, fileSize))
return
}
// reassemble all file parts
filePartInfos := api.contractStore.GetDownoadedFilePartInfos(args.ContractHash, fileHash)
outputFilePath := filepath.Join(filepath.Dir(filePartInfos[0].DestinationFilePath), args.FileHash)
log.Info("outputfile path ", outputFilePath)
fileParts := make([]string, len(filePartInfos))
for i, v := range filePartInfos {
fileParts[i] = v.DestinationFilePath
}
err = common.ConcatenateFiles(outputFilePath, fileParts)
if err != nil {
api.contractStore.SetError(args.ContractHash, fileHash, fmt.Sprintf("failed to concatenate downloaded file parts: %s", err.Error()))
return
}
// delete the part files
for _, v := range fileParts {
err := os.Remove(v)
if err != nil {
log.Warnf("failed to remove file %s : %v", v, err)
}
}
}()
response.Status = "started"
return nil
}
func getDownloadedPartsInfo(downloadedPartsFolder string) ([]FileRanges, error) {
filesRanges := make([]FileRanges, 0)
f, err := os.Open(downloadedPartsFolder)
if err != nil {
return nil, fmt.Errorf("failed to open downloaded parts folder: %w", err)
}
fileInfo, err := f.Readdir(-1)
if err != nil {
return nil, fmt.Errorf("failed to read downloaded parts folder content: %w", err)
}
f.Close()
for _, file := range fileInfo {
fileParts := strings.Split(file.Name(), "_part_")
if len(fileParts) == 2 {
fromToParts := strings.Split(fileParts[1], "_")
if len(fromToParts) == 2 {
from, err := strconv.ParseInt(fromToParts[0], 10, 64)
if err != nil {
continue
}
to, err := strconv.ParseInt(fromToParts[1], 10, 64)
if err != nil {
continue
}
tmpRange := FileRanges{
from: from,
to: to,
availableSize: file.Size(),
}
filesRanges = append(filesRanges, tmpRange)
}
}
}
sort.Slice(filesRanges, func(i, j int) bool { return filesRanges[i].to < filesRanges[j].to })
return filesRanges, nil
}
type FileRanges struct {
from int64
to int64
availableSize int64
}
func createFileRanges(fileSize int64) []FileRanges {
numWorkers := int64(4)
chunkSize := fileSize / numWorkers
ranges := make([]FileRanges, 0)
if chunkSize == 0 {
ranges = append(ranges, FileRanges{
from: 0,
to: fileSize - 1,
})
return ranges
}
for i := 0; i < int(numWorkers); i++ {
start := int64(i) * chunkSize
end := int64(0)
if i == int(numWorkers-1) {
end = fileSize - 1
} else {
end = start + chunkSize - 1
}
ranges = append(ranges, FileRanges{
from: start,
to: end,
})
}
return ranges
}
// DownloadFileProgressArgs represent args.
type DownloadFileProgressArgs struct {
ContractHash string `json:"contract_hash"`
FileHash string `json:"file_hash"`
}
// DownloadFileProgressResponse represents the response of a download file progress.
type DownloadFileProgressResponse struct {
Error string `json:"error"`
BytesTransfered uint64 `json:"bytes_transfered"`
}
// DownloadFileProgress returns the download progress of a file.
func (api *DataTransferAPI) DownloadFileProgress(r *http.Request, args *DownloadFileProgressArgs, response *DownloadFileProgressResponse) error {
fileHash, err := hexutil.DecodeNoPrefix(args.FileHash)
if err != nil {
return fmt.Errorf("failed to decode file hash: %w", err)
}
fileInfo, err := api.contractStore.GetContractFileInfo(args.ContractHash, fileHash)
if err != nil {
return fmt.Errorf("contract not found: %w", err)
}
response.BytesTransfered = api.contractStore.GetTransferedBytes(args.ContractHash, fileHash)
response.Error = fileInfo.Error
return nil
}
// SendFileMerkleTreeNodesToVerifierArgs represents args.
type SendFileMerkleTreeNodesToVerifierArgs struct {
ContractHash string `json:"contract_hash"`
FileHash string `json:"file_hash"`
}
// SendFileMerkleTreeNodesToVerifierResponse represents a struct.
type SendFileMerkleTreeNodesToVerifierResponse struct {
Success bool `json:"success"`
}
// SendFileMerkleTreeNodesToVerifier sends the merkle tree nodes of a downloaded encrypted file to verifier from the file downloader.
func (api *DataTransferAPI) SendFileMerkleTreeNodesToVerifier(r *http.Request, args *SendFileMerkleTreeNodesToVerifierArgs, response *SendFileMerkleTreeNodesToVerifierResponse) error {
fileHash, err := hexutil.DecodeNoPrefix(args.FileHash)
if err != nil {
return fmt.Errorf("failed to decode file hash: %w", err)
}
downloadContract, err := api.contractStore.GetContract(args.ContractHash)
if err != nil {
return fmt.Errorf("contract not found: %w", err)
}
fileInfo, err := api.contractStore.GetContractFileInfo(args.ContractHash, fileHash)
if err != nil {
return fmt.Errorf("contract not found: %w", err)
}
transferedBytes := api.contractStore.GetTransferedBytes(args.ContractHash, fileHash)
if fileInfo.Error != "" {
return fmt.Errorf("contract file info failure: %s", fileInfo.Error)
}
if fileInfo.FileSize != transferedBytes {
return fmt.Errorf("file wasn't fully transfered: size: %d, transfered: %d", fileInfo.FileSize, transferedBytes)
}
totalDesiredSegments, _ := api.dataVerificationProtocol.GetMerkleTreeFileSegmentsEncryptionPercentage()
downloadDir := api.dataVerificationProtocol.GetDownloadDirectory()
fileHashWithPrefix := hexutil.EncodeNoPrefix(fileHash)
destinationFilePath := filepath.Join(downloadDir, args.ContractHash, fileHashWithPrefix)
orderedSlice := make([]int, totalDesiredSegments)
for i := 0; i < totalDesiredSegments; i++ {
orderedSlice[i] = i
}
merkleNodes, err := common.HashFileBlockSegments(destinationFilePath, totalDesiredSegments, orderedSlice)
if err != nil {
return fmt.Errorf("failed to hash downloaded file block segments: %w", err)
}
contractHash, err := hexutil.Decode(args.ContractHash)
if err != nil {
return fmt.Errorf("failed to decode contract hash: %w", err)
}
merkleRequest := &messages.MerkleTreeNodesOfFileContractProto{
ContractHash: contractHash,
FileHash: fileHash,
MerkleTreeNodes: make([][]byte, len(merkleNodes)),
}
for i, v := range merkleNodes {
merkleRequest.MerkleTreeNodes[i] = make([]byte, len(v.X))
copy(merkleRequest.MerkleTreeNodes[i], v.X)
}
publicKey, err := ffgcrypto.PublicKeyFromBytes(downloadContract.VerifierPublicKey)
if err != nil {
return fmt.Errorf("failed to get verifier's public key: %w", err)
}
verifierID, err := peer.IDFromPublicKey(publicKey)
if err != nil {
return fmt.Errorf("failed to get verifier's peer id: %w", err)
}
err = api.dataVerificationProtocol.SendFileMerkleTreeNodesToVerifier(context.Background(), verifierID, merkleRequest)
if err != nil {
return fmt.Errorf("failed to send merkle tree nodes to verifier: %w", err)
}
response.Success = true
return nil
}
// RequestEncryptionDataFromVerifierArgs represents args.
type RequestEncryptionDataFromVerifierArgs struct {
ContractHash string `json:"contract_hash"`
FileHashes []string `json:"file_hashes"`
FileMerkleRootHashes []string `json:"file_merkle_root_hashes"`
RestoredFilePaths []string `json:"restored_file_paths"`
}
// RequestEncryptionDataFromVerifierResponse represents the response.
type RequestEncryptionDataFromVerifierResponse struct {
DecryptedFilePaths []string `json:"decrypted_file_paths"`
}
// RequestEncryptionDataFromVerifierAndDecrypt requires encryption data from verifier and decrypts.
func (api *DataTransferAPI) RequestEncryptionDataFromVerifierAndDecrypt(r *http.Request, args *RequestEncryptionDataFromVerifierArgs, response *RequestEncryptionDataFromVerifierResponse) error {
if len(args.FileHashes) != len(args.FileMerkleRootHashes) {
return errors.New("size of merkle root hashes and the file hashes are not equal")
}
downloadContract, err := api.contractStore.GetContract(args.ContractHash)
if err != nil {
return fmt.Errorf("contract not found: %w", err)
}
encRequest := &messages.KeyIVRequestsProto{
KeyIvs: make([]*messages.KeyIVProto, 0),
}
for idx, v := range args.FileHashes {
fileHash, err := hexutil.DecodeNoPrefix(v)
if err != nil {
return fmt.Errorf("failed to decode file hash: %w", err)
}
fileInfo, err := api.contractStore.GetContractFileInfo(args.ContractHash, fileHash)
if err != nil {
return fmt.Errorf("contract not found: %w", err)
}
transferedBytes := api.contractStore.GetTransferedBytes(args.ContractHash, fileHash)
if fileInfo.Error != "" {
return fmt.Errorf("contract file info failure: %s", fileInfo.Error)
}
if fileInfo.FileSize != transferedBytes {
return fmt.Errorf("file wasn't fully transfered: size: %d, transfered: %d", fileInfo.FileSize, transferedBytes)
}
contractHashBytes, err := hexutil.Decode(args.ContractHash)
if err != nil {
return fmt.Errorf("failed to decode contract hash: %w", err)
}
merkleRootHash, err := hexutil.Decode(args.FileMerkleRootHashes[idx])
if err != nil {
return fmt.Errorf("failed to decode merkle root hash: %w", err)
}
encRequest.KeyIvs = append(encRequest.KeyIvs, &messages.KeyIVProto{
ContractHash: contractHashBytes,
FileHash: fileHash,
FileMerkleRootHash: merkleRootHash,
})
}
publicKey, err := ffgcrypto.PublicKeyFromBytes(downloadContract.VerifierPublicKey)
if err != nil {
return fmt.Errorf("failed to get verifier's public key: %w", err)
}
verifierID, err := peer.IDFromPublicKey(publicKey)
if err != nil {
return fmt.Errorf("failed to get verifier's peer id: %w", err)
}
encryptionData, err := api.dataVerificationProtocol.RequestEncryptionData(context.Background(), verifierID, encRequest)
if err != nil {
return fmt.Errorf("failed to request decryption data from verifier: %w", err)
}
response.DecryptedFilePaths = make([]string, 0)
for i, v := range encryptionData.KeyIvRandomizedFileSegments {
foundIdx := -1
for j, w := range encRequest.KeyIvs {
if bytes.Equal(v.FileHash, w.FileHash) {
foundIdx = j
break
}
}
if foundIdx == -1 {
return fmt.Errorf("decryption data doesn't contain the requested file hash: %s", hexutil.Encode(v.FileHash))
}
randomizedSegsFromKey := make([]int, len(encryptionData.KeyIvRandomizedFileSegments[i].RandomizedSegments))
for i, v := range encryptionData.KeyIvRandomizedFileSegments[i].RandomizedSegments {
randomizedSegsFromKey[i] = int(v)
}
fileInfo, err := api.contractStore.GetContractFileInfo(args.ContractHash, v.FileHash)
if err != nil {
return fmt.Errorf("failed to get a file of a contract: %w", err)
}
if fileInfo.FileDecryptionStatus == contract.FileDecrypting {
continue
}
api.contractStore.SetFileDecryptionStatus(args.ContractHash, v.FileHash, contract.FileDecrypting)
outputPathOfFile := args.RestoredFilePaths[foundIdx]
inputEncryptedFilePath := filepath.Join(api.dataVerificationProtocol.GetDownloadDirectory(), hexutil.Encode(v.ContractHash), hexutil.EncodeNoPrefix(v.FileHash))
decryptedPath, err := api.dataVerificationProtocol.DecryptFile(inputEncryptedFilePath, outputPathOfFile, encryptionData.KeyIvRandomizedFileSegments[i].Key, encryptionData.KeyIvRandomizedFileSegments[i].Iv, common.EncryptionType(encryptionData.KeyIvRandomizedFileSegments[i].EncryptionType), randomizedSegsFromKey, fileInfo.FileDecryptionStatus == contract.FileDecrypted)
if err != nil {
api.contractStore.SetFileDecryptionStatus(args.ContractHash, v.FileHash, contract.FileDecryptionError)
return fmt.Errorf("failed to decrypt file %s with message: %w", hexutil.EncodeNoPrefix(v.FileHash), err)
}
api.contractStore.SetFileDecryptionStatus(args.ContractHash, v.FileHash, contract.FileDecrypted)
response.DecryptedFilePaths = append(response.DecryptedFilePaths, decryptedPath)
}
return nil
}
// SendContractToFileHosterAndVerifierArgs represents the args.
type SendContractToFileHosterAndVerifierArgs struct {
ContractHash string `json:"contract_hash"`
}
// SendContractToFileHosterAndVerifierResponse represents a response.
type SendContractToFileHosterAndVerifierResponse struct {
Success bool `json:"success"`
}
// SendContractToFileHosterAndVerifier sends the contract to file hoster and verifier.
func (api *DataTransferAPI) SendContractToFileHosterAndVerifier(r *http.Request, args *SendContractToFileHosterAndVerifierArgs, response *SendContractToFileHosterAndVerifierResponse) error {
downloadContract, err := api.contractStore.GetContract(args.ContractHash)
if err != nil {
return fmt.Errorf("contract not found: %w", err)
}
publicKeyVerifier, err := ffgcrypto.PublicKeyFromBytes(downloadContract.VerifierPublicKey)
if err != nil {
return fmt.Errorf("failed to get verifier's public key: %w", err)
}
verifierID, err := peer.IDFromPublicKey(publicKeyVerifier)
if err != nil {
return fmt.Errorf("failed to get verifier's peer id: %w", err)
}
publicKeyHoster, err := ffgcrypto.PublicKeyFromBytes(downloadContract.FileHosterResponse.PublicKey)
if err != nil {
return fmt.Errorf("failed to get file hoster's public key: %w", err)
}
fileHosterID, err := peer.IDFromPublicKey(publicKeyHoster)
if err != nil {
return fmt.Errorf("failed to get file hoster's peer id: %w", err)
}
err = api.dataVerificationProtocol.TransferContract(r.Context(), verifierID, downloadContract)
if err != nil {
return fmt.Errorf("failed to send contract to verifier: %w", err)
}
err = api.dataVerificationProtocol.TransferContract(r.Context(), fileHosterID, downloadContract)
if err != nil {
return fmt.Errorf("failed to send contract to file hoster: %w", err)
}
response.Success = true
return nil
}
// CreateTransactionDataPayloadFromContractHashesArgs represent the function args.
type CreateTransactionDataPayloadFromContractHashesArgs struct {
AccessToken string `json:"access_token"`
ContractHashes []string `json:"contract_hashes"`
CurrentNounce string `json:"current_nounce"`
TransactionFeesToBeUsed string `json:"transaction_fees_to_be_used"`
}
// CreateTransactionDataPayloadFromContractHashesResponse represent the function response.
type CreateTransactionDataPayloadFromContractHashesResponse struct {
TransactionDataBytesHex []string `json:"transaction_data_bytes_hex"`
TotalFeesForTransactions string `json:"total_fees_for_transaction"`
}
// CreateTransactionsWithDataPayloadFromContractHashes given a list of contract hashes it creates the transactions and its data payloads.
func (api *DataTransferAPI) CreateTransactionsWithDataPayloadFromContractHashes(r *http.Request, args *CreateTransactionDataPayloadFromContractHashesArgs, response *CreateTransactionDataPayloadFromContractHashesResponse) error {
ok, key, err := api.keystore.Authorized(args.AccessToken)
if err != nil || !ok {
return fmt.Errorf("failed to authorize access token %v", err)
}
response.TransactionDataBytesHex = make([]string, 0)
currentNounce, err := hexutil.DecodeUint64(args.CurrentNounce)
if err != nil {
return fmt.Errorf("failed to decode current nounce: %w", err)
}
transactionFees, err := hexutil.DecodeBig(args.TransactionFeesToBeUsed)
if err != nil {
return fmt.Errorf("failed to decode transaction fees to be used for transaction: %w", err)
}
allTransactionFess := big.NewInt(0)
for _, v := range args.ContractHashes {
currentNounce++
downloadContract, err := api.contractStore.GetContract(v)
if err != nil {
return fmt.Errorf("failed to get contract: %w", err)
}
dcinTX := &messages.DownloadContractInTransactionDataProto{
ContractHash: downloadContract.ContractHash,
FileRequesterNodePublicKey: downloadContract.FileRequesterNodePublicKey,
FileHosterNodePublicKey: downloadContract.FileHosterResponse.PublicKey,
VerifierPublicKey: downloadContract.VerifierPublicKey,
VerifierFees: downloadContract.VerifierFees,
FileHosterFees: downloadContract.FileHosterResponse.FeesPerByte,
}
contractsEnvelope := &messages.DownloadContractsHashesProto{
Contracts: []*messages.DownloadContractInTransactionDataProto{dcinTX},
}
itemsBytes, err := proto.Marshal(contractsEnvelope)
if err != nil {
return fmt.Errorf("failed to marshal contract envelope: %w", err)
}
txPayload := transaction.DataPayload{
Type: transaction.DataType_DATA_CONTRACT,
Payload: itemsBytes,
}
txPayloadBytes, err := proto.Marshal(&txPayload)
if err != nil {
return fmt.Errorf("failed to marshal data payload with contract envelope inside: %w", err)
}
dataverifierAddr, err := ffgcrypto.RawPublicToAddress(downloadContract.VerifierPublicKey)
if err != nil {
return fmt.Errorf("failed to get the address of data verifier: %w", err)
}
publicKeyOfTxSigner, err := key.Key.PublicKey.Raw()
if err != nil {
return fmt.Errorf("failed get the public key bytes of unlocked address: %w", err)
}
mainChain, _ := hexutil.Decode(transaction.ChainID)
totalFileSize := uint64(0)
for _, v := range downloadContract.FileHashesNeededSizes {
totalFileSize += v