This repository has been archived by the owner on Nov 22, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 3
/
tx.go
1239 lines (1120 loc) · 31.6 KB
/
tx.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 exchange
import (
"bytes"
"context"
"errors"
"fmt"
"path/filepath"
"sort"
"text/tabwriter"
"time"
"github.com/filecoin-project/go-address"
"github.com/filecoin-project/go-state-types/abi"
"github.com/ipfs/go-blockservice"
cid "github.com/ipfs/go-cid"
"github.com/ipfs/go-graphsync/storeutil"
blockstore "github.com/ipfs/go-ipfs-blockstore"
offline "github.com/ipfs/go-ipfs-exchange-offline"
files "github.com/ipfs/go-ipfs-files"
ipldformat "github.com/ipfs/go-ipld-format"
"github.com/ipfs/go-merkledag"
"github.com/ipfs/go-unixfs"
unixfile "github.com/ipfs/go-unixfs/file"
dagpb "github.com/ipld/go-codec-dagpb"
"github.com/ipld/go-ipld-prime"
cidlink "github.com/ipld/go-ipld-prime/linking/cid"
basicnode "github.com/ipld/go-ipld-prime/node/basic"
peer "github.com/libp2p/go-libp2p-core/peer"
mh "github.com/multiformats/go-multihash"
"github.com/myelnet/go-multistore"
"github.com/myelnet/pop/filecoin"
"github.com/myelnet/pop/internal/utils"
"github.com/myelnet/pop/retrieval"
"github.com/myelnet/pop/retrieval/client"
"github.com/myelnet/pop/retrieval/deal"
"github.com/myelnet/pop/selectors"
"github.com/rs/zerolog/log"
)
// DefaultHashFunction used for generating CIDs of imported data
const DefaultHashFunction = uint64(mh.SHA2_256)
// ErrNoStrategy is returned when we try querying content without a read strategy
var ErrNoStrategy = errors.New("no strategy")
// Entry represents a link to an item in the DAG map
type Entry struct {
// Key is string name of the entry
Key string `json:"key"`
// Value is the CID of the represented content
Value cid.Cid `json:"value"`
// Size is the original file size. Not encoded in the DAG
Size int64 `json:"size"`
}
// TxResult returns metadata about the transaction including a potential error if something failed
type TxResult struct {
Err error
Size uint64 // Size is the total amount of bytes exchanged during this transaction
Spent abi.TokenAmount
PayCh address.Address
}
// Tx is an exchange transaction which may contain multiple DAGs to be exchanged with a set of connected peers
type Tx struct {
ctx context.Context
cancelCtx context.CancelFunc
// global blockstore to dump the content to when the work is over
bs blockstore.Blockstore
// MultiStore creates an isolated store for this transaction before it is migrated over to the main store
ms *multistore.MultiStore
// storeID is the ID of the store used to read or write the content of this session
storeID multistore.StoreID
// store is the isolated blockstore and DAG instances for this session
store *multistore.Store
// entries is the cached reference to values used during the session
entries map[string]Entry
// disco is the discovery mechanism for finding content offers
rou *GossipRouting
// retriever manages the state of the transfer once we have a good offer
retriever *retrieval.Client
// deals keeps track of ongoing provider offers to use instead of querying the network
deals *deal.Mgr
// index is the exchange content index
index *Index
// repl is the replication module
repl *Replication
// clientAddr is the address that will be used to make any payment for retrieving the content
clientAddr address.Address
// root is the root cid of the dag we are retrieving during this session
root cid.Cid
// size it the total size of content used in this session
size int64
// chunk size is the chunk size to use when adding files
chunkSize int64
// codec defines what IPLD multicodec to use for assembling the entries
codec uint64
// sel is the selector used to select specific nodes only to retrieve. if not provided we select
// all the nodes by default
sel ipld.Node
// we can also declare the nodes to retrieve using a list of paths
paths []string
// done is the final message telling us we have received all the blocks and all is well. if the error
// is not nil we've run out of options and nothing we can do at this time will get us the content.
done chan TxResult
// errs receives any kind of error status from execution so we can try to fix it.
errs chan deal.Status
// unsubscribes is used to clear any subscriptions to our retrieval events when we have received
// all the content
unsub retrieval.Unsubscribe
// worker executes retrieval over one or more offers
worker OfferWorker
// ongoing
ongoing chan DealRef
// triage is a stream of deals that requires manual confirmation
// if it's nil we don't need confirmation
triage chan DealSelection
// dispatching is a stream of peer confirmations when dispatching updates
dispatching chan PRecord
// committed indicates whether this transaction was committed or not
committed bool
// Err exposes any error reported by the session during use
Err error
// closed keeps track whether the tx was already closed
closed bool
}
// TxOption sets optional fields on a Tx struct
type TxOption func(*Tx)
// WithStrategy starts a new strategy worker to handle incoming discovery results
func WithStrategy(strategy SelectionStrategy) TxOption {
return func(tx *Tx) {
tx.worker = strategy(tx)
tx.worker.Start()
tx.rou.SetReceiver(tx.worker.PushBack)
}
}
// WithRoot assigns a new root to the transaction if we are working with a DAG that wasn't created
// during this transaction
func WithRoot(r cid.Cid) TxOption {
return func(tx *Tx) {
tx.root = r
}
}
// WithSize allows overriding the size manually if we know it ahead of time
func WithSize(size int64) TxOption {
return func(tx *Tx) {
tx.size = size
}
}
// WithTriage allows a transaction to manually prompt for external confirmation before executing an offer
func WithTriage() TxOption {
return func(tx *Tx) {
tx.triage = make(chan DealSelection)
}
}
// WithCodec changes the codec to use for aggregating the entries in a single root
func WithCodec(codec uint64) TxOption {
return func(tx *Tx) {
tx.codec = codec
}
}
// Put a DAG for a given key in the transaction
func (tx *Tx) Put(key string, value cid.Cid, size int64) error {
tx.entries[key] = Entry{
Key: key,
Value: value,
Size: size,
}
return tx.buildRoot()
}
// Status represents our staged values
type Status map[string]Entry
func (s Status) String() string {
buf := bytes.NewBuffer(nil)
// Format everything in a balanced table layout
// we might want to move this with the cli
w := new(tabwriter.Writer)
w.Init(buf, 0, 4, 2, ' ', 0)
var total int64 = 0
for _, e := range s {
fmt.Fprintf(
w,
"%s\t%s\t%s\n",
e.Key,
e.Value,
filecoin.SizeStr(filecoin.NewInt(uint64(e.Size))),
)
total += e.Size
}
if total > 0 {
fmt.Fprintf(w, "Total\t-\t%s\n", filecoin.SizeStr(filecoin.NewInt(uint64(total))))
}
w.Flush()
return buf.String()
}
// Status returns a list of the current entries
func (tx *Tx) Status() (Status, error) {
if tx.Err != nil {
return Status{}, tx.Err
}
return Status(tx.entries), nil
}
// rootProto returns the node prototype to use for assembling entries
func (tx *Tx) rootProto() (ipld.NodePrototype, error) {
var proto ipld.NodePrototype
switch tx.codec {
case 0x70:
proto = dagpb.Type.PBNode
case 0x71:
proto = basicnode.Prototype.Map
default:
return nil, errors.New("codec invalid")
}
return proto, nil
}
// EntrySlice is a slice of entries exposing method for sorting
type EntrySlice []Entry
func (es EntrySlice) Len() int { return len(es) }
func (es EntrySlice) Swap(a, b int) { es[a], es[b] = es[b], es[a] }
func (es EntrySlice) Less(a, b int) bool { return es[a].Key < es[b].Key }
// assemble all the entries into a single dag Node
func (tx *Tx) assembleEntries() (ipld.Node, error) {
proto, err := tx.rootProto()
if err != nil {
return nil, err
}
nb := proto.NewBuilder()
as, err := nb.BeginMap(int64(len(tx.entries)))
if err != nil {
return nil, err
}
// Create an entry for all the links
lks, err := as.AssembleEntry("Links")
if err != nil {
return nil, err
}
// Create a list of entries
lm, err := lks.BeginList(int64(len(tx.entries)))
if err != nil {
return nil, err
}
entries, err := tx.Entries()
if err != nil {
return nil, err
}
for _, v := range entries {
mas, err := lm.AssembleValue().BeginMap(3)
if err != nil {
return nil, err
}
nas, err := mas.AssembleEntry("Name")
if err != nil {
return nil, err
}
if err := nas.AssignString(v.Key); err != nil {
return nil, err
}
has, err := mas.AssembleEntry("Hash")
if err != nil {
return nil, err
}
if err := has.AssignLink(cidlink.Link{Cid: v.Value}); err != nil {
return nil, err
}
sas, err := mas.AssembleEntry("Tsize")
if err != nil {
return nil, err
}
if err := sas.AssignInt(v.Size); err != nil {
return nil, err
}
if err := mas.Finish(); err != nil {
return nil, err
}
}
if err := lm.Finish(); err != nil {
return nil, err
}
// Add folder pb data to stay compatible with unixfs
dt, err := as.AssembleEntry("Data")
if err != nil {
return nil, err
}
if err := dt.AssignBytes(unixfs.FolderPBData()); err != nil {
return nil, err
}
if err := as.Finish(); err != nil {
return nil, err
}
return nb.Build(), nil
}
// updateDAG stores the current contents of the index in an array to yield a single root CID
func (tx *Tx) buildRoot() error {
var size int64
for _, e := range tx.entries {
size += e.Size
}
lsys := tx.store.LinkSystem
lp := cidlink.LinkPrototype{
Prefix: cid.Prefix{
Version: 1,
Codec: tx.codec,
MhType: DefaultHashFunction,
MhLength: -1,
},
}
nd, err := tx.assembleEntries()
if err != nil {
return err
}
lnk, err := lsys.Store(ipld.LinkContext{}, lp, nd)
if err != nil {
return err
}
c := lnk.(cidlink.Link)
tx.root = c.Cid
tx.size = size
return nil
}
// Ref returns the DataRef associated with this transaction
func (tx *Tx) Ref() *DataRef {
var keys [][]byte
if len(tx.entries) > 0 {
for k := range tx.entries {
keys = append(keys, []byte(k))
}
} else {
kl, err := utils.MapLoadableKeys(tx.root, tx.Store().LinkSystem)
if err != nil {
tx.Err = err
} else {
keys = kl.AsBytes()
}
}
return &DataRef{
PayloadCID: tx.root,
PayloadSize: tx.size,
Keys: keys,
}
}
// DispatchOption is a functional option for customizing DispatchOptions
type DispatchOption = func(*DispatchOptions)
// Commit sends the transaction on the exchange
func (tx *Tx) Commit(dopts ...DispatchOption) error {
if tx.Err != nil {
return tx.Err
}
tx.committed = true
opts := DefaultDispatchOptions
// force default to 0
opts.RF = 0
opts.StoreID = tx.storeID
for _, opt := range dopts {
opt(&opts)
}
if opts.RF > 0 {
var err error
tx.dispatching, err = tx.repl.Dispatch(tx.root, uint64(tx.size), opts)
if err != nil {
return err
}
} else {
// Do not block WatchDispatch
tx.dispatching = make(chan PRecord)
close(tx.dispatching)
}
return nil
}
func (tx *Tx) getUnixDAG(k cid.Cid, DAG ipldformat.DAGService) (files.Node, error) {
dn, err := DAG.Get(tx.ctx, k)
if err != nil {
return nil, err
}
return unixfile.NewUnixfsFile(tx.ctx, DAG, dn)
}
// GetFile retrieves a file associated with the given key from the cache
func (tx *Tx) GetFile(k string) (files.Node, error) {
// If the key is in our cached entries we can use the current DAG
if e, ok := tx.entries[k]; ok {
return tx.getUnixDAG(e.Value, tx.store.DAG)
}
// Check the index if we may already have it from a different transaction
if _, err := tx.index.GetRef(tx.root); err == nil {
return tx.loadFileEntry(k, &multistore.Store{
LinkSystem: storeutil.LinkSystemForBlockstore(tx.bs),
DAG: merkledag.NewDAGService(blockservice.New(tx.bs, offline.Exchange(tx.bs))),
})
}
return tx.loadFileEntry(k, tx.store)
}
// IsLocal tells us if this node is storing the content of this transaction or if it needs to retrieve it
func (tx *Tx) IsLocal(key string) bool {
_, exists := tx.entries[key]
if exists {
return true
}
ref, err := tx.index.GetRef(tx.root)
if err != nil {
return false
}
if ref != nil && key == "" {
return true
}
if ref != nil {
has := ref.Has(key)
if has {
return has
}
// If we don't have it, let's warm up the mutistore with the index so we don't pay for it twice
err := utils.MigrateSelectBlocks(tx.bs, tx.store.Bstore, tx.root, selectors.Entries())
if err != nil {
log.Error().Err(err).Msg("warming up index blocks")
}
return false
}
return false
}
// Keys lists the keys for all the entries in the root map of this transaction
func (tx *Tx) Keys() ([]string, error) {
// If this transaction has entries we just return them otherwise
// we're looking at a different transaction
if len(tx.entries) > 0 {
entries := make([]string, len(tx.entries))
i := 0
for k := range tx.entries {
entries[i] = k
i++
}
return entries, nil
}
lsys := storeutil.LinkSystemForBlockstore(tx.bs)
if _, err := tx.index.GetRef(tx.root); err != nil {
// Keys might still be in multistore
lsys = tx.store.LinkSystem
}
keys, err := utils.MapLoadableKeys(
tx.root,
lsys,
)
if err != nil {
return nil, fmt.Errorf("failed to get keys: %w", err)
}
return keys, nil
}
func (tx *Tx) getEntry(key string, lsys ipld.LinkSystem) (en Entry, err error) {
lk := cidlink.Link{Cid: tx.root}
proto, err := tx.rootProto()
if err != nil {
return en, err
}
nd, err := lsys.Load(ipld.LinkContext{}, lk, proto)
if err != nil {
return en, err
}
links, err := nd.LookupByString("Links")
if err != nil {
return en, err
}
it := links.ListIterator()
for !it.Done() {
_, v, err := it.Next()
if err != nil {
return en, err
}
nn, err := v.LookupByString("Name")
if err != nil {
return en, err
}
name, err := nn.AsString()
if err != nil {
return en, err
}
if name != key {
continue
}
ln, err := v.LookupByString("Hash")
if err != nil {
return en, err
}
l, err := ln.AsLink()
if err != nil {
return en, err
}
sn, err := v.LookupByString("Tsize")
if err != nil {
return en, err
}
s, err := sn.AsInt()
if err != nil {
return en, err
}
return Entry{
Key: key,
Value: l.(cidlink.Link).Cid,
Size: int64(s),
}, nil
}
return en, errors.New("entry not found")
}
// RootFor returns the root of a given key
// @TODO: improve scaling and performance for accessing subroots
func (tx *Tx) RootFor(key string) (cid.Cid, error) {
if key == "*" {
return tx.root, nil
}
lsys := storeutil.LinkSystemForBlockstore(tx.bs)
if _, err := tx.index.GetRef(tx.root); err != nil {
// Keys might still be in multistore
lsys = tx.store.LinkSystem
}
entry, err := tx.getEntry(key, lsys)
if err != nil {
return cid.Undef, err
}
return entry.Value, nil
}
// Entries returns all the entries in the root map of this transaction sorted by key
func (tx *Tx) Entries() ([]Entry, error) {
// If this transaction has entries we just return them otherwise
// we're looking at a different transaction
if len(tx.entries) > 0 {
entries := make([]Entry, len(tx.entries))
i := 0
for _, v := range tx.entries {
entries[i] = v
i++
}
sort.Stable(EntrySlice(entries))
return entries, nil
}
lsys := storeutil.LinkSystemForBlockstore(tx.bs)
if _, err := tx.index.GetRef(tx.root); err != nil {
// Keys might still be in multistore
lsys = tx.store.LinkSystem
}
lk := cidlink.Link{Cid: tx.root}
proto, err := tx.rootProto()
if err != nil {
return nil, err
}
// Use a loader from the link to read all the children blocks from the global store
nd, err := lsys.Load(ipld.LinkContext{}, lk, proto)
if err != nil {
return nil, err
}
links, err := nd.LookupByString("Links")
if err != nil {
return nil, err
}
// Gather the keys in an array
entries := make([]Entry, links.Length())
it := links.ListIterator()
i := 0
// Iterate over all the map entries
for !it.Done() {
_, v, err := it.Next()
// all succeed or fail
if err != nil {
return nil, err
}
nn, err := v.LookupByString("Name")
if err != nil {
return nil, err
}
key, err := nn.AsString()
if err != nil {
return nil, err
}
// An entry with no value should fail
vn, err := v.LookupByString("Hash")
if err != nil {
return nil, err
}
l, err := vn.AsLink()
if err != nil {
return nil, err
}
entries[i] = Entry{
Key: key,
Value: l.(cidlink.Link).Cid,
}
i++
// An entry with no size is still fine
sn, err := v.LookupByString("Tsize")
if err != nil {
log.Debug().Str("key", key).Msg("no size present in entry")
continue
}
size, err := sn.AsInt()
if err != nil {
continue
}
entries[i-1].Size = int64(size)
}
return entries, nil
}
func (tx *Tx) loadFileEntry(k string, store *multistore.Store) (files.Node, error) {
entry, err := tx.getEntry(k, store.LinkSystem)
if err != nil {
return nil, err
}
return tx.getUnixDAG(entry.Value, store.DAG)
}
// WatchDispatch registers a function to be called every time
// the content is received by a peer
func (tx *Tx) WatchDispatch(fn func(r PRecord)) {
for rec := range tx.dispatching {
fn(rec)
}
}
// Root returns the current root CID of the transaction
func (tx *Tx) Root() cid.Cid {
return tx.root
}
// Size returns the current size of content cached by the transaction
func (tx *Tx) Size() int64 {
return tx.size
}
// Store exposes the underlying store
func (tx *Tx) Store() *multistore.Store {
return tx.store
}
// StoreID exposes the ID of the underlying store
func (tx *Tx) StoreID() multistore.StoreID {
return tx.storeID
}
// DealRef is the reference to an ongoing deal
type DealRef struct {
ID deal.ID
Offer deal.Offer
}
// DealExecParams are params to apply when executing a selected deal
// Can be used to assign different parameters than the defaults in the offer
// while respecting the offer conditions otherwise it will fail
type DealExecParams struct {
Accepted bool
Selector ipld.Node
TotalFunds abi.TokenAmount
}
// DealParam is a functional paramter to set a value on DealExecParams
type DealParam func(*DealExecParams)
// DealSel sets a Deal Selector parameter when executing an offer
func DealSel(sel ipld.Node) DealParam {
return func(params *DealExecParams) {
params.Selector = sel
}
}
// DealFunds sets a total amount to load in payment channel when executing an offer
func DealFunds(amount abi.TokenAmount) DealParam {
return func(params *DealExecParams) {
params.TotalFunds = amount
}
}
// DealSelection sends the selected offer with a channel to expect confirmation on
type DealSelection struct {
Offer deal.Offer
confirm chan DealExecParams
}
// Exec accepts execution for an offer
func (ds DealSelection) Exec(pms ...DealParam) {
params := DealExecParams{
Accepted: true,
TotalFunds: ds.Offer.RetrievalPrice(),
}
for _, p := range pms {
p(¶ms)
}
ds.confirm <- params
}
// Next declines an offer and moves on to the next one if available
func (ds DealSelection) Next() {
ds.confirm <- DealExecParams{
Accepted: false,
}
}
// Query the discovery service for offers
func (tx *Tx) Query(paths ...string) error {
if tx.worker == nil {
return ErrNoStrategy
}
// For now we assume providers must have all the blocks from a given root
// to send a valid offer. When selectors improve we may be able to query for partial offers.
tx.sel = selectors.All()
tx.AppendPaths(paths...)
offer, err := tx.deals.FindOfferByCid(tx.root)
if err == nil {
info, err := offer.AddrInfo()
if err == nil {
newoffer, err := tx.QueryOffer(*info, tx.sel)
if err == nil {
tx.ApplyOffer(newoffer)
return nil
}
}
}
return tx.rou.Query(tx.ctx, tx.root, selectors.All())
}
// AppendPaths used to combine multiple queries
func (tx *Tx) AppendPaths(paths ...string) {
// clean paths
for _, p := range paths {
if p == "" {
continue
}
tx.paths = append(tx.paths, p)
}
}
// QueryOffer allows querying directly from a given peer
func (tx *Tx) QueryOffer(info peer.AddrInfo, sel ipld.Node) (deal.Offer, error) {
tx.sel = sel
return tx.rou.QueryProvider(info, tx.root, sel)
}
// ApplyOffer allows executing a transaction based on an existing offer without querying the routing service
// By the default the offer is added at the front of the queue. If there is already an offer in progress it will
// thus execute after it or if not will execute immediately.
func (tx *Tx) ApplyOffer(offer deal.Offer) {
tx.worker.PushFront(offer)
}
// Execute starts a retrieval operation for a given offer and returns the deal ID for that operation
func (tx *Tx) Execute(of deal.Offer, p DealExecParams) TxResult {
info, err := of.AddrInfo()
if err != nil {
return TxResult{
Err: err,
}
}
// Make sure our provider is in our peerstore
tx.rou.AddAddrs(info.ID, info.Addrs)
// number of transfers is 1 by default
transferCount := 1
var root cid.Cid
if len(tx.paths) > 0 && tx.paths[0] != "*" {
// number of transfers based on path + initial index if needed
transferCount = len(tx.paths)
// check if we can already get the root of the first path
root, err = tx.RootFor(tx.paths[0])
if err != nil {
// we need to retrieve the entries first
transferCount++
}
}
results := make(chan TxResult, transferCount)
tx.unsub = tx.retriever.SubscribeToEvents(func(event client.Event, state deal.ClientState) {
switch state.Status {
case deal.StatusCompleted:
payCh := address.Undef
if state.PaymentInfo != nil {
payCh = state.PaymentInfo.PayCh
}
select {
case results <- TxResult{
Size: state.TotalReceived,
Spent: state.FundsSpent,
PayCh: payCh,
}:
default:
}
case deal.StatusCancelled, deal.StatusErrored:
select {
case results <- TxResult{
Err: errors.New(deal.Statuses[state.Status]),
}:
default:
}
return
}
})
final := TxResult{
Spent: abi.NewTokenAmount(0),
}
for i := 0; i < transferCount; i++ {
funds := tx.deals.GetFundsForCid(tx.root)
sel := selectors.All()
if root == cid.Undef {
root = tx.root
if len(tx.paths) == 0 || tx.paths[i] != "*" {
// if we will be fetching some paths we need to retrieve the entries first
sel = selectors.Entries()
}
// set the funds as for the total size of the DAG
funds = of.RetrievalPrice()
}
// we've fetched the entries already or the root from the first path,
// switch the root to the next path
if i > 0 {
root, err = tx.RootFor(tx.paths[i-1])
if err != nil {
return TxResult{
Err: err,
}
}
}
params, err := deal.NewParams(
of.MinPricePerByte,
of.MaxPaymentInterval,
of.MaxPaymentIntervalIncrease,
sel,
nil,
of.UnsealPrice,
)
if err != nil {
return TxResult{
Err: err,
}
}
id, err := tx.retriever.Retrieve(
tx.ctx,
root,
params,
funds,
info.ID,
tx.clientAddr,
of.PaymentAddress,
&tx.storeID,
)
if err != nil {
final.Err = err
return final
}
tx.ongoing <- DealRef{
ID: id,
Offer: of,
}
select {
case res := <-results:
if res.Err != nil {
final.Err = res.Err
return final
}
if root.Equals(tx.root) {
err := tx.deals.SetOfferForCid(root, of)
if err != nil {
log.Error().Err(err).Msg("failed to set offer")
}
}
// For now we just return the error and assume the transfer is failed
// we do have access to the status in order to try and restart the deal or something else
final.Size += res.Size
final.Spent = filecoin.BigAdd(final.Spent, res.Spent)
final.PayCh = res.PayCh
remaining := filecoin.BigSub(funds, res.Spent)
tx.deals.SetFundsForCid(tx.root, remaining)
continue
case <-tx.ctx.Done():
final.Err = tx.ctx.Err()
return final
}
}
tx.committed = true
return final
}
// Confirm takes an offer and blocks to wait for user confirmation before returning true or false
func (tx *Tx) Confirm(of deal.Offer) DealExecParams {
if tx.triage != nil {
dch := make(chan DealExecParams, 1)
tx.triage <- DealSelection{
Offer: of,
confirm: dch,
}
select {
case d := <-dch:
return d
case <-tx.ctx.Done():
return DealExecParams{
Accepted: false,
}
}
}
return DealExecParams{
Accepted: true,
Selector: tx.sel,
TotalFunds: of.RetrievalPrice(),
}
}
// Triage allows manually triaging the next selection
func (tx *Tx) Triage() (DealSelection, error) {
select {
case dc := <-tx.triage:
return dc, nil
case <-tx.ctx.Done():
return DealSelection{}, tx.ctx.Err()
}
}
// Finish tells the tx all operations have been completed
func (tx *Tx) Finish(res TxResult) {
tx.done <- res
}
// Done returns a channel that receives any resulting error from the latest operation
func (tx *Tx) Done() <-chan TxResult {
return tx.done
}
// Ongoing exposes the ongoing channel to get the reference of any in progress deals
func (tx *Tx) Ongoing() <-chan DealRef {
return tx.ongoing
}
// Close removes any listeners and stream handlers related to a session
// If the transaction was not committed, any staged content will be deleted
func (tx *Tx) Close() error {
if tx.closed {
return tx.Err
}
tx.closed = true
if tx.worker != nil {
_ = tx.worker.Close()
}
if tx.unsub != nil {
tx.unsub()
}
err := tx.dumpStore()
if err != nil {