forked from rs-ipfs/rust-ipfs
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathlib.rs
1508 lines (1331 loc) · 52.3 KB
/
lib.rs
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
//! IPFS node implementation
//#![deny(missing_docs)]
#![cfg_attr(feature = "nightly", feature(external_doc))]
#![cfg_attr(feature = "nightly", doc(include = "../README.md"))]
#[macro_use]
extern crate tracing;
pub use crate::ipld::Ipld;
use anyhow::{anyhow, format_err};
pub use bitswap::{BitswapEvent, Block, Stats};
pub use cid::Cid;
use cid::Codec;
use either::Either;
use futures::channel::mpsc::{channel, Receiver, Sender};
use futures::channel::oneshot::{channel as oneshot_channel, Sender as OneshotSender};
use futures::sink::SinkExt;
use futures::stream::{Fuse, Stream};
pub use libp2p::core::{
connection::ListenerId, multiaddr::Protocol, ConnectedPoint, Multiaddr, PeerId, PublicKey,
};
pub use libp2p::identity::Keypair;
use libp2p::swarm::NetworkBehaviour;
use std::path::PathBuf;
use tracing::Span;
use tracing_futures::Instrument;
use std::borrow::Borrow;
use std::collections::HashMap;
use std::fmt;
use std::future::Future;
use std::ops::Range;
use std::pin::Pin;
use std::sync::{atomic::Ordering, Arc};
use std::task::{Context, Poll};
mod config;
pub mod dag;
pub mod error;
#[macro_use]
pub mod ipld;
pub mod ipns;
pub mod p2p;
pub mod path;
pub mod refs;
pub mod repo;
mod subscription;
pub mod unixfs;
use self::dag::IpldDag;
pub use self::error::Error;
use self::ipns::Ipns;
pub use self::p2p::pubsub::{PubsubMessage, SubscriptionStream};
use self::p2p::{create_swarm, SwarmOptions, TSwarm};
pub use self::p2p::{Connection, KadResult, MultiaddrWithPeerId, MultiaddrWithoutPeerId};
pub use self::path::IpfsPath;
pub use self::repo::RepoTypes;
use self::repo::{create_repo, Repo, RepoEvent, RepoOptions};
use self::subscription::SubscriptionFuture;
/// All types can be changed at compile time by implementing
/// `IpfsTypes`.
pub trait IpfsTypes: RepoTypes {}
impl<T: RepoTypes> IpfsTypes for T {}
/// Default IPFS types.
#[derive(Debug)]
pub struct Types;
impl RepoTypes for Types {
type TBlockStore = repo::fs::FsBlockStore;
type TDataStore = repo::mem::MemDataStore;
}
/// Testing IPFS types
#[derive(Debug)]
pub struct TestTypes;
impl RepoTypes for TestTypes {
type TBlockStore = repo::mem::MemBlockStore;
type TDataStore = repo::mem::MemDataStore;
}
/// Ipfs options
#[derive(Clone)]
pub struct IpfsOptions {
/// The path of the ipfs repo.
pub ipfs_path: PathBuf,
/// The keypair used with libp2p.
pub keypair: Keypair,
/// Nodes dialed during startup.
pub bootstrap: Vec<(Multiaddr, PeerId)>,
/// Enables mdns for peer discovery when true.
pub mdns: bool,
/// Custom Kademlia protocol name.
pub kad_protocol: Option<String>,
}
impl fmt::Debug for IpfsOptions {
fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
// needed since libp2p::identity::Keypair does not have a Debug impl, and the IpfsOptions
// is a struct with all public fields, so don't enforce users to use this wrapper.
fmt.debug_struct("IpfsOptions")
.field("ipfs_path", &self.ipfs_path)
.field("bootstrap", &self.bootstrap)
.field("keypair", &DebuggableKeypair(&self.keypair))
.field("mdns", &self.mdns)
.field("kad_protocol", &self.kad_protocol)
.finish()
}
}
impl IpfsOptions {
/// Creates an inmemory store backed node for tests
pub fn inmemory_with_generated_keys() -> Self {
Self {
ipfs_path: std::env::temp_dir(),
keypair: Keypair::generate_ed25519(),
mdns: Default::default(),
bootstrap: Default::default(),
kad_protocol: Default::default(),
}
}
}
/// Workaround for libp2p::identity::Keypair missing a Debug impl, works with references and owned
/// keypairs.
#[derive(Clone)]
struct DebuggableKeypair<I: Borrow<Keypair>>(I);
impl<I: Borrow<Keypair>> fmt::Debug for DebuggableKeypair<I> {
fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
let kind = match self.get_ref() {
Keypair::Ed25519(_) => "Ed25519",
Keypair::Rsa(_) => "Rsa",
Keypair::Secp256k1(_) => "Secp256k1",
};
write!(fmt, "Keypair::{}", kind)
}
}
impl<I: Borrow<Keypair>> DebuggableKeypair<I> {
fn get_ref(&self) -> &Keypair {
self.0.borrow()
}
}
impl IpfsOptions {
pub fn new(
ipfs_path: PathBuf,
keypair: Keypair,
bootstrap: Vec<(Multiaddr, PeerId)>,
mdns: bool,
kad_protocol: Option<String>,
) -> Self {
Self {
ipfs_path,
keypair,
bootstrap,
mdns,
kad_protocol,
}
}
}
impl Default for IpfsOptions {
/// Create `IpfsOptions` from environment.
///
/// # Panics
///
/// Can panic if two threads call this method at the same time due to race condition on
/// creating a configuration file under `IPFS_PATH` and other thread failing to read the just
/// created empty file. Because of this, the implementation has been disabled in tests.
fn default() -> Self {
use self::config::ConfigFile;
if cfg!(test) {
// making this implementation conditional on `not(test)` results in multiple dead_code
// lints on config.rs but for rustc 1.42.0 at least having this `cfg!(test)` branch
// does not result in the same.
panic!(
"This implementation must not be invoked when testing as it cannot be safely
used from multiple threads"
);
}
let ipfs_path = if let Ok(path) = std::env::var("IPFS_PATH") {
PathBuf::from(path)
} else {
let root = if let Some(home) = dirs::home_dir() {
home
} else {
std::env::current_dir().unwrap()
};
root.join(".rust-ipfs")
};
let config_path = dirs::config_dir()
.unwrap()
.join("rust-ipfs")
.join("config.json");
let config = ConfigFile::new(config_path).unwrap();
let keypair = config.identity_key_pair();
let bootstrap = config.bootstrap();
IpfsOptions {
ipfs_path,
keypair,
bootstrap,
mdns: true,
kad_protocol: None,
}
}
}
#[derive(Debug)]
pub struct Ipfs<Types: IpfsTypes>(Arc<IpfsInner<Types>>);
impl<Types: IpfsTypes> Clone for Ipfs<Types> {
fn clone(&self) -> Self {
Ipfs(Arc::clone(&self.0))
}
}
/// Ipfs struct creates a new IPFS node and is the main entry point
/// for interacting with IPFS.
#[derive(Debug)]
pub struct IpfsInner<Types: IpfsTypes> {
pub span: Span,
repo: Repo<Types>,
keys: DebuggableKeypair<Keypair>,
to_task: Sender<IpfsEvent>,
}
type Channel<T> = OneshotSender<Result<T, Error>>;
/// Events used internally to communicate with the swarm, which is executed in the the background
/// task.
#[derive(Debug)]
enum IpfsEvent {
/// Connect
Connect(
MultiaddrWithPeerId,
OneshotSender<Option<SubscriptionFuture<(), String>>>,
),
/// Addresses
Addresses(Channel<Vec<(PeerId, Vec<Multiaddr>)>>),
/// Local addresses
Listeners(Channel<Vec<Multiaddr>>),
/// Connections
Connections(Channel<Vec<Connection>>),
/// Disconnect
Disconnect(MultiaddrWithPeerId, Channel<()>),
/// Request background task to return the listened and external addresses
GetAddresses(OneshotSender<Vec<Multiaddr>>),
PubsubSubscribe(String, OneshotSender<Option<SubscriptionStream>>),
PubsubUnsubscribe(String, OneshotSender<bool>),
PubsubPublish(String, Vec<u8>, OneshotSender<()>),
PubsubPeers(Option<String>, OneshotSender<Vec<PeerId>>),
PubsubSubscribed(OneshotSender<Vec<String>>),
WantList(Option<PeerId>, OneshotSender<Vec<(Cid, bitswap::Priority)>>),
BitswapStats(OneshotSender<BitswapStats>),
AddListeningAddress(Multiaddr, Channel<Multiaddr>),
RemoveListeningAddress(Multiaddr, Channel<()>),
Bootstrap(OneshotSender<Result<SubscriptionFuture<KadResult, String>, Error>>),
AddPeer(PeerId, Multiaddr),
GetClosestPeers(PeerId, OneshotSender<SubscriptionFuture<KadResult, String>>),
GetBitswapPeers(OneshotSender<Vec<PeerId>>),
FindPeer(
PeerId,
bool,
OneshotSender<Either<Vec<Multiaddr>, SubscriptionFuture<KadResult, String>>>,
),
GetProviders(Cid, OneshotSender<SubscriptionFuture<KadResult, String>>),
Provide(
Cid,
OneshotSender<Result<SubscriptionFuture<KadResult, String>, Error>>,
),
Exit,
}
/// Configured Ipfs instace or value which can be only initialized.
pub struct UninitializedIpfs<Types: IpfsTypes> {
repo: Repo<Types>,
span: Span,
keys: Keypair,
options: IpfsOptions,
repo_events: Receiver<RepoEvent>,
}
impl<Types: IpfsTypes> UninitializedIpfs<Types> {
/// Configures a new UninitializedIpfs with from the given options and optionally a span.
/// If the span is not given, it is defaulted to `tracing::trace_span!("ipfs")`.
///
/// The span is attached to all operations called on the later created `Ipfs` along with all
/// operations done in the background task as well as tasks spawned by the underlying
/// `libp2p::Swarm`.
pub async fn new(options: IpfsOptions, span: Option<Span>) -> Self {
let repo_options = RepoOptions::from(&options);
let (repo, repo_events) = create_repo(repo_options);
let keys = options.keypair.clone();
let span = span.unwrap_or_else(|| tracing::trace_span!("ipfs"));
UninitializedIpfs {
repo,
span,
keys,
options,
repo_events,
}
}
pub async fn default() -> Self {
Self::new(IpfsOptions::default(), None).await
}
/// Initialize the ipfs node. The returned `Ipfs` value is cloneable, send and sync, and the
/// future should be spawned on a executor as soon as possible.
pub async fn start(self) -> Result<(Ipfs<Types>, impl Future<Output = ()>), Error> {
use futures::stream::StreamExt;
let UninitializedIpfs {
repo,
span,
keys,
repo_events,
..
} = self;
repo.init().await?;
let (to_task, receiver) = channel::<IpfsEvent>(1);
let ipfs = Ipfs(Arc::new(IpfsInner {
span,
repo,
keys: DebuggableKeypair(keys),
to_task,
}));
let swarm_options = SwarmOptions::from(&self.options);
let swarm = create_swarm(swarm_options, ipfs.clone()).await;
let fut = IpfsFuture {
repo_events: repo_events.fuse(),
from_facade: receiver.fuse(),
swarm,
listening_addresses: HashMap::new(),
};
Ok((ipfs, fut))
}
}
impl<Types: IpfsTypes> std::ops::Deref for Ipfs<Types> {
type Target = IpfsInner<Types>;
fn deref(&self) -> &Self::Target {
&self.0
}
}
impl<Types: IpfsTypes> Ipfs<Types> {
pub fn dag(&self) -> IpldDag<Types> {
IpldDag::new(self.clone())
}
fn ipns(&self) -> Ipns<Types> {
Ipns::new(self.clone())
}
/// Puts a block into the ipfs repo.
pub async fn put_block(&self, block: Block) -> Result<Cid, Error> {
self.repo
.put_block(block)
.instrument(self.span.clone())
.await
.map(|(cid, _put_status)| cid)
}
/// Retrieves a block from the local blockstore, or starts fetching from the network or join an
/// already started fetch.
pub async fn get_block(&self, cid: &Cid) -> Result<Block, Error> {
self.repo.get_block(cid).instrument(self.span.clone()).await
}
/// Remove block from the ipfs repo.
pub async fn remove_block(&self, cid: Cid) -> Result<Cid, Error> {
self.repo
.remove_block(&cid)
.instrument(self.span.clone())
.await
}
/// Pins a given Cid
pub async fn pin_block(&self, cid: &Cid) -> Result<(), Error> {
self.repo.pin_block(cid).instrument(self.span.clone()).await
}
/// Unpins a given Cid
pub async fn unpin_block(&self, cid: &Cid) -> Result<(), Error> {
self.repo
.unpin_block(cid)
.instrument(self.span.clone())
.await
}
/// Checks whether a given block is pinned
pub async fn is_pinned(&self, cid: &Cid) -> Result<bool, Error> {
self.repo.is_pinned(cid).instrument(self.span.clone()).await
}
/// Puts an ipld dag node into the ipfs repo.
pub async fn put_dag(&self, ipld: Ipld) -> Result<Cid, Error> {
self.dag()
.put(ipld, Codec::DagCBOR)
.instrument(self.span.clone())
.await
}
/// Gets an ipld dag node from the ipfs repo.
pub async fn get_dag(&self, path: IpfsPath) -> Result<Ipld, Error> {
self.dag()
.get(path)
.instrument(self.span.clone())
.await
.map_err(Error::new)
}
/// Creates a stream which will yield the bytes of an UnixFS file from the root Cid, with the
/// optional file byte range. If the range is specified and is outside of the file, the stream
/// will end without producing any bytes.
///
/// To create an owned version of the stream, please use `ipfs::unixfs::cat` directly.
pub async fn cat_unixfs(
&self,
starting_point: impl Into<unixfs::StartingPoint>,
range: Option<Range<u64>>,
) -> Result<
impl Stream<Item = Result<Vec<u8>, unixfs::TraversalFailed>> + Send + '_,
unixfs::TraversalFailed,
> {
// convert early not to worry about the lifetime of parameter
let starting_point = starting_point.into();
unixfs::cat(self, starting_point, range)
.instrument(self.span.clone())
.await
}
/// Resolves a ipns path to an ipld path.
pub async fn resolve_ipns(&self, path: &IpfsPath, recursive: bool) -> Result<IpfsPath, Error> {
let ipns = self.ipns();
let mut resolved = ipns.resolve(path).await;
if recursive {
let mut previous = None;
while let Ok(ref res) = resolved {
if let Some(ref prev) = previous {
if prev == res {
break;
}
}
previous = Some(res.clone());
resolved = ipns.resolve(&res).await;
}
resolved
} else {
resolved
}
}
/// Publishes an ipld path.
pub async fn publish_ipns(&self, key: &PeerId, path: &IpfsPath) -> Result<IpfsPath, Error> {
self.ipns()
.publish(key, path)
.instrument(self.span.clone())
.await
}
/// Cancel an ipns path.
pub async fn cancel_ipns(&self, key: &PeerId) -> Result<(), Error> {
self.ipns().cancel(key).instrument(self.span.clone()).await
}
pub async fn connect(&self, target: MultiaddrWithPeerId) -> Result<(), Error> {
async move {
let (tx, rx) = oneshot_channel();
self.to_task
.clone()
.send(IpfsEvent::Connect(target, tx))
.await?;
let subscription = rx.await?;
if let Some(future) = subscription {
future.await.map_err(|e| anyhow!(e))
} else {
futures::future::ready(Err(anyhow!("Duplicate connection attempt"))).await
}
}
.instrument(self.span.clone())
.await
}
pub async fn addrs(&self) -> Result<Vec<(PeerId, Vec<Multiaddr>)>, Error> {
async move {
let (tx, rx) = oneshot_channel();
self.to_task.clone().send(IpfsEvent::Addresses(tx)).await?;
rx.await?
}
.instrument(self.span.clone())
.await
}
pub async fn addrs_local(&self) -> Result<Vec<Multiaddr>, Error> {
async move {
let (tx, rx) = oneshot_channel();
self.to_task.clone().send(IpfsEvent::Listeners(tx)).await?;
rx.await?
}
.instrument(self.span.clone())
.await
}
pub async fn peers(&self) -> Result<Vec<Connection>, Error> {
async move {
let (tx, rx) = oneshot_channel();
self.to_task
.clone()
.send(IpfsEvent::Connections(tx))
.await?;
rx.await?
}
.instrument(self.span.clone())
.await
}
pub async fn disconnect(&self, target: MultiaddrWithPeerId) -> Result<(), Error> {
async move {
let (tx, rx) = oneshot_channel();
self.to_task
.clone()
.send(IpfsEvent::Disconnect(target, tx))
.await?;
rx.await?
}
.instrument(self.span.clone())
.await
}
/// Returns the local node public key and the listened and externally visible addresses.
/// The addresses are suffixed with the P2p protocol containing the node's PeerId.
///
/// Public key can be converted to [`PeerId`].
pub async fn identity(&self) -> Result<(PublicKey, Vec<Multiaddr>), Error> {
async move {
let (tx, rx) = oneshot_channel();
self.to_task
.clone()
.send(IpfsEvent::GetAddresses(tx))
.await?;
let mut addresses = rx.await?;
let public_key = self.keys.get_ref().public();
let peer_id = public_key.clone().into_peer_id();
for addr in &mut addresses {
addr.push(Protocol::P2p(peer_id.clone().into()))
}
Ok((public_key, addresses))
}
.instrument(self.span.clone())
.await
}
/// Subscribes to a given topic. Can be done at most once without unsubscribing in the between.
/// The subscription can be unsubscribed by dropping the stream or calling
/// [`pubsub_unsubscribe`].
pub async fn pubsub_subscribe(&self, topic: String) -> Result<SubscriptionStream, Error> {
async move {
let (tx, rx) = oneshot_channel();
self.to_task
.clone()
.send(IpfsEvent::PubsubSubscribe(topic.clone(), tx))
.await?;
rx.await?
.ok_or_else(|| format_err!("already subscribed to {:?}", topic))
}
.instrument(self.span.clone())
.await
}
/// Publishes to the topic which may have been subscribed to earlier
pub async fn pubsub_publish(&self, topic: String, data: Vec<u8>) -> Result<(), Error> {
async move {
let (tx, rx) = oneshot_channel();
self.to_task
.clone()
.send(IpfsEvent::PubsubPublish(topic, data, tx))
.await?;
Ok(rx.await?)
}
.instrument(self.span.clone())
.await
}
/// Returns true if unsubscription was successful
pub async fn pubsub_unsubscribe(&self, topic: &str) -> Result<bool, Error> {
async move {
let (tx, rx) = oneshot_channel();
self.to_task
.clone()
.send(IpfsEvent::PubsubUnsubscribe(topic.into(), tx))
.await?;
Ok(rx.await?)
}
.instrument(self.span.clone())
.await
}
/// Returns all known pubsub peers with the optional topic filter
pub async fn pubsub_peers(&self, topic: Option<String>) -> Result<Vec<PeerId>, Error> {
async move {
let (tx, rx) = oneshot_channel();
self.to_task
.clone()
.send(IpfsEvent::PubsubPeers(topic, tx))
.await?;
Ok(rx.await?)
}
.instrument(self.span.clone())
.await
}
/// Returns all currently subscribed topics
pub async fn pubsub_subscribed(&self) -> Result<Vec<String>, Error> {
async move {
let (tx, rx) = oneshot_channel();
self.to_task
.clone()
.send(IpfsEvent::PubsubSubscribed(tx))
.await?;
Ok(rx.await?)
}
.instrument(self.span.clone())
.await
}
pub async fn bitswap_wantlist(
&self,
peer: Option<PeerId>,
) -> Result<Vec<(Cid, bitswap::Priority)>, Error> {
async move {
let (tx, rx) = oneshot_channel();
self.to_task
.clone()
.send(IpfsEvent::WantList(peer, tx))
.await?;
Ok(rx.await?)
}
.instrument(self.span.clone())
.await
}
pub async fn refs_local(&self) -> Result<Vec<Cid>, Error> {
self.repo.list_blocks().instrument(self.span.clone()).await
}
pub async fn bitswap_stats(&self) -> Result<BitswapStats, Error> {
async move {
let (tx, rx) = oneshot_channel();
self.to_task
.clone()
.send(IpfsEvent::BitswapStats(tx))
.await?;
Ok(rx.await?)
}
.instrument(self.span.clone())
.await
}
/// Add a given multiaddr as a listening address. Will fail if the address is unsupported, or
/// if it is already being listened on. Currently will invoke `Swarm::listen_on` internally,
/// keep the ListenerId for later `remove_listening_address` use in a HashMap.
///
/// The returned future will resolve on the first bound listening address when this is called
/// with `/ip4/0.0.0.0/...` or anything similar which will bound through multiple concrete
/// listening addresses.
///
/// Trying to add an unspecified listening address while any other listening address adding is
/// in progress will result in error.
///
/// Returns the bound multiaddress, which in the case of original containing an ephemeral port
/// has now been changed.
pub async fn add_listening_address(&self, addr: Multiaddr) -> Result<Multiaddr, Error> {
async move {
let (tx, rx) = oneshot_channel();
self.to_task
.clone()
.send(IpfsEvent::AddListeningAddress(addr, tx))
.await?;
rx.await?
}
.instrument(self.span.clone())
.await
}
/// Stop listening on a previously added listening address. Fails if the address is not being
/// listened to.
///
/// The removal of all listening addresses added through unspecified addresses is not supported.
pub async fn remove_listening_address(&self, addr: Multiaddr) -> Result<(), Error> {
async move {
let (tx, rx) = oneshot_channel();
self.to_task
.clone()
.send(IpfsEvent::RemoveListeningAddress(addr, tx))
.await?;
rx.await?
}
.instrument(self.span.clone())
.await
}
/// Obtain the addresses associated with the given `PeerId`; they are first searched for locally
/// and the DHT is used as a fallback: a `Kademlia::get_closest_peers(peer_id)` query is run and
/// when it's finished, the newly added DHT records are checked for the existence of the desired
/// `peer_id` and if it's there, the list of its known addresses is returned.
pub async fn find_peer(&self, peer_id: PeerId) -> Result<Vec<Multiaddr>, Error> {
async move {
let (tx, rx) = oneshot_channel();
self.to_task
.clone()
.send(IpfsEvent::FindPeer(peer_id.clone(), false, tx))
.await?;
match rx.await? {
Either::Left(addrs) if !addrs.is_empty() => return Ok(addrs),
Either::Left(_) => unreachable!(),
Either::Right(future) => {
future.await?;
let (tx, rx) = oneshot_channel();
self.to_task
.clone()
.send(IpfsEvent::FindPeer(peer_id.clone(), true, tx))
.await?;
match rx.await? {
Either::Left(addrs) if !addrs.is_empty() => return Ok(addrs),
_ => return Err(anyhow!("couldn't find peer {}", peer_id)),
}
}
}
}
.instrument(self.span.clone())
.await
}
/// Performs a DHT lookup for providers of a value to the given key.
pub async fn get_providers(&self, cid: Cid) -> Result<Vec<PeerId>, Error> {
let kad_result = async move {
let (tx, rx) = oneshot_channel();
self.to_task
.clone()
.send(IpfsEvent::GetProviders(cid, tx))
.await?;
Ok(rx.await?).map_err(|e: String| anyhow!(e))
}
.instrument(self.span.clone())
.await?
.await;
match kad_result {
Ok(KadResult::Peers(providers)) => Ok(providers),
Ok(_) => unreachable!(),
Err(e) => Err(anyhow!(e)),
}
}
/// Establishes the node as a provider of a block with the given Cid: it publishes a provider
/// record with the given key (Cid) and the node's PeerId to the peers closest to the key. The
/// publication of provider records is periodically repeated as per the interval specified in
/// `libp2p`'s `KademliaConfig`.
pub async fn provide(&self, cid: Cid) -> Result<(), Error> {
// don't provide things we don't actually have
if self.repo.get_block_now(&cid).await?.is_none() {
return Err(anyhow!(
"Error: block {} not found locally, cannot provide",
cid
));
}
let kad_result = async move {
let (tx, rx) = oneshot_channel();
self.to_task
.clone()
.send(IpfsEvent::Provide(cid, tx))
.await?;
rx.await?
}
.instrument(self.span.clone())
.await?
.await;
match kad_result {
Ok(KadResult::Complete) => Ok(()),
Ok(_) => unreachable!(),
Err(e) => Err(anyhow!(e)),
}
}
/// Returns a list of peers closest to the given `PeerId`, as suggested by the DHT. The
/// node must have at least one known peer in its routing table in order for the query
/// to return any values.
pub async fn get_closest_peers(&self, peer_id: PeerId) -> Result<Vec<PeerId>, Error> {
let kad_result = async move {
let (tx, rx) = oneshot_channel();
self.to_task
.clone()
.send(IpfsEvent::GetClosestPeers(peer_id, tx))
.await?;
Ok(rx.await?).map_err(|e: String| anyhow!(e))
}
.instrument(self.span.clone())
.await?
.await;
match kad_result {
Ok(KadResult::Peers(closest)) => Ok(closest),
Ok(_) => unreachable!(),
Err(e) => Err(anyhow!(e)),
}
}
/// Walk the given Iplds' links up to `max_depth` (or indefinitely for `None`). Will return
/// any duplicate trees unless `unique` is `true`.
///
/// More information and a `'static` lifetime version available at [`refs::iplds_refs`].
pub fn refs<'a, Iter>(
&'a self,
iplds: Iter,
max_depth: Option<u64>,
unique: bool,
) -> impl Stream<Item = Result<refs::Edge, ipld::BlockError>> + Send + 'a
where
Iter: IntoIterator<Item = (Cid, Ipld)> + 'a,
{
refs::iplds_refs(self, iplds, max_depth, unique)
}
/// Exit daemon.
pub async fn exit_daemon(self) {
// FIXME: this is a stopgap measure needed while repo is part of the struct Ipfs instead of
// the background task or stream. After that this could be handled by dropping.
self.repo.shutdown();
// ignoring the error because it'd mean that the background task had already been dropped
let _ = self.to_task.clone().try_send(IpfsEvent::Exit);
}
}
/// Background task of `Ipfs` created when calling `UninitializedIpfs::start`.
// The receivers are Fuse'd so that we don't have to manage state on them being exhausted.
struct IpfsFuture<Types: IpfsTypes> {
swarm: TSwarm<Types>,
repo_events: Fuse<Receiver<RepoEvent>>,
from_facade: Fuse<Receiver<IpfsEvent>>,
listening_addresses: HashMap<Multiaddr, (ListenerId, Option<Channel<Multiaddr>>)>,
}
impl<TRepoTypes: RepoTypes> IpfsFuture<TRepoTypes> {
/// Completes the adding of listening address by matching the new listening address `addr` to
/// the `self.listening_addresses` so that we can detect even the multiaddresses with ephemeral
/// ports.
fn complete_listening_address_adding(&mut self, addr: Multiaddr) {
let maybe_sender = match self.listening_addresses.get_mut(&addr) {
// matching a non-ephemeral is simpler
Some((_, maybe_sender)) => maybe_sender.take(),
None => {
// try finding an ephemeral binding on the same prefix
let mut matching_keys = self
.listening_addresses
.keys()
.filter(|right| could_be_bound_from_ephemeral(0, &addr, right))
.cloned();
let first = matching_keys.next();
if let Some(first) = first {
let second = matching_keys.next();
match (first, second) {
(first, None) => {
if let Some((id, maybe_sender)) =
self.listening_addresses.remove(&first)
{
self.listening_addresses.insert(addr.clone(), (id, None));
maybe_sender
} else {
unreachable!("We found a matching ephemeral key already, it must be in the listening_addresses")
}
}
(first, Some(second)) => {
// this is more complicated, but we are guarding
// against this in the from_facade match below
unreachable!(
"More than one matching [{}, {}] and {:?} for {}",
first,
second,
matching_keys.collect::<Vec<_>>(),
addr
);
}
}
} else {
// this case is hit when user asks for /ip4/0.0.0.0/tcp/0 for example, the
// libp2p will bound to multiple addresses but we will not get access in 0.19
// to their ListenerIds.
let first = self
.listening_addresses
.iter()
.filter(|(addr, _)| starts_unspecified(addr))
.filter(|(could_have_ephemeral, _)| {
could_be_bound_from_ephemeral(1, &addr, could_have_ephemeral)
})
// finally we want to make sure we only match on addresses which are yet to
// be reported back
.filter(|(_, (_, maybe_sender))| maybe_sender.is_some())
.map(|(addr, _)| addr.to_owned())
.next();
if let Some(first) = first {
let (id, maybe_sender) = self
.listening_addresses
.remove(&first)
.expect("just filtered this key out");
self.listening_addresses.insert(addr.clone(), (id, None));
trace!("guessing the first match for {} to be {}", first, addr);
maybe_sender
} else {
None
}
}
}
};
if let Some(sender) = maybe_sender {
let _ = sender.send(Ok(addr));
}
}
fn start_add_listener_address(&mut self, addr: Multiaddr, ret: Channel<Multiaddr>) {
use libp2p::Swarm;
use std::collections::hash_map::Entry;
if starts_unspecified(&addr)
&& self
.listening_addresses
.values()
.filter(|(_, maybe_sender)| maybe_sender.is_some())
.count()
> 0
{
let _ = ret.send(Err(format_err!("Cannot start listening to unspecified address when there are pending specified addresses awaiting")));
return;
}
match self.listening_addresses.entry(addr) {
Entry::Occupied(oe) => {
let _ = ret.send(Err(format_err!("Already adding a possibly ephemeral multiaddr, wait first one to resolve before adding next: {}", oe.key())));
}
Entry::Vacant(ve) => match Swarm::listen_on(&mut self.swarm, ve.key().to_owned()) {
Ok(id) => {