This repository has been archived by the owner on Oct 3, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
peer.go
1097 lines (915 loc) · 26.6 KB
/
peer.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 main
import (
"context"
"crypto/rand"
"encoding/json"
"errors"
"fmt"
"io"
"io/fs"
"os"
"path/filepath"
"sort"
"sync"
"time"
"github.com/iand/mfsng"
"github.com/ipfs/boxo/bitswap"
"github.com/ipfs/boxo/bitswap/network"
blockservice "github.com/ipfs/boxo/blockservice"
blockstore "github.com/ipfs/boxo/blockstore"
offline "github.com/ipfs/boxo/exchange/offline"
files "github.com/ipfs/boxo/files"
"github.com/ipfs/boxo/filestore"
"github.com/ipfs/boxo/ipld/merkledag"
"github.com/ipfs/boxo/ipld/unixfs"
"github.com/ipfs/boxo/ipld/unixfs/importer/helpers"
"github.com/ipfs/boxo/ipld/unixfs/importer/trickle"
ipns "github.com/ipfs/boxo/ipns"
"github.com/ipfs/boxo/mfs"
provider "github.com/ipfs/boxo/provider"
"github.com/ipfs/boxo/provider/queue"
"github.com/ipfs/boxo/provider/simple"
"github.com/ipfs/go-cid"
"github.com/ipfs/go-datastore"
"github.com/ipfs/go-ds-badger2"
ipld "github.com/ipfs/go-ipld-format"
metrics "github.com/ipfs/go-metrics-interface"
pool "github.com/libp2p/go-buffer-pool"
"github.com/libp2p/go-libp2p"
dht "github.com/libp2p/go-libp2p-kad-dht"
dualdht "github.com/libp2p/go-libp2p-kad-dht/dual"
record "github.com/libp2p/go-libp2p-record"
crypto "github.com/libp2p/go-libp2p/core/crypto"
host "github.com/libp2p/go-libp2p/core/host"
"github.com/libp2p/go-libp2p/core/peer"
routing "github.com/libp2p/go-libp2p/core/routing"
connmgr "github.com/libp2p/go-libp2p/p2p/net/connmgr"
libp2ptls "github.com/libp2p/go-libp2p/p2p/security/tls"
"github.com/multiformats/go-multiaddr"
multihash "github.com/multiformats/go-multihash"
)
var BootstrapPeers = []peer.AddrInfo{
mustParseAddr("/dnsaddr/bootstrap.libp2p.io/p2p/QmNnooDu7bfjPFoTZYxMNLWUQJyrVwtbZg5gBMjTezGAJN"),
mustParseAddr("/dnsaddr/bootstrap.libp2p.io/p2p/QmQCU2EcMqAqQPR2i9bChDtGNJchTbq5TbXJJ16u19uLTa"),
mustParseAddr("/dnsaddr/bootstrap.libp2p.io/p2p/QmbLHAnMoJPWSCR5Zhtx6BHJX9KiKNN6tpvbUcqanj75Nb"),
mustParseAddr("/dnsaddr/bootstrap.libp2p.io/p2p/QmcZf59bWwK5XFi76CZX8cbJ4BhTzzA3gU1ZjYZcYW3dwt"),
}
func mustParseAddr(addr string) peer.AddrInfo {
ma, err := multiaddr.NewMultiaddr(addr)
if err != nil {
panic(fmt.Sprintf("failed to parse bootstrap address: %v", err))
}
ai, err := peer.AddrInfoFromP2pAddr(ma)
if err != nil {
panic(fmt.Sprintf("failed to create address info: %v", err))
}
return *ai
}
var defaultReprovideInterval = 12 * time.Hour
// Config wraps configuration options for the Peer.
type PeerConfig struct {
Offline bool
ReprovideInterval time.Duration
DatastorePath string
FileSystemPath string
ListenAddr string
Libp2pKeyFile string
ManifestPath string
}
type Peer struct {
offline bool
reprovideInterval time.Duration
listenAddr multiaddr.Multiaddr
peerKey crypto.PrivKey
datastorePath string
fileSystemPath string
manifestPath string
builder cid.Builder
host host.Host
dht routing.Routing
store datastore.Batching
dag ipld.DAGService // (consider ipld.BufferedDAG)
bstore *filestore.Filestore
// metrics
filesScannedCounter metrics.Counter
filesSyncedGauge metrics.Gauge
blocksScannedCounter metrics.Counter
blocksOrphanedCounter metrics.Counter
syncErrorsCounter metrics.Counter
gcErrorsCounter metrics.Counter
mu sync.Mutex // guards writes to bserv, reprovider and mfsRoot fields
bserv blockservice.BlockService
reprovider provider.System
mfsRoot *mfs.Root
}
func NewPeer(cfg *PeerConfig) (*Peer, error) {
// Create a temporary context to hold metrics metadata
ctx := metrics.CtxScope(context.Background(), appName)
p := new(Peer)
p.setupMetrics(ctx)
if err := p.applyConfig(cfg); err != nil {
return nil, fmt.Errorf("config: %w", err)
}
if err := p.setupDatastore(); err != nil {
return nil, fmt.Errorf("setup datastore: %w", err)
}
if err := p.setupBlockstore(ctx); err != nil {
return nil, fmt.Errorf("setup blockstore: %w", err)
}
if !p.offline {
if err := p.setupLibp2p(ctx); err != nil {
return nil, fmt.Errorf("setup libp2p: %w", err)
}
if err := p.bootstrap(ctx, BootstrapPeers); err != nil {
return nil, fmt.Errorf("bootstrap: %w", err)
}
}
if err := p.setupBlockService(ctx); err != nil {
return nil, fmt.Errorf("setup blockservice: %w", err)
}
if err := p.setupReprovider(ctx); err != nil {
return nil, fmt.Errorf("setup reprovider: %w", err)
}
if err := p.setupDAGService(); err != nil {
p.Close()
return nil, fmt.Errorf("setup dagservice: %w", err)
}
if err := p.setupMfs(ctx); err != nil {
p.Close()
return nil, fmt.Errorf("setup mfs: %w", err)
}
return p, nil
}
func (p *Peer) Close() error {
p.mu.Lock()
defer p.mu.Unlock()
if p.reprovider != nil {
if err := p.reprovider.Close(); err != nil {
return fmt.Errorf("reprovider: %w", err)
}
p.reprovider = nil
}
if p.mfsRoot != nil {
if err := p.mfsRoot.Close(); err != nil {
return fmt.Errorf("mfs: %w", err)
}
p.mfsRoot = nil
}
if p.bserv != nil {
if err := p.bserv.Close(); err != nil {
return fmt.Errorf("block service: %w", err)
}
p.bserv = nil
}
return nil
}
func (p *Peer) applyConfig(cfg *PeerConfig) error {
if cfg == nil {
cfg = &PeerConfig{}
}
p.offline = cfg.Offline
p.manifestPath = cfg.ManifestPath
if cfg.ReprovideInterval == 0 {
p.reprovideInterval = defaultReprovideInterval
} else {
p.reprovideInterval = cfg.ReprovideInterval
}
if cfg.DatastorePath == "" {
return fmt.Errorf("missing datastore path")
}
p.datastorePath = cfg.DatastorePath
if cfg.FileSystemPath == "" {
return fmt.Errorf("missing file system path")
}
p.fileSystemPath = cfg.FileSystemPath
var err error
p.listenAddr, err = multiaddr.NewMultiaddr(cfg.ListenAddr)
if err != nil {
return fmt.Errorf("listen addr: %w", err)
}
if cfg.Libp2pKeyFile == "" {
return fmt.Errorf("missing libp2p keyfile")
}
p.peerKey, err = loadOrInitPeerKey(cfg.Libp2pKeyFile)
if err != nil {
return fmt.Errorf("key file: %w", err)
}
// Set up a consistent cid builder
const hashfunc = "sha2-256"
prefix, err := merkledag.PrefixForCidVersion(1)
if err != nil {
return fmt.Errorf("bad CID Version: %s", err)
}
hashFunCode, ok := multihash.Names[hashfunc]
if !ok {
return fmt.Errorf("unrecognized hash function: %s", hashfunc)
}
prefix.MhType = hashFunCode
prefix.MhLength = -1
p.builder = &prefix
return nil
}
func (p *Peer) setupMetrics(ctx context.Context) {
p.filesScannedCounter = metrics.NewCtx(ctx, "files_scanned_total", "Total number of files scanned during a sync").Counter()
p.filesSyncedGauge = metrics.NewCtx(ctx, "files_synced", "Current number of files known to be synced to the blockstore").Gauge()
p.blocksScannedCounter = metrics.NewCtx(ctx, "blocks_scanned_total", "Total number of blocks in the blockstore scanned during garbage collection").Counter()
p.blocksOrphanedCounter = metrics.NewCtx(ctx, "blocks_orphaned_total", "Total number of blocks in the blockstore found to be orphaned during garbage collection").Counter()
p.syncErrorsCounter = metrics.NewCtx(ctx, "sync_errors_total", "Total number of errors encountered during a sync").Counter()
p.gcErrorsCounter = metrics.NewCtx(ctx, "gc_errors_total", "Total number of errors encountered during garbage collection").Counter()
}
func (p *Peer) setupDatastore() error {
logger.Debugf("setting up ipfs datastore at %s", p.datastorePath)
opts := badger.DefaultOptions
ds, err := badger.NewDatastore(p.datastorePath, &opts)
if err != nil {
return fmt.Errorf("new datastore: %w", err)
}
p.store = ds
return nil
}
func (p *Peer) setupBlockstore(ctx context.Context) error {
logger.Debug("setting up ipfs blockstore")
fm := filestore.NewFileManager(p.store, p.fileSystemPath)
fm.AllowFiles = true
bs := blockstore.NewBlockstore(p.store)
bs = blockstore.NewIdStore(bs)
cachedbs, err := blockstore.CachedBlockstore(ctx, bs, blockstore.DefaultCacheOpts())
if err != nil {
return fmt.Errorf("new cached blockstore: %w", err)
}
p.bstore = filestore.NewFilestore(cachedbs, fm)
return nil
}
func (p *Peer) setupBlockService(ctx context.Context) error {
logger.Debug("setting up ipfs block service")
if p.offline {
p.bserv = blockservice.New(p.bstore, offline.Exchange(p.bstore))
return nil
}
bswapnet := network.NewFromIpfsHost(p.host, p.dht)
bswap := bitswap.New(ctx, bswapnet, p.bstore)
bserv := blockservice.New(p.bstore, bswap)
p.mu.Lock()
p.bserv = bserv
p.mu.Unlock()
return nil
}
func (p *Peer) setupDAGService() error {
p.dag = merkledag.NewDAGService(p.bserv)
return nil
}
func (p *Peer) setupReprovider(ctx context.Context) error {
logger.Debug("setting up reprovider")
if p.offline || p.reprovideInterval < 0 {
p.reprovider = provider.NewOfflineProvider()
return nil
}
queue, err := queue.NewQueue(ctx, "repro", p.store)
if err != nil {
return err
}
prov := simple.NewProvider(
ctx,
queue,
p.dht,
)
reprov := simple.NewReprovider(
ctx,
p.reprovideInterval,
p.dht,
simple.NewBlockstoreProvider(p.bstore),
)
reprovider := provider.NewSystem(prov, reprov)
reprovider.Run()
p.mu.Lock()
p.reprovider = reprovider
p.mu.Unlock()
return nil
}
func (p *Peer) bootstrap(ctx context.Context, peers []peer.AddrInfo) error {
logger.Info("bootstrapping ipfs node")
connected := make(chan struct{}, len(peers))
var wg sync.WaitGroup
for _, pinfo := range peers {
// h.Peerstore().AddAddrs(pinfo.ID, pinfo.Addrs, peerstore.PermanentAddrTTL)
wg.Add(1)
go func(pinfo peer.AddrInfo) {
defer wg.Done()
err := p.host.Connect(ctx, pinfo)
if err != nil {
logger.Warn(err)
return
}
logger.Debugf("Connected to %s", pinfo.ID)
connected <- struct{}{}
}(pinfo)
}
wg.Wait()
close(connected)
i := 0
for range connected {
i++
}
logger.Debugf("connected to %d peers", len(peers))
err := p.dht.Bootstrap(context.TODO())
if err != nil {
return fmt.Errorf("dht bootstrap: %w", err)
}
p.logHostAddresses()
return nil
}
func (p *Peer) setupLibp2p(ctx context.Context) error {
var ddht *dualdht.DHT
var err error
connmgr, err := connmgr.NewConnManager(100, 600, connmgr.WithGracePeriod(time.Minute))
if err != nil {
return fmt.Errorf("libp2p: %w", err)
}
finalOpts := []libp2p.Option{
libp2p.Identity(p.peerKey),
libp2p.ListenAddrs(p.listenAddr),
libp2p.Routing(func(h host.Host) (routing.PeerRouting, error) {
ddht, err = newDHT(ctx, h, p.store)
return ddht, err
}),
libp2p.NATPortMap(),
libp2p.ConnectionManager(connmgr),
libp2p.EnableNATService(),
libp2p.Security(libp2ptls.ID, libp2ptls.New),
libp2p.DefaultTransports,
}
h, err := libp2p.New(
finalOpts...,
)
if err != nil {
return fmt.Errorf("libp2p: %w", err)
}
p.host = h
p.dht = ddht
return nil
}
func (p *Peer) setupMfs(ctx context.Context) error {
dsk := datastore.NewKey("/local/filesroot")
pf := func(ctx context.Context, c cid.Cid) error {
if err := p.store.Sync(ctx, blockstore.BlockPrefix); err != nil {
return err
}
if err := p.store.Sync(ctx, filestore.FilestorePrefix); err != nil {
return err
}
if err := p.store.Put(ctx, dsk, c.Bytes()); err != nil {
return err
}
return p.store.Sync(ctx, dsk)
}
var nd *merkledag.ProtoNode
val, err := p.store.Get(ctx, dsk)
switch {
case err == datastore.ErrNotFound || val == nil:
nd = unixfs.EmptyDirNode()
err := p.dag.Add(ctx, nd)
if err != nil {
return fmt.Errorf("write root: %w", err)
}
case err == nil:
c, err := cid.Cast(val)
if err != nil {
return fmt.Errorf("cast root cid: %w", err)
}
rnd, err := p.dag.Get(ctx, c)
if err != nil {
return fmt.Errorf("get root: %w", err)
}
pbnd, ok := rnd.(*merkledag.ProtoNode)
if !ok {
return merkledag.ErrNotProtobuf
}
nd = pbnd
default:
return err
}
root, err := mfs.NewRoot(ctx, p.dag, nd, pf)
if err != nil {
return fmt.Errorf("new root: %w", err)
}
root.GetDirectory().SetCidBuilder(p.builder)
p.mu.Lock()
p.mfsRoot = root
p.mu.Unlock()
return nil
}
func (p *Peer) getMfsRoot() *mfs.Root {
p.mu.Lock()
r := p.mfsRoot
p.mu.Unlock()
return r
}
// Sync ensures that the underlying blockstore accurately represents the filesystem the peer is monitoring.
func (p *Peer) Sync(ctx context.Context) error {
logger.Infow("starting filesystem sync")
// ensure mfs only contains files that are under the file system root
if err := p.removeOrphanedFiles(ctx); err != nil {
p.syncErrorsCounter.Inc()
return fmt.Errorf("ensure orphaned files: %w", err)
}
// ensure all files under the file system root are in the filestore and mfs
if err := p.ensureFilesIndexed(ctx); err != nil {
p.syncErrorsCounter.Inc()
return fmt.Errorf("ensure files indexed: %w", err)
}
// provide the new mfs root on the dht
if err := p.announceMfsRoot(ctx); err != nil {
p.syncErrorsCounter.Inc()
return fmt.Errorf("announce mfs root: %w", err)
}
if p.manifestPath != "" {
if err := p.writeManifest(ctx); err != nil {
p.syncErrorsCounter.Inc()
return fmt.Errorf("write manifest: %w", err)
}
}
return nil
}
// GarbageCollect removes blocks from the filestore that do not correspond to valid files.
func (p *Peer) GarbageCollect(ctx context.Context) error {
logger.Infow("starting garbage collection")
next, err := filestore.VerifyAll(ctx, p.bstore, true)
if err != nil {
p.gcErrorsCounter.Inc()
return err
}
deleteSet := cid.NewSet()
for {
select {
case <-ctx.Done():
return ctx.Err()
default:
}
r := next(ctx)
if r == nil {
break
}
p.blocksScannedCounter.Inc()
if r.Status == filestore.StatusOk {
continue
}
deleteSet.Visit(r.Key)
logger.Debugw("orphaned block", "cid", r.Key, "status", r.Status, "error", r.ErrorMsg, "filepath", r.FilePath, "offset", r.Offset, "size", r.Size)
p.blocksOrphanedCounter.Inc()
}
return deleteSet.ForEach(func(c cid.Cid) error {
if err := p.bstore.DeleteBlock(ctx, c); err != nil {
p.gcErrorsCounter.Inc()
logger.Errorf("failed to delete block '%s': %v", c.String(), err)
}
return nil
})
}
// removeOrphanedFiles removes files from mfs that do not correspond to valid files.
func (p *Peer) removeOrphanedFiles(ctx context.Context) error {
logger.Debugw("scanning for orphaned files (not implemented yet)")
// TODO: implement
return nil
}
func (p *Peer) ensureFilesIndexed(ctx context.Context) error {
logger.Debugw("ensuring filesystem files are present in blockstore")
mfsRoot := p.getMfsRoot()
if mfsRoot == nil {
return fmt.Errorf("mfs unavailable")
}
filesSynced := 0
defer func() {
p.filesSyncedGauge.Set(float64(filesSynced))
}()
return filepath.WalkDir(config.fileSystemPath, func(path string, di fs.DirEntry, rerr error) error {
select {
case <-ctx.Done():
return ctx.Err()
default:
}
// It's valiid to place the manifest file in the directory being served but we don't add it to the dag
if path == p.manifestPath {
logger.Debugw("found manifest, not adding to blockstore", "path", path)
return nil // don't abort the entire walk
}
if rerr != nil {
logger.Errorw("failed to walk file", "error", rerr, "path", path)
return nil // don't abort the entire walk
}
if di.Type() != 0 {
// non-file
return nil
}
p.filesScannedCounter.Inc()
relPath, err := filepath.Rel(p.fileSystemPath, path)
if err != nil {
return fmt.Errorf("path not relative to %s: %w", p.fileSystemPath, err)
}
mfsPath := filepath.Join("/", relPath)
fsn, err := mfs.Lookup(mfsRoot, mfsPath)
if err != nil {
if errors.Is(err, os.ErrNotExist) {
logger.Debugw("adding unindexed file", "path", path)
_, err := p.addFile(ctx, path, di)
if err != nil {
logger.Errorw("failed to add file to mfs", "error", err, "path", path)
return nil // don't abort the entire walk
}
return nil
}
logger.Errorw("failed to lookup file in mfs", "error", err, "mfs_path", mfsPath)
return nil // don't abort the entire walk
}
fi, err := di.Info()
if err != nil {
logger.Errorw("failed to read fileinfo for file", "error", err, "path", path)
return nil // don't abort the entire walk
}
modTime, err := mfsModTime(fsn)
if err != nil {
logger.Errorw("failed to read modtime for mfs file", "error", err, "mfs_path", mfsPath)
return nil // don't abort the entire walk
}
if !fi.ModTime().Equal(modTime) {
logger.Debugw("updating modified file", "path", path, "mfs_modtime", modTime, "file_modtime", fi.ModTime())
_, err := p.addFile(ctx, path, di)
if err != nil {
logger.Errorw("failed to add file to mfs", "error", err, "path", path)
return nil // don't abort the entire walk
}
}
filesSynced++
return nil
})
}
func (p *Peer) announceMfsRoot(ctx context.Context) error {
mfsRoot := p.getMfsRoot()
if mfsRoot == nil {
return fmt.Errorf("mfs unavailable")
}
rootNode, err := mfsRoot.GetDirectory().GetNode()
if err != nil {
return fmt.Errorf("get root node: %s", err)
}
// provide root synchronously
logger.Infow("providing mfs root", "cid", rootNode.Cid().String())
if err := p.dht.Provide(ctx, rootNode.Cid(), true); err != nil {
return fmt.Errorf("provide mfs root: %w", err)
}
return nil
}
func (p *Peer) ProvideExistingFiles(ctx context.Context) error {
mfsRoot := p.getMfsRoot()
if mfsRoot == nil {
return fmt.Errorf("mfs unavailable")
}
rootNode, err := mfsRoot.GetDirectory().GetNode()
if err != nil {
return fmt.Errorf("get root node: %s", err)
}
fsys, err := mfsng.ReadFS(rootNode, p.dag)
if err != nil {
return fmt.Errorf("readfs: %s", err)
}
count := 0
if err := fs.WalkDir(fsys, ".", func(path string, de fs.DirEntry, rerr error) error {
select {
case <-ctx.Done():
return ctx.Err()
default:
}
if fde, ok := de.(*mfsng.File); ok {
// provide files asynchronously
if err := p.reprovider.Provide(fde.Cid()); err != nil {
return fmt.Errorf("provide file: %w", err)
}
count++
}
return nil
}); err != nil {
return fmt.Errorf("walk: %w", err)
}
logger.Debugf("queued %d files for providing", count)
return nil
}
func (p *Peer) addFile(ctx context.Context, path string, di fs.DirEntry) (ipld.Node, error) {
logger.Debugw("adding file", "path", path)
relPath, err := filepath.Rel(p.fileSystemPath, path)
if err != nil {
return nil, fmt.Errorf("path not relative to %s: %w", p.fileSystemPath, err)
}
baseName := filepath.Base(path)
if baseName == "" {
return nil, fmt.Errorf("path does not refer to a file: %s", path)
}
f, err := os.Open(path) // For read access.
if err != nil {
return nil, fmt.Errorf("open file: %w", err)
}
defer f.Close()
fi, err := di.Info()
if err != nil {
return nil, fmt.Errorf("file info: %w", err)
}
r, err := files.NewReaderPathFile(path, f, fi)
if err != nil {
return nil, fmt.Errorf("new reader path file: %w", err)
}
dbp := helpers.DagBuilderParams{
Dagserv: p.dag,
RawLeaves: true,
Maxlinks: helpers.DefaultLinksPerBlock,
NoCopy: true,
CidBuilder: p.builder,
}
// TODO: special handling for car files - serve their blocks directly?
chnk := NewSplitter(r, DefaultFirstBlockSize, DefaultBlockSize)
dbh, err := dbp.New(chnk)
if err != nil {
return nil, fmt.Errorf("new dag builder helper: %w", err)
}
node, err := trickle.Layout(dbh)
if err != nil {
return nil, fmt.Errorf("layout dag: %w", err)
}
logger.Debugw("written to blockstore", "cid", node.Cid().String())
mfsPath := filepath.Join("/", relPath)
if err := p.addFileToMfs(ctx, mfsPath, node); err != nil {
return nil, fmt.Errorf("add file to mfs: %w", err)
}
logger.Debugw("written to mfs", "cid", node.Cid().String(), "mfs_path", mfsPath)
if err := p.reprovider.Provide(node.Cid()); err != nil {
return node, fmt.Errorf("provide file cid: %w", err)
}
logger.Debugw("announced file to dht", "cid", node.Cid().String())
return node, nil
}
func (p *Peer) addFileToMfs(ctx context.Context, mfsPath string, node ipld.Node) error {
mfsRoot := p.getMfsRoot()
if mfsRoot == nil {
return fmt.Errorf("mfs unavailable")
}
mfsDir := filepath.Dir(mfsPath)
baseName := filepath.Base(mfsPath)
// Remove existing if it exists
_, err := mfs.Lookup(mfsRoot, mfsPath)
if err == nil {
// No error so file must exists and we need to remove it
dir, err := p.lookupDir(mfsDir)
if err != nil {
return fmt.Errorf("lookup dir %s: %w", mfsDir, err)
}
if err := dir.Unlink(baseName); err != nil {
return fmt.Errorf("unlink file %s: %s", mfsPath, err)
}
} else {
// Not exists is fine, we ignore it, otherwise return the error
if !errors.Is(err, os.ErrNotExist) {
return fmt.Errorf("lookup: %w", err)
}
}
dirOpts := mfs.MkdirOpts{
Mkparents: true,
Flush: true,
CidBuilder: p.builder,
}
if err := mfs.Mkdir(mfsRoot, mfsDir, dirOpts); err != nil {
return fmt.Errorf("mkdir %s: %w", mfsDir, err)
}
dir, err := p.lookupDir(mfsDir)
if err != nil {
return fmt.Errorf("lookup dir %s: %w", mfsDir, err)
}
err = dir.AddChild(baseName, node)
if err != nil {
return fmt.Errorf("add child %s: %w", baseName, err)
}
if _, err := mfs.FlushPath(ctx, mfsRoot, mfsPath); err != nil {
return fmt.Errorf("flush path %s: %w", mfsPath, err)
}
return nil
}
func (p *Peer) lookupDir(mfsDir string) (*mfs.Directory, error) {
mfsRoot := p.getMfsRoot()
if mfsRoot == nil {
return nil, fmt.Errorf("mfs unavailable")
}
di, err := mfs.Lookup(mfsRoot, mfsDir)
if err != nil {
return nil, err
}
d, ok := di.(*mfs.Directory)
if !ok {
return nil, fmt.Errorf("%s is not a directory", mfsDir)
}
return d, nil
}
func (p *Peer) logHostAddresses() {
if p.offline {
logger.Debugf("not listening, running in offline mode")
return
}
var lisAddrs []string
ifaceAddrs, err := p.host.Network().InterfaceListenAddresses()
if err != nil {
logger.Errorf("failed to read listening addresses: %s", err)
}
for _, addr := range ifaceAddrs {
lisAddrs = append(lisAddrs, addr.String())
}
sort.Strings(lisAddrs)
for _, addr := range lisAddrs {
logger.Debugf("listening on %s", addr)
}
var addrs []string
for _, addr := range p.host.Addrs() {
addrs = append(addrs, addr.String())
}
sort.Strings(addrs)
for _, addr := range addrs {
logger.Debugf("announcing %s", addr)
}
}
func (p *Peer) writeManifest(ctx context.Context) error {
mfsRoot := p.getMfsRoot()
if mfsRoot == nil {
return fmt.Errorf("mfs unavailable")
}
node, err := mfsRoot.GetDirectory().GetNode()
if err != nil {
return fmt.Errorf("get root node: %w", err)
}
lastWritten, err := p.readManifestRootCid(ctx)
if err != nil {
return fmt.Errorf("read manifest root cid: %w", err)
}
if lastWritten == node.Cid().String() {
// mfs is unchanged since last time
return nil
}
logger.Debug("writing manifest file")
f, err := os.OpenFile(p.manifestPath, os.O_RDWR|os.O_CREATE, 0o755)
if err != nil {
return fmt.Errorf("open manifest file for writing: %w", err)
}
defer f.Close()
man := &Manifest{
RootCid: node.Cid().String(),
}
fsys, err := mfsng.ReadFS(node, p.dag)
if err != nil {
return fmt.Errorf("readfs: %s", err)
}
if err := fs.WalkDir(fsys, ".", func(path string, de fs.DirEntry, rerr error) error {
select {
case <-ctx.Done():
return ctx.Err()
default:
}
if fde, ok := de.(*mfsng.File); ok {
mfile := ManifestFile{
Path: path,
Cid: fde.Cid().String(),
}
info, err := fde.Stat()
if err == nil {
mfile.Size = info.Size()
}
man.Files = append(man.Files, mfile)
}
return nil
}); err != nil {
return fmt.Errorf("walk: %w", err)
}
sort.Slice(man.Files, func(a, b int) bool {
return man.Files[a].Path < man.Files[b].Path
})
if err := json.NewEncoder(f).Encode(man); err != nil {
return fmt.Errorf("encode json: %w", err)
}
logger.Debugf("manifest file written to %s", p.manifestPath)
return nil
}
func (p *Peer) readManifestRootCid(ctx context.Context) (string, error) {
f, err := os.Open(p.manifestPath)
if errors.Is(err, os.ErrNotExist) {
return "", nil
}
defer f.Close()
var man struct {
RootCid string `json:"root_cid"`
}
if err := json.NewDecoder(f).Decode(&man); err != nil {
return "", fmt.Errorf("decode json: %w", err)
}
return man.RootCid, nil
}
func newDHT(ctx context.Context, h host.Host, ds datastore.Batching) (*dualdht.DHT, error) {
dhtOpts := []dualdht.Option{
dualdht.DHTOption(dht.NamespacedValidator("pk", record.PublicKeyValidator{})),
dualdht.DHTOption(dht.NamespacedValidator("ipns", ipns.Validator{KeyBook: h.Peerstore()})),
dualdht.DHTOption(dht.Concurrency(10)),
dualdht.DHTOption(dht.Mode(dht.ModeAuto)),
}
if ds != nil {
dhtOpts = append(dhtOpts, dualdht.DHTOption(dht.Datastore(ds)))
}
return dualdht.New(ctx, h, dhtOpts...)
}
func loadOrInitPeerKey(kf string) (crypto.PrivKey, error) {
data, err := os.ReadFile(kf)
if err != nil {
if !os.IsNotExist(err) {
return nil, err
}
keyDir := filepath.Dir(kf)
if err := os.MkdirAll(keyDir, os.ModePerm); err != nil {
return nil, fmt.Errorf("mkdir %q: %w", keyDir, err)
}
k, _, err := crypto.GenerateEd25519Key(rand.Reader)
if err != nil {
return nil, err