-
Notifications
You must be signed in to change notification settings - Fork 22
/
filclient.go
2209 lines (1856 loc) · 65.7 KB
/
filclient.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 filclient
import (
"context"
"encoding/json"
"errors"
"fmt"
"os"
"path/filepath"
"strings"
"sync"
"time"
"github.com/application-research/filclient/rep"
boostcar "github.com/filecoin-project/boost/car"
smtypes "github.com/filecoin-project/boost/storagemarket/types"
"github.com/filecoin-project/boost/storagemarket/types/dealcheckpoints"
"github.com/filecoin-project/boost/transport/httptransport"
boosttypes "github.com/filecoin-project/boost/transport/types"
"github.com/filecoin-project/go-address"
cborutil "github.com/filecoin-project/go-cbor-util"
"github.com/filecoin-project/go-commp-utils/writer"
datatransfer "github.com/filecoin-project/go-data-transfer"
"github.com/filecoin-project/go-data-transfer/channelmonitor"
dtimpl "github.com/filecoin-project/go-data-transfer/impl"
dtnet "github.com/filecoin-project/go-data-transfer/network"
gst "github.com/filecoin-project/go-data-transfer/transport/graphsync"
commcid "github.com/filecoin-project/go-fil-commcid"
commp "github.com/filecoin-project/go-fil-commp-hashhash"
"github.com/filecoin-project/go-fil-markets/retrievalmarket"
"github.com/filecoin-project/go-fil-markets/shared"
"github.com/filecoin-project/go-fil-markets/storagemarket"
"github.com/filecoin-project/go-fil-markets/storagemarket/impl/clientutils"
"github.com/filecoin-project/go-fil-markets/storagemarket/impl/requestvalidation"
"github.com/filecoin-project/go-fil-markets/storagemarket/network"
"github.com/filecoin-project/go-state-types/abi"
"github.com/filecoin-project/go-state-types/big"
"github.com/filecoin-project/go-state-types/builtin"
"github.com/filecoin-project/go-state-types/builtin/v8/paych"
"github.com/filecoin-project/go-state-types/builtin/v9/market"
"github.com/filecoin-project/go-state-types/crypto"
"github.com/filecoin-project/lotus/api"
rpcstmgr "github.com/filecoin-project/lotus/chain/stmgr/rpc"
"github.com/filecoin-project/lotus/chain/types"
"github.com/filecoin-project/lotus/chain/wallet"
"github.com/filecoin-project/lotus/paychmgr"
"github.com/google/uuid"
"github.com/ipfs/go-cid"
"github.com/ipfs/go-datastore"
"github.com/ipfs/go-datastore/namespace"
"github.com/ipfs/go-graphsync"
gsimpl "github.com/ipfs/go-graphsync/impl"
gsnet "github.com/ipfs/go-graphsync/network"
"github.com/ipfs/go-graphsync/peerstate"
"github.com/ipfs/go-graphsync/storeutil"
blockstore "github.com/ipfs/go-ipfs-blockstore"
logging "github.com/ipfs/go-log/v2"
"github.com/ipld/go-car"
"github.com/libp2p/go-libp2p/core/host"
inet "github.com/libp2p/go-libp2p/core/network"
"github.com/libp2p/go-libp2p/core/peer"
"github.com/libp2p/go-libp2p/core/protocol"
"github.com/multiformats/go-multiaddr"
"go.opentelemetry.io/otel"
"go.opentelemetry.io/otel/attribute"
"go.opentelemetry.io/otel/trace"
)
var Tracer = otel.Tracer("filclient")
var log = logging.Logger("filclient")
var retrievalLogger = logging.Logger("filclient-retrieval")
const DealProtocolv110 = "/fil/storage/mk/1.1.0"
const DealProtocolv120 = "/fil/storage/mk/1.2.0"
const QueryAskProtocol = "/fil/storage/ask/1.1.0"
const DealStatusProtocolv110 = "/fil/storage/status/1.1.0"
const DealStatusProtocolv120 = "/fil/storage/status/1.2.0"
const RetrievalQueryProtocol = "/fil/retrieval/qry/1.0.0"
const maxTraversalLinks = 32 * (1 << 20)
type FilClient struct {
mpusher *MsgPusher
pchmgr *paychmgr.Manager
host host.Host
api api.Gateway
wallet *wallet.LocalWallet
ClientAddr address.Address
blockstore blockstore.Blockstore
dataTransfer datatransfer.Manager
computePieceComm GetPieceCommFunc
graphSync *gsimpl.GraphSync
transport *gst.Transport
logRetrievalProgressEvents bool
Libp2pTransferMgr *libp2pTransferManager
retrievalEventPublisher *rep.RetrievalEventPublisher
}
type GetPieceCommFunc func(ctx context.Context, payloadCid cid.Cid, bstore blockstore.Blockstore) (cid.Cid, uint64, abi.UnpaddedPieceSize, error)
type Lp2pDTConfig struct {
Server httptransport.ServerConfig
TransferTimeout time.Duration
}
type Config struct {
DataDir string
GraphsyncOpts []gsimpl.Option
Api api.Gateway
Wallet *wallet.LocalWallet
Addr address.Address
Blockstore blockstore.Blockstore
Datastore datastore.Batching
Host host.Host
ChannelMonitorConfig channelmonitor.Config
RetrievalConfigurer datatransfer.TransportConfigurer
LogRetrievalProgressEvents bool
Lp2pDTConfig Lp2pDTConfig
}
func NewClient(h host.Host, api api.Gateway, w *wallet.LocalWallet, addr address.Address, bs blockstore.Blockstore, ds datastore.Batching, ddir string, opts ...func(*Config)) (*FilClient, error) {
cfg := &Config{
Host: h,
Api: api,
Wallet: w,
Addr: addr,
Blockstore: bs,
Datastore: ds,
DataDir: ddir,
GraphsyncOpts: []gsimpl.Option{
gsimpl.MaxInProgressIncomingRequests(200),
gsimpl.MaxInProgressOutgoingRequests(200),
gsimpl.MaxMemoryResponder(8 << 30),
gsimpl.MaxMemoryPerPeerResponder(32 << 20),
gsimpl.MaxInProgressIncomingRequestsPerPeer(20),
gsimpl.MessageSendRetries(2),
gsimpl.SendMessageTimeout(2 * time.Minute),
gsimpl.MaxLinksPerIncomingRequests(maxTraversalLinks),
gsimpl.MaxLinksPerOutgoingRequests(maxTraversalLinks),
},
ChannelMonitorConfig: channelmonitor.Config{
AcceptTimeout: time.Hour * 24,
RestartDebounce: time.Second * 10,
RestartBackoff: time.Second * 20,
MaxConsecutiveRestarts: 15,
//RestartAckTimeout: time.Second * 30,
CompleteTimeout: time.Minute * 40,
// Called when a restart completes successfully
//OnRestartComplete func(id datatransfer.ChannelID)
},
Lp2pDTConfig: Lp2pDTConfig{
Server: httptransport.ServerConfig{
// Keep the cache around for one minute after a request
// finishes in case the connection bounced in the middle
// of a transfer, or there is a request for the same payload
// soon after
BlockInfoCacheManager: boostcar.NewDelayedUnrefBICM(time.Minute),
ThrottleLimit: uint(100),
},
// Wait up to 24 hours for the transfer to complete (including
// after a connection bounce) before erroring out the deal
TransferTimeout: 24 * time.Hour,
},
}
for _, opt := range opts {
opt(cfg)
}
return NewClientWithConfig(cfg)
}
func NewClientWithConfig(cfg *Config) (*FilClient, error) {
ctx, shutdown := context.WithCancel(context.Background())
mpusher := NewMsgPusher(cfg.Api, cfg.Wallet)
smapi := rpcstmgr.NewRPCStateManager(cfg.Api)
pchds := namespace.Wrap(cfg.Datastore, datastore.NewKey("paych"))
store := paychmgr.NewStore(pchds)
papi := &paychApiProvider{
Gateway: cfg.Api,
wallet: cfg.Wallet,
mp: mpusher,
}
pchmgr := paychmgr.NewManager(ctx, shutdown, smapi, store, papi)
if err := pchmgr.Start(); err != nil {
return nil, err
}
gse := gsimpl.New(context.Background(),
gsnet.NewFromLibp2pHost(cfg.Host),
storeutil.LinkSystemForBlockstore(cfg.Blockstore),
cfg.GraphsyncOpts...,
).(*gsimpl.GraphSync)
dtn := dtnet.NewFromLibp2pHost(cfg.Host)
tpt := gst.NewTransport(cfg.Host.ID(), gse)
dtRestartConfig := dtimpl.ChannelRestartConfig(cfg.ChannelMonitorConfig)
cidlistsdirPath := filepath.Join(cfg.DataDir, "cidlistsdir")
if err := os.MkdirAll(cidlistsdirPath, 0755); err != nil {
return nil, fmt.Errorf("failed to initialize cidlistsdir: %w", err)
}
mgr, err := dtimpl.NewDataTransfer(cfg.Datastore, dtn, tpt, dtRestartConfig)
if err != nil {
return nil, err
}
err = mgr.RegisterVoucherType(&requestvalidation.StorageDataTransferVoucher{}, nil)
if err != nil {
return nil, err
}
err = mgr.RegisterVoucherType(&retrievalmarket.DealProposal{}, nil)
if err != nil {
return nil, err
}
err = mgr.RegisterVoucherType(&retrievalmarket.DealPayment{}, nil)
if err != nil {
return nil, err
}
err = mgr.RegisterVoucherResultType(&retrievalmarket.DealResponse{})
if err != nil {
return nil, err
}
if cfg.RetrievalConfigurer != nil {
if err := mgr.RegisterTransportConfigurer(&retrievalmarket.DealProposal{}, cfg.RetrievalConfigurer); err != nil {
return nil, err
}
}
if err := mgr.Start(ctx); err != nil {
return nil, err
}
/*
mgr.SubscribeToEvents(func(event datatransfer.Event, channelState datatransfer.ChannelState) {
fmt.Printf("[%s] event: %s %d %s %s\n", time.Now().Format("15:04:05"), event.Message, event.Code, datatransfer.Events[event.Code], event.Timestamp.Format("15:04:05"))
fmt.Printf("channelstate: %s %s\n", datatransfer.Statuses[channelState.Status()], channelState.Message())
})
*/
// Create a server for libp2p data transfers
lp2pds := namespace.Wrap(cfg.Datastore, datastore.NewKey("/libp2p-dt"))
authDB := httptransport.NewAuthTokenDB(lp2pds)
dtServer := httptransport.NewLibp2pCarServer(cfg.Host, authDB, cfg.Blockstore, cfg.Lp2pDTConfig.Server)
// Create a manager to watch for libp2p data transfer events
lp2pXferOpts := libp2pTransferManagerOpts{
xferTimeout: cfg.Lp2pDTConfig.TransferTimeout,
authCheckPeriod: time.Minute,
}
libp2pTransferMgr := newLibp2pTransferManager(dtServer, lp2pds, authDB, lp2pXferOpts)
if err := libp2pTransferMgr.Start(ctx); err != nil {
return nil, err
}
// Create a retrieval event publisher
retrievalEventPublisher := rep.New(ctx)
fc := &FilClient{
host: cfg.Host,
api: cfg.Api,
wallet: cfg.Wallet,
ClientAddr: cfg.Addr,
blockstore: cfg.Blockstore,
dataTransfer: mgr,
pchmgr: pchmgr,
mpusher: mpusher,
computePieceComm: GeneratePieceCommitment,
graphSync: gse,
transport: tpt,
logRetrievalProgressEvents: cfg.LogRetrievalProgressEvents,
Libp2pTransferMgr: libp2pTransferMgr,
retrievalEventPublisher: retrievalEventPublisher,
}
// Subscribe this FilClient instance to retrieval events
retrievalEventPublisher.Subscribe(fc)
return fc, nil
}
func (fc *FilClient) GetDtMgr() datatransfer.Manager {
return fc.dataTransfer
}
func (fc *FilClient) SetPieceCommFunc(pcf GetPieceCommFunc) {
fc.computePieceComm = pcf
}
func (fc *FilClient) DealProtocolForMiner(ctx context.Context, miner address.Address) (protocol.ID, error) {
// Connect to the miner. If there's not already a connection to the miner,
// libp2p will open a connection and exchange protocol IDs.
mpid, err := fc.ConnectToMiner(ctx, miner)
if err != nil {
return "", fmt.Errorf("connecting to %s: %w", miner, err)
}
// Get the supported deal protocols for the miner's peer
proto, err := fc.host.Peerstore().FirstSupportedProtocol(mpid, DealProtocolv120, DealProtocolv110)
if err != nil {
return "", fmt.Errorf("getting deal protocol for %s: %w", miner, err)
}
if proto == "" {
return "", fmt.Errorf("%s does not support any deal making protocol", miner)
}
return protocol.ID(proto), nil
}
func (fc *FilClient) streamToMiner(ctx context.Context, maddr address.Address, protocol ...protocol.ID) (inet.Stream, error) {
ctx, span := Tracer.Start(ctx, "streamToMiner", trace.WithAttributes(
attribute.Stringer("miner", maddr),
))
defer span.End()
mpid, err := fc.ConnectToMiner(ctx, maddr)
if err != nil {
return nil, err
}
s, err := fc.host.NewStream(ctx, mpid, protocol...)
if err != nil {
return nil, fmt.Errorf("failed to open stream to peer: %w", err)
}
return s, nil
}
// Errors - ErrMinerConnectionFailed, ErrLotusError
func (fc *FilClient) ConnectToMiner(ctx context.Context, maddr address.Address) (peer.ID, error) {
addrInfo, err := fc.minerAddrInfo(ctx, maddr)
if err != nil {
return "", err
}
if err := fc.host.Connect(ctx, *addrInfo); err != nil {
return "", NewErrMinerConnectionFailed(err)
}
return addrInfo.ID, nil
}
func (fc *FilClient) minerAddrInfo(ctx context.Context, maddr address.Address) (*peer.AddrInfo, error) {
minfo, err := fc.api.StateMinerInfo(ctx, maddr, types.EmptyTSK)
if err != nil {
return nil, NewErrLotusError(err)
}
if minfo.PeerId == nil {
return nil, NewErrMinerConnectionFailed(fmt.Errorf("miner %s has no peer ID set", maddr))
}
var maddrs []multiaddr.Multiaddr
for _, mma := range minfo.Multiaddrs {
ma, err := multiaddr.NewMultiaddrBytes(mma)
if err != nil {
return nil, NewErrMinerConnectionFailed(fmt.Errorf("miner %s had invalid multiaddrs in their info: %w", maddr, err))
}
maddrs = append(maddrs, ma)
}
// FIXME - lotus-client-proper falls back on the DHT when it has a peerid but no multiaddr
// filc should do the same
if len(maddrs) == 0 {
return nil, NewErrMinerConnectionFailed(fmt.Errorf("miner %s has no multiaddrs set on chain", maddr))
}
if err := fc.host.Connect(ctx, peer.AddrInfo{
ID: *minfo.PeerId,
Addrs: maddrs,
}); err != nil {
return nil, NewErrMinerConnectionFailed(err)
}
return &peer.AddrInfo{
ID: *minfo.PeerId,
Addrs: maddrs,
}, nil
}
func (fc *FilClient) openStreamToPeer(ctx context.Context, addr peer.AddrInfo, protocol protocol.ID) (inet.Stream, error) {
ctx, span := Tracer.Start(ctx, "openStreamToPeer", trace.WithAttributes(
attribute.Stringer("peerID", addr.ID),
))
defer span.End()
err := fc.connectToPeer(ctx, addr)
if err != nil {
return nil, err
}
s, err := fc.host.NewStream(ctx, addr.ID, protocol)
if err != nil {
return nil, fmt.Errorf("failed to open stream to peer: %w", err)
}
return s, nil
}
// Errors - ErrMinerConnectionFailed, ErrLotusError
func (fc *FilClient) connectToPeer(ctx context.Context, addr peer.AddrInfo) error {
if err := fc.host.Connect(ctx, addr); err != nil {
return NewErrMinerConnectionFailed(err)
}
return nil
}
func (fc *FilClient) GetMinerVersion(ctx context.Context, maddr address.Address) (string, error) {
pid, err := fc.ConnectToMiner(ctx, maddr)
if err != nil {
return "", err
}
agent, err := fc.host.Peerstore().Get(pid, "AgentVersion")
if err != nil {
return "", nil
}
return agent.(string), nil
}
func (fc *FilClient) GetAsk(ctx context.Context, maddr address.Address) (*network.AskResponse, error) {
ctx, span := Tracer.Start(ctx, "doGetAsk", trace.WithAttributes(
attribute.Stringer("miner", maddr),
))
defer span.End()
s, err := fc.streamToMiner(ctx, maddr, QueryAskProtocol)
if err != nil {
return nil, err
}
fc.host.ConnManager().Protect(s.Conn().RemotePeer(), "GetAsk")
defer func() {
fc.host.ConnManager().Unprotect(s.Conn().RemotePeer(), "GetAsk")
s.Close()
}()
areq := &network.AskRequest{Miner: maddr}
var resp network.AskResponse
// Sending the query ask and reading the response
if err := doRpc(ctx, s, areq, &resp); err != nil {
return nil, fmt.Errorf("get ask rpc: %w", err)
}
return &resp, nil
}
func doRpc(ctx context.Context, s inet.Stream, req interface{}, resp interface{}) error {
dline, ok := ctx.Deadline()
if ok {
s.SetDeadline(dline)
defer s.SetDeadline(time.Time{})
}
if err := cborutil.WriteCborRPC(s, req); err != nil {
return fmt.Errorf("failed to send request: %w", err)
}
if err := cborutil.ReadCborRPC(s, resp); err != nil {
return fmt.Errorf("failed to read response: %w", err)
}
return nil
}
const epochsPerHour = 60 * 2
func ComputePrice(askPrice types.BigInt, size abi.PaddedPieceSize, duration abi.ChainEpoch) (*abi.TokenAmount, error) {
cost := big.Mul(big.Div(big.Mul(big.NewInt(int64(size)), askPrice), big.NewInt(1<<30)), big.NewInt(int64(duration)))
return (*abi.TokenAmount)(&cost), nil
}
type DealPieceInfo struct {
// Piece CID
Cid cid.Cid
// Piece size
Size abi.PaddedPieceSize
// Payload size
PayloadSize uint64
}
type DealConfig struct {
Verified bool
FastRetrieval bool
MinSize abi.PaddedPieceSize
PieceInfo DealPieceInfo
StartEpoch abi.ChainEpoch
EndEpoch abi.ChainEpoch
PricePerEpoch abi.TokenAmount
Signer DealSigner // May be nil!
Label market.DealLabel
TransferType string
}
func DefaultDealConfig() DealConfig {
return DealConfig{
Verified: false,
FastRetrieval: false,
MinSize: 0,
PieceInfo: DealPieceInfo{},
TransferType: storagemarket.TTGraphsync,
}
}
type DealOption func(*DealConfig)
// Whether to use verified FIL.
func DealWithVerified(verified bool) DealOption {
return func(cfg *DealConfig) {
cfg.Verified = verified
}
}
// Whether to request for the provider to keep an unsealed copy.
func DealWithFastRetrieval(fastRetrieval bool) DealOption {
return func(cfg *DealConfig) {
cfg.FastRetrieval = fastRetrieval
}
}
// If the computed piece size is smaller than minSize, minSize will be used
// instead.
func DealWithMinSize(minSize abi.PaddedPieceSize) DealOption {
return func(cfg *DealConfig) {
cfg.MinSize = minSize
}
}
// This can be used to pass a precomputed piece cid and size. If it's not
// passed, the piece commitment will be automatically calculated.
func DealWithPieceInfo(pieceInfo DealPieceInfo) DealOption {
return func(cfg *DealConfig) {
cfg.PieceInfo = pieceInfo
}
}
func DealWithStartEpoch(startEpoch abi.ChainEpoch) DealOption {
return func(cfg *DealConfig) {
cfg.StartEpoch = startEpoch
}
}
func DealWithEndEpoch(endEpoch abi.ChainEpoch) DealOption {
return func(cfg *DealConfig) {
cfg.EndEpoch = endEpoch
}
}
func DealWithPricePerEpoch(pricePerEpoch abi.TokenAmount) DealOption {
return func(cfg *DealConfig) {
cfg.PricePerEpoch = pricePerEpoch
}
}
type DealSigner func(ctx context.Context, raw []byte) (*crypto.Signature, error)
func DealWithSigner(signer DealSigner) DealOption {
return func(cfg *DealConfig) {
cfg.Signer = signer
}
}
func DealWithLabel(label market.DealLabel) DealOption {
return func(cfg *DealConfig) {
cfg.Label = label
}
}
func DealWithTransferType(transferType string) DealOption {
return func(cfg *DealConfig) {
cfg.TransferType = transferType
}
}
func DealWithConfig(newCfg DealConfig) DealOption {
return func(cfg *DealConfig) {
*cfg = newCfg
}
}
func (fc *FilClient) MakeDealUnsigned(
ctx context.Context,
sp address.Address,
payload cid.Cid,
price types.BigInt,
duration abi.ChainEpoch,
options ...DealOption,
) (*market.DealProposal, []byte, error) {
ctx, span := Tracer.Start(ctx, "makeDeal", trace.WithAttributes(
attribute.Stringer("sp", sp),
attribute.Stringer("price", price),
attribute.Int64("duration", int64(duration)),
attribute.Stringer("cid", payload),
))
defer span.End()
cfg := DefaultDealConfig()
for _, option := range options {
option(&cfg)
}
// If no piece CID was provided, calculate it now
if cfg.PieceInfo.Cid == cid.Undef {
pieceCid, payloadSize, unpaddedPieceSize, err := fc.computePieceComm(ctx, payload, fc.blockstore)
if err != nil {
return nil, nil, err
}
cfg.PieceInfo = DealPieceInfo{
Cid: pieceCid,
Size: unpaddedPieceSize.Padded(),
PayloadSize: payloadSize,
}
}
if cfg.PieceInfo.Size < cfg.MinSize {
paddedPieceCid, err := ZeroPadPieceCommitment(cfg.PieceInfo.Cid, cfg.PieceInfo.Size.Unpadded(), cfg.MinSize.Unpadded())
if err != nil {
return nil, nil, err
}
cfg.PieceInfo.Cid = paddedPieceCid
cfg.PieceInfo.Size = cfg.MinSize
}
// After this point, cfg.pieceInfo can be considered VALID
head, err := fc.api.ChainHead(ctx)
if err != nil {
return nil, nil, err
}
collBounds, err := fc.api.StateDealProviderCollateralBounds(ctx, cfg.PieceInfo.Size, cfg.Verified, types.EmptyTSK)
if err != nil {
return nil, nil, err
}
// set provider collateral 10% above minimum to avoid fluctuations causing deal failure
provCol := big.Div(big.Mul(collBounds.Min, big.NewInt(11)), big.NewInt(10))
if cfg.StartEpoch == 0 {
// give miners a week to seal and commit the sector
cfg.StartEpoch = head.Height() + (epochsPerHour * 24 * 7)
}
if cfg.EndEpoch == 0 {
cfg.EndEpoch = cfg.StartEpoch + duration
}
if cfg.PricePerEpoch.Nil() {
cfg.PricePerEpoch = big.Div(big.Mul(big.NewInt(int64(cfg.PieceInfo.Size)), price), big.NewInt(1<<30))
}
if cfg.Label.Equals(market.EmptyDealLabel) {
label, err := clientutils.LabelField(payload)
if err != nil {
return nil, nil, fmt.Errorf("failed to construct label field: %v", err)
}
cfg.Label = label
}
proposal := &market.DealProposal{
PieceCID: cfg.PieceInfo.Cid,
PieceSize: cfg.PieceInfo.Size,
VerifiedDeal: cfg.Verified,
Client: fc.ClientAddr,
Provider: sp,
Label: cfg.Label,
StartEpoch: cfg.StartEpoch,
EndEpoch: cfg.EndEpoch,
StoragePricePerEpoch: cfg.PricePerEpoch,
ProviderCollateral: provCol,
ClientCollateral: big.Zero(),
}
raw, err := cborutil.Dump(proposal)
if err != nil {
return nil, nil, err
}
return proposal, raw, err
}
func (fc *FilClient) MakeDealWithOptions(
ctx context.Context,
sp address.Address,
payload cid.Cid,
price types.BigInt,
duration abi.ChainEpoch,
options ...DealOption,
) (*network.Proposal, error) {
cfg := DefaultDealConfig()
for _, option := range options {
option(&cfg)
}
proposal, raw, err := fc.MakeDealUnsigned(ctx, sp, payload, price, duration, DealWithConfig(cfg))
if err != nil {
return nil, err
}
// Sign using the custom signer if provided in the options, or if not
// provided, use client's wallet to make the signature
var sig *crypto.Signature
if cfg.Signer != nil {
_sig, err := cfg.Signer(ctx, raw)
if err != nil {
return nil, err
}
sig = _sig
} else {
_sig, err := fc.wallet.WalletSign(ctx, fc.ClientAddr, raw, api.MsgMeta{Type: api.MTDealProposal})
if err != nil {
return nil, err
}
sig = _sig
}
sigprop := &market.ClientDealProposal{
Proposal: *proposal,
ClientSignature: *sig,
}
return &network.Proposal{
DealProposal: sigprop,
Piece: &storagemarket.DataRef{
TransferType: cfg.TransferType,
Root: payload,
RawBlockSize: cfg.PieceInfo.PayloadSize,
},
FastRetrieval: cfg.FastRetrieval,
}, nil
}
// Deprecated: MakeDeal will be removed and MakeDealWithOptions will be renamed
// to MakeDeal.
func (fc *FilClient) MakeDeal(
ctx context.Context,
miner address.Address,
data cid.Cid,
price types.BigInt,
minSize abi.PaddedPieceSize,
duration abi.ChainEpoch,
verified bool,
removeUnsealed bool,
) (*network.Proposal, error) {
return fc.MakeDealWithOptions(
ctx,
miner,
data,
price,
duration,
DealWithMinSize(minSize),
DealWithVerified(verified),
DealWithFastRetrieval(!removeUnsealed),
)
}
func (fc *FilClient) SendProposalV110(ctx context.Context, netprop network.Proposal, propCid cid.Cid) (bool, error) {
ctx, span := Tracer.Start(ctx, "sendProposalV110")
defer span.End()
s, err := fc.streamToMiner(ctx, netprop.DealProposal.Proposal.Provider, DealProtocolv110)
if err != nil {
return false, fmt.Errorf("opening stream to miner: %w", err)
}
fc.host.ConnManager().Protect(s.Conn().RemotePeer(), "SendProposalV110")
defer func() {
fc.host.ConnManager().Unprotect(s.Conn().RemotePeer(), "SendProposalV110")
s.Close()
}()
// Send proposal to provider using deal protocol v1.1.0 format
var resp network.SignedResponse
if err := doRpc(ctx, s, &netprop, &resp); err != nil {
return false, fmt.Errorf("send proposal rpc: %w", err)
}
switch resp.Response.State {
case storagemarket.StorageDealError:
return true, fmt.Errorf("error response from miner: %s", resp.Response.Message)
case storagemarket.StorageDealProposalRejected:
return true, fmt.Errorf("deal rejected by miner: %s", resp.Response.Message)
default:
return true, fmt.Errorf("unrecognized response from miner: %d %s", resp.Response.State, resp.Response.Message)
case storagemarket.StorageDealWaitingForData, storagemarket.StorageDealProposalAccepted:
}
if propCid != resp.Response.Proposal {
return true, fmt.Errorf("proposal in saved deal did not match response (%s != %s)", propCid, resp.Response.Proposal)
}
return false, nil
}
type ProposalV120Config struct {
DealUUID uuid.UUID
Transfer smtypes.Transfer
Offline bool
SkipIPNIAnnounce bool
}
func DefaultProposalV120Config() ProposalV120Config {
return ProposalV120Config{
DealUUID: uuid.New(),
Transfer: smtypes.Transfer{},
}
}
type ProposalV120Option func(*ProposalV120Config, network.Proposal) error
func ProposalV120WithDealUUID(dealUUID uuid.UUID) ProposalV120Option {
return func(cfg *ProposalV120Config, netprop network.Proposal) error {
cfg.DealUUID = dealUUID
return nil
}
}
func ProposalV120WithLibp2pTransfer(
announceAddr multiaddr.Multiaddr,
authToken string,
clientID uint,
) ProposalV120Option {
return func(cfg *ProposalV120Config, netprop network.Proposal) error {
transferParams, err := json.Marshal(boosttypes.HttpRequest{
URL: "libp2p://" + announceAddr.String(),
Headers: map[string]string{
"Authorization": httptransport.BasicAuthHeader("", authToken),
},
})
if err != nil {
return fmt.Errorf("failed to marshal libp2p transfer params: %v", err)
}
cfg.Transfer = smtypes.Transfer{
Type: "libp2p",
ClientID: fmt.Sprintf("%d", clientID),
Params: transferParams,
Size: netprop.Piece.RawBlockSize,
}
return nil
}
}
func ProposalV120WithTransfer(transfer smtypes.Transfer) ProposalV120Option {
return func(cfg *ProposalV120Config, netprop network.Proposal) error {
cfg.Transfer = transfer
return nil
}
}
func ProposalV120WithOffline(offline bool) ProposalV120Option {
return func(cfg *ProposalV120Config, netprop network.Proposal) error {
cfg.Offline = offline
return nil
}
}
func ProposalV120WithSkipIPNIAnnounce(skip bool) ProposalV120Option {
return func(cfg *ProposalV120Config, netprop network.Proposal) error {
cfg.SkipIPNIAnnounce = skip
return nil
}
}
func ProposalV120WithConfig(newCfg ProposalV120Config) ProposalV120Option {
return func(cfg *ProposalV120Config, netprop network.Proposal) error {
*cfg = newCfg
return nil
}
}
// Deprecated: SendProposalV120 will be removed and SendProposalV120WithOptions
// will be replaced by SendProposalV120
func (fc *FilClient) SendProposalV120(
ctx context.Context,
dbid uint,
netprop network.Proposal,
dealUUID uuid.UUID,
announce multiaddr.Multiaddr,
authToken string,
) (bool, error) {
return fc.SendProposalV120WithOptions(
ctx,
netprop,
ProposalV120WithDealUUID(dealUUID),
ProposalV120WithLibp2pTransfer(announce, authToken, dbid),
)
}
func (fc *FilClient) SendProposalV120WithOptions(ctx context.Context, netprop network.Proposal, options ...ProposalV120Option) (bool, error) {
ctx, span := Tracer.Start(ctx, "sendProposalV120")
defer span.End()
// Gen config with options
cfg := DefaultProposalV120Config()
for _, option := range options {
if err := option(&cfg, netprop); err != nil {
return false, fmt.Errorf("failed to apply option %T: %v", option, err)
}
}
s, err := fc.streamToMiner(ctx, netprop.DealProposal.Proposal.Provider, DealProtocolv120)
if err != nil {
return false, fmt.Errorf("opening stream to miner: %w", err)
}
fc.host.ConnManager().Protect(s.Conn().RemotePeer(), "SendProposalV120")
defer func() {
fc.host.ConnManager().Unprotect(s.Conn().RemotePeer(), "SendProposalV120")
s.Close()
}()
// Send proposal to storage provider using deal protocol v1.2.0 format
params := smtypes.DealParams{
DealUUID: cfg.DealUUID,
ClientDealProposal: *netprop.DealProposal,
DealDataRoot: netprop.Piece.Root,
Transfer: cfg.Transfer,
RemoveUnsealedCopy: !netprop.FastRetrieval,
IsOffline: cfg.Offline,
SkipIPNIAnnounce: cfg.SkipIPNIAnnounce,
}
var resp smtypes.DealResponse
if err := doRpc(ctx, s, ¶ms, &resp); err != nil {
return false, fmt.Errorf("send proposal rpc: %w", err)
}
// Check if the deal proposal was accepted
if !resp.Accepted {
return true, fmt.Errorf("deal proposal rejected: %s", resp.Message)
}
return false, nil
}
func GeneratePieceCommitment(ctx context.Context, payloadCid cid.Cid, bstore blockstore.Blockstore) (cid.Cid, uint64, abi.UnpaddedPieceSize, error) {
selectiveCar := car.NewSelectiveCar(
context.Background(),
bstore,
[]car.Dag{{Root: payloadCid, Selector: shared.AllSelector()}},
car.MaxTraversalLinks(maxTraversalLinks),
car.TraverseLinksOnlyOnce(),
)
preparedCar, err := selectiveCar.Prepare()
if err != nil {
return cid.Undef, 0, 0, err
}
writer := new(commp.Calc)
err = preparedCar.Dump(ctx, writer)
if err != nil {
return cid.Undef, 0, 0, err
}
commpc, size, err := writer.Digest()
if err != nil {
return cid.Undef, 0, 0, err