Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat(libp2p): add SwarmBuilder #4120

Merged
merged 186 commits into from
Oct 10, 2023
Merged
Show file tree
Hide file tree
Changes from 170 commits
Commits
Show all changes
186 commits
Select commit Hold shift + click to select a range
557d052
feat(libp2p): add `TransportBuilder`
mxinden Jun 26, 2023
90e53c0
Introduce BuildableTransport abstraction
mxinden Jun 30, 2023
fe1f3d3
Feature flag
mxinden Jun 30, 2023
a42f09a
Add OtherTransportBuilder
mxinden Jun 30, 2023
321f588
Fix order
mxinden Jun 30, 2023
4c11afc
Introduce SwarmBuilder
mxinden Jul 1, 2023
f8e0fe7
Add with_custom_tcp
mxinden Jul 8, 2023
343ba2d
Have with_other_transport take keypair closure
mxinden Jul 8, 2023
be22008
Fully qualify libp2p_swarm::NetworkBehaviour
mxinden Jul 8, 2023
44b9ac4
Use SwwarmBuilder in DCUtR example
mxinden Jul 8, 2023
eba4607
Remove resolved TODO
mxinden Jul 29, 2023
5c0593f
Remove custom TCP option
mxinden Jul 29, 2023
777542d
Add without_tcp option
mxinden Jul 29, 2023
bcf36ae
feat(core): add upgrade::Map
mxinden Jul 31, 2023
b301850
feat(swarm/builder): make authentication configurable
mxinden Jul 31, 2023
7acc531
Feature flag for relay
mxinden Jul 31, 2023
493bc8d
refactor(examples/ping): use `SwarmBuilder`
mxinden Jul 31, 2023
b5ed4ed
Rename to without_any_other_transports
mxinden Jul 31, 2023
17258af
Merge branch 'master' of https://github.com/libp2p/rust-libp2p into t…
mxinden Aug 12, 2023
43c9b36
feat: websocket support
mxinden Aug 12, 2023
e694bc9
Use macros for de-duplication
mxinden Aug 12, 2023
ffcffae
Fix tests
mxinden Aug 12, 2023
225771f
Allow configuring tcp
mxinden Aug 12, 2023
bcdaf41
Add shortcuts
mxinden Aug 12, 2023
fec404a
Update autonat examples
mxinden Aug 12, 2023
987dc11
Update chat examples
mxinden Aug 12, 2023
fc7c8f6
Fix dcutr example
mxinden Aug 12, 2023
499121b
Add shortcuts
mxinden Aug 12, 2023
e1acfa1
Update key value store example
mxinden Aug 12, 2023
eb54dda
Update file sharing example
mxinden Aug 12, 2023
0883641
Update metrics example
mxinden Aug 13, 2023
e05ccaf
Update libp2p identify example
mxinden Aug 13, 2023
e4abd6a
Update ipfs-kad example
mxinden Aug 13, 2023
7aff8ee
Update ipfs-private example
mxinden Aug 13, 2023
7a7e3c4
Update relay server
mxinden Aug 13, 2023
f4a4ca3
Update rendezvous examples
mxinden Aug 13, 2023
cb67678
Export as libp2p::SwarmBuilder
mxinden Aug 13, 2023
a6cf98f
Add shortcuts to skip without_any_other_transports
mxinden Aug 13, 2023
04a39c0
Error handling
mxinden Aug 13, 2023
1a5418d
Make with_behaviour fallible
mxinden Aug 18, 2023
e244c53
Add with_quic
mxinden Aug 18, 2023
9b78ca9
Merge branch 'master' of https://github.com/libp2p/rust-libp2p into t…
mxinden Aug 18, 2023
14606dd
Use with_quic
mxinden Aug 18, 2023
d3ffdd4
Introduce phases
mxinden Aug 20, 2023
faecb8b
Make without_ methods private whereever possible
mxinden Aug 21, 2023
bc7291b
Change phase order
mxinden Aug 21, 2023
711bfcb
Rename runtime to provider
mxinden Aug 21, 2023
12a22ed
Merge branch 'master' of https://github.com/libp2p/rust-libp2p into t…
mxinden Aug 21, 2023
1b1f49d
Avoid need for `Ok` wrapping behaviour when closure is infallible
thomaseizinger Aug 24, 2023
83a55e9
Apply global timeout of 10s
mxinden Aug 26, 2023
2b68727
feat(swarm): add SwarmConfig
mxinden Aug 26, 2023
4ad2a0e
Make `without_noise` on `TcpNoisePhase` private
mxinden Aug 27, 2023
c289ccc
Move pub use down
mxinden Aug 27, 2023
fb8f4b7
Deprecate development_transport
mxinden Aug 27, 2023
46a8bd9
Wrap errors
mxinden Aug 27, 2023
3dfb915
Make RelayNoisePhase without_noise private
mxinden Aug 27, 2023
9f2aa7f
Add example showcasing all features
mxinden Aug 27, 2023
37cb71a
Merge branch 'master' of https://github.com/libp2p/rust-libp2p into t…
mxinden Aug 27, 2023
e3ec84b
Add with_quic_config
mxinden Aug 27, 2023
4c20f83
refactor(misc/server): use new SwarmBuilder
mxinden Aug 27, 2023
19c401d
Use FnOnce instead of FnMut
mxinden Aug 27, 2023
642bae2
Feature gate most from wasm32
mxinden Aug 27, 2023
55dfaac
Fix clippy
mxinden Aug 27, 2023
5a49887
More feature flags
mxinden Aug 27, 2023
c6feb01
More feature flags
mxinden Aug 27, 2023
adc3180
More feature flags
mxinden Aug 27, 2023
6e760d7
Fix feature flag
mxinden Aug 27, 2023
8793498
Clippy
mxinden Aug 27, 2023
7393b8a
Clippy
mxinden Aug 27, 2023
f4cfa36
Merge branch 'master' of https://github.com/libp2p/rust-libp2p into t…
mxinden Sep 2, 2023
dec90c7
Make with_other_transport fallible
mxinden Sep 2, 2023
62d2c8a
Use SwarmBuilder in interop-tests
mxinden Sep 2, 2023
00dca91
Add WASM support
mxinden Sep 2, 2023
926a684
Simplify with_wasm_bindgen
mxinden Sep 2, 2023
9e53d1b
Remove wasm TODO
mxinden Sep 2, 2023
9edf25e
interop: remove mplex support
mxinden Sep 2, 2023
c0c6e9c
Update ping tutorial
mxinden Sep 2, 2023
f22a4ff
Add with_bandwidth_logging
mxinden Sep 3, 2023
01ea8eb
Shortcut for with_bandwidth_logging
mxinden Sep 3, 2023
8f2d043
Fix minor CI failures
mxinden Sep 3, 2023
bc9cf5f
Feature flag any(tls, noise)
mxinden Sep 3, 2023
32162a6
Use SwarmConfig
mxinden Sep 3, 2023
054c9d3
Typo
mxinden Sep 3, 2023
4f909c9
Don't build swarm
mxinden Sep 3, 2023
9f640f3
fmt
mxinden Sep 3, 2023
732072e
Bump versions and add changelog entries
mxinden Sep 3, 2023
0b74e3f
Fix relay tests
mxinden Sep 3, 2023
a39a177
Move upgrade::Map into builder/map.rs
mxinden Sep 3, 2023
97bf535
Bail on mplex
mxinden Sep 3, 2023
ce43526
Remove obsolete TODO
mxinden Sep 3, 2023
c6d580c
Feature flag map module
mxinden Sep 3, 2023
e497cb2
More feature flags
mxinden Sep 3, 2023
a80d726
Remove use for map
mxinden Sep 3, 2023
848f360
Make Upgrade::new pub(crate)
mxinden Sep 3, 2023
14954f0
Clippy
mxinden Sep 3, 2023
fa30561
Update libp2p/CHANGELOG.md
mxinden Sep 5, 2023
c6c8ca4
Update libp2p/src/lib.rs
mxinden Sep 7, 2023
aa19b1f
[WIP] with_tcp including sec and mux
mxinden Sep 16, 2023
14c199f
[WIP] add support for tls+noise and yamux+mplex
mxinden Sep 17, 2023
7f6da36
Be generic over provider
mxinden Sep 25, 2023
10b3bc1
Simplify tls and noise construction
mxinden Sep 25, 2023
1f310bb
Remove 1-tuple from security upgrade
thomaseizinger Sep 26, 2023
729416e
Resolve single tuple problem for muxer upgrade
thomaseizinger Sep 26, 2023
8dd8f37
Undo accidental change
thomaseizinger Sep 26, 2023
e9695cb
Merge branch 'master' into transport-builder
thomaseizinger Sep 26, 2023
0c1e4ef
Resolve some more warnings
thomaseizinger Sep 26, 2023
5ef58bb
Undo unnecessary changes
thomaseizinger Sep 26, 2023
41bc9b6
Merge branch 'master' of https://github.com/libp2p/rust-libp2p into t…
mxinden Sep 28, 2023
9d0538f
Remove unnecessary trait bounds on IntoSecurityUpgrade::Error
mxinden Sep 28, 2023
ca29c39
Adjust with_relay
mxinden Sep 28, 2023
82eb655
Adjust with_websocket
mxinden Sep 28, 2023
a60993d
Split builder.rs into separate files
mxinden Sep 30, 2023
4b052e5
Update upnp and browser webrtc
mxinden Sep 30, 2023
5faae59
Rename SwarmConfig to Config
mxinden Sep 30, 2023
4d7d3c6
Fix wasm compilation
mxinden Sep 30, 2023
46c00a2
More wasm compilation flags
mxinden Sep 30, 2023
ec42577
Fix ipfs-kad example
mxinden Sep 30, 2023
9f6950e
Remove reference to keep alive behaviour
mxinden Sep 30, 2023
3bcbca3
Fix example warning
mxinden Sep 30, 2023
288d964
cargo fmt
mxinden Sep 30, 2023
d8869e5
Fix doc tests
mxinden Sep 30, 2023
09e7bae
fix swarm test
mxinden Sep 30, 2023
f1ef2ec
Fix kad tests
mxinden Sep 30, 2023
1a2c540
Fix swarm config method names
mxinden Sep 30, 2023
c640929
Rename to with_relay_client
mxinden Oct 2, 2023
3845c23
Implement with_websocket for RelayPhase
mxinden Oct 2, 2023
4a8d38b
Rename to IdentityPhase
mxinden Oct 2, 2023
b135900
Introduce BehaviourError
mxinden Oct 2, 2023
b4e160b
Introduce TransportError
mxinden Oct 2, 2023
cb59522
Refactor nested quic macro
mxinden Oct 2, 2023
cc84f7c
Reword note on dummy transport usage
mxinden Oct 2, 2023
705b086
Rephase note on unnecessary tokio await
mxinden Oct 2, 2023
52ac76c
Seal TryInto traits
mxinden Oct 2, 2023
b1891b2
Merge branch 'master' of https://github.com/libp2p/rust-libp2p into t…
mxinden Oct 2, 2023
83e3674
Rename to providerPascalCase
mxinden Oct 2, 2023
9ee251f
interop: re-introduce mplex
mxinden Oct 2, 2023
3e34a65
Refactor websocket error handling
mxinden Oct 2, 2023
4853caf
Remove without_executor
mxinden Oct 2, 2023
fe79451
Rename new_with_config to new
mxinden Oct 2, 2023
80b8657
Reword libp2p changelog
mxinden Oct 2, 2023
63633dc
Reword swarm changelog
mxinden Oct 2, 2023
5828b9e
refactor(examples/dcutr): use tokio
mxinden Oct 2, 2023
2b680d6
Minor fixes
mxinden Oct 2, 2023
1fd5a5f
Have with_swarm_config take closure
mxinden Oct 3, 2023
4743616
Have with_quic_config take closure
mxinden Oct 3, 2023
7a8ee9b
Remove unwrap
mxinden Oct 3, 2023
e962f02
Remove duplicate local peer id print
mxinden Oct 3, 2023
358e7ff
Handle behaviour error
mxinden Oct 3, 2023
711d7b6
Handle behaviour error
mxinden Oct 3, 2023
99d7b6d
Ping idle connection timeout
mxinden Oct 3, 2023
9bd04c7
Interop remove separate yamux import
mxinden Oct 3, 2023
5a8c853
Use tls instead of libp2p-tls
mxinden Oct 3, 2023
371b380
Require errors to be 'static
mxinden Oct 3, 2023
a5dc83c
Extend license header
mxinden Oct 3, 2023
8c12ec5
Use libp2p_tcp::Config::default()
mxinden Oct 3, 2023
5f060b4
Fix bad merge
mxinden Oct 3, 2023
0058b02
Reduce diff
mxinden Oct 3, 2023
d57ceb0
Merge branch 'master' of https://github.com/libp2p/rust-libp2p into t…
mxinden Oct 3, 2023
e0a4a8e
Use new SwarmBuilder in examples/browser-webrtc wasm
mxinden Oct 3, 2023
20bdf2c
Update libp2p/src/tutorials/ping.rs
mxinden Oct 4, 2023
fa90d63
fmt
mxinden Oct 3, 2023
6be89c9
Use webrtc_websys module
mxinden Oct 4, 2023
04929db
Use with_tokio_executor
mxinden Oct 4, 2023
3717d1f
Re-introduce env_logger and fix idle timeout
mxinden Oct 4, 2023
bb91e8b
Remove duplicate peer id printing
mxinden Oct 4, 2023
5014087
Don't require StreamMuxerBox in with_other_transport
mxinden Oct 8, 2023
aec063d
fmt
mxinden Oct 8, 2023
7246971
Merge branch 'master' of https://github.com/libp2p/rust-libp2p into t…
mxinden Oct 8, 2023
19d4f21
Minor follow-ups
mxinden Oct 8, 2023
766c877
Fix wasm arch
mxinden Oct 8, 2023
6d737f6
Merge branch 'master' into transport-builder
thomaseizinger Oct 9, 2023
9afde03
Use #[allow(unused_imports)]
mxinden Oct 9, 2023
334589e
Remove obsolete peer id print
mxinden Oct 9, 2023
c150965
Don't unwrap
mxinden Oct 9, 2023
87808e2
Remove obsolete comment
mxinden Oct 9, 2023
e0029e4
Document with_tcp with_relay_client with_websocket taking function po…
mxinden Oct 9, 2023
1df30f3
Merge branch 'master' of https://github.com/libp2p/rust-libp2p into t…
mxinden Oct 9, 2023
a015706
Fix intra-doc link
mxinden Oct 9, 2023
1adf920
Merge branch 'master' into transport-builder
thomaseizinger Oct 10, 2023
a8351da
Merge branch 'master' into transport-builder
thomaseizinger Oct 10, 2023
59409d3
Reduce diff
thomaseizinger Oct 10, 2023
4eee7af
Reduce diff
thomaseizinger Oct 10, 2023
01fbf43
Fix bug sec protocol selection
thomaseizinger Oct 10, 2023
88d4361
Configure idle-connection timeout
thomaseizinger Oct 10, 2023
e3cc656
Merge branch 'master' into transport-builder
thomaseizinger Oct 10, 2023
06ba925
Fix interop config bug
thomaseizinger Oct 10, 2023
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 8 additions & 2 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

4 changes: 2 additions & 2 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -71,7 +71,7 @@ rust-version = "1.65.0"

[workspace.dependencies]
futures-bounded = { version = "0.1.0", path = "misc/futures-bounded" }
libp2p = { version = "0.52.3", path = "libp2p" }
libp2p = { version = "0.52.4", path = "libp2p" }
libp2p-allow-block-list = { version = "0.2.0", path = "misc/allow-block-list" }
libp2p-autonat = { version = "0.11.0", path = "protocols/autonat" }
libp2p-connection-limits = { version = "0.2.1", path = "misc/connection-limits" }
Expand Down Expand Up @@ -100,7 +100,7 @@ libp2p-rendezvous = { version = "0.13.0", path = "protocols/rendezvous" }
libp2p-upnp = { version = "0.1.1", path = "protocols/upnp" }
libp2p-request-response = { version = "0.25.1", path = "protocols/request-response" }
libp2p-server = { version = "0.12.3", path = "misc/server" }
libp2p-swarm = { version = "0.43.5", path = "swarm" }
libp2p-swarm = { version = "0.43.6", path = "swarm" }
libp2p-swarm-derive = { version = "0.33.0", path = "swarm-derive" }
libp2p-swarm-test = { version = "0.2.0", path = "swarm-test" }
libp2p-tcp = { version = "0.40.0", path = "transports/tcp" }
Expand Down
26 changes: 12 additions & 14 deletions examples/autonat/src/bin/autonat_client.rs
Original file line number Diff line number Diff line change
Expand Up @@ -21,10 +21,10 @@
#![doc = include_str!("../../README.md")]

use clap::Parser;
use futures::prelude::*;
use futures::StreamExt;
use libp2p::core::multiaddr::Protocol;
use libp2p::core::{upgrade::Version, Multiaddr, Transport};
use libp2p::swarm::{NetworkBehaviour, SwarmBuilder, SwarmEvent};
use libp2p::core::Multiaddr;
use libp2p::swarm::{NetworkBehaviour, SwarmEvent};
use libp2p::{autonat, identify, identity, noise, tcp, yamux, PeerId};
use std::error::Error;
use std::net::Ipv4Addr;
Expand All @@ -49,18 +49,16 @@ async fn main() -> Result<(), Box<dyn Error>> {

let opt = Opt::parse();

let local_key = identity::Keypair::generate_ed25519();
let local_peer_id = PeerId::from(local_key.public());
let mut swarm = libp2p::SwarmBuilder::with_new_identity()
.with_tokio()
.with_tcp(
tcp::Config::default(),
noise::Config::new,
yamux::Config::default,
)?
.with_behaviour(|key| Behaviour::new(key.public()))?
.build();

let transport = tcp::tokio::Transport::default()
.upgrade(Version::V1Lazy)
.authenticate(noise::Config::new(&local_key)?)
.multiplex(yamux::Config::default())
.boxed();

let behaviour = Behaviour::new(local_key.public());

let mut swarm = SwarmBuilder::with_tokio_executor(transport, behaviour, local_peer_id).build();
swarm.listen_on(
Multiaddr::empty()
.with(Protocol::Ip4(Ipv4Addr::UNSPECIFIED))
Expand Down
28 changes: 13 additions & 15 deletions examples/autonat/src/bin/autonat_server.rs
Original file line number Diff line number Diff line change
Expand Up @@ -21,10 +21,10 @@
#![doc = include_str!("../../README.md")]

use clap::Parser;
use futures::prelude::*;
use libp2p::core::{multiaddr::Protocol, upgrade::Version, Multiaddr, Transport};
use libp2p::swarm::{NetworkBehaviour, SwarmBuilder, SwarmEvent};
use libp2p::{autonat, identify, identity, noise, tcp, yamux, PeerId};
use futures::StreamExt;
use libp2p::core::{multiaddr::Protocol, Multiaddr};
use libp2p::swarm::{NetworkBehaviour, SwarmEvent};
use libp2p::{autonat, identify, identity, noise, tcp, yamux};
use std::error::Error;
use std::net::Ipv4Addr;

Expand All @@ -41,18 +41,16 @@ async fn main() -> Result<(), Box<dyn Error>> {

let opt = Opt::parse();

let local_key = identity::Keypair::generate_ed25519();
let local_peer_id = PeerId::from(local_key.public());
let mut swarm = libp2p::SwarmBuilder::with_new_identity()
.with_tokio()
.with_tcp(
tcp::Config::default(),
noise::Config::new,
yamux::Config::default,
)?
.with_behaviour(|key| Behaviour::new(key.public()))?
.build();

let transport = tcp::tokio::Transport::default()
.upgrade(Version::V1Lazy)
.authenticate(noise::Config::new(&local_key)?)
.multiplex(yamux::Config::default())
.boxed();

let behaviour = Behaviour::new(local_key.public());

let mut swarm = SwarmBuilder::with_tokio_executor(transport, behaviour, local_peer_id).build();
swarm.listen_on(
Multiaddr::empty()
.with(Protocol::Ip4(Ipv4Addr::UNSPECIFIED))
Expand Down
20 changes: 9 additions & 11 deletions examples/browser-webrtc/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ use libp2p::core::Multiaddr;
use libp2p::identity::{Keypair, PeerId};
use libp2p::ping;
use libp2p::swarm::{keep_alive, NetworkBehaviour, SwarmBuilder, SwarmEvent};
use libp2p::webrtc_websys;
use std::convert::From;
use std::io;
use wasm_bindgen::prelude::*;
Expand All @@ -18,19 +19,16 @@ pub async fn run(libp2p_endpoint: String) -> Result<(), JsError> {
let body = Body::from_current_window()?;
body.append_p("Let's ping the WebRTC Server!")?;

let local_key = Keypair::generate_ed25519();
let local_peer_id = PeerId::from(local_key.public());
let mut swarm = SwarmBuilder::with_wasm_executor(
libp2p_webrtc_websys::Transport::new(libp2p_webrtc_websys::Config::new(&local_key)).boxed(),
Behaviour {
let swarm = libp2p::SwarmBuilder::with_new_identity()
.with_wasm_bindgen()
.with_other_transport(|key| {
webrtc_websys::Transport::new(webrtc_websys::Config::new(&key))
})?
.with_behaviour(|_| Behaviour {
ping: ping::Behaviour::new(ping::Config::new()),
keep_alive: keep_alive::Behaviour,
},
local_peer_id,
)
.build();

log::info!("Initialize swarm with identity: {local_peer_id}");
})?
.build();

let addr = libp2p_endpoint.parse::<Multiaddr>()?;
log::info!("Dialing {addr}");
Expand Down
32 changes: 17 additions & 15 deletions examples/browser-webrtc/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -10,10 +10,9 @@ use futures::StreamExt;
use libp2p::{
core::muxing::StreamMuxerBox,
core::Transport,
identity,
multiaddr::{Multiaddr, Protocol},
ping,
swarm::{SwarmBuilder, SwarmEvent},
swarm::SwarmEvent,
};
use libp2p_webrtc as webrtc;
use rand::thread_rng;
Expand All @@ -28,19 +27,22 @@ async fn main() -> anyhow::Result<()> {
.parse_default_env()
.init();

let id_keys = identity::Keypair::generate_ed25519();
let local_peer_id = id_keys.public().to_peer_id();
let transport = webrtc::tokio::Transport::new(
id_keys,
webrtc::tokio::Certificate::generate(&mut thread_rng())?,
)
.map(|(peer_id, conn), _| (peer_id, StreamMuxerBox::new(conn)))
.boxed();

let mut swarm =
SwarmBuilder::with_tokio_executor(transport, ping::Behaviour::default(), local_peer_id)
.idle_connection_timeout(Duration::from_secs(30)) // Allows us to observe the pings.
.build();
let mut swarm = libp2p::SwarmBuilder::with_new_identity()
.with_tokio()
.with_other_transport(|id_keys| {
Ok(webrtc::tokio::Transport::new(
id_keys.clone(),
webrtc::tokio::Certificate::generate(&mut thread_rng())?,
)
.map(|(peer_id, conn), _| (peer_id, StreamMuxerBox::new(conn))))
})?
.with_behaviour(|_| ping::Behaviour::default())?
.with_swarm_config(|cfg| {
cfg.with_idle_connection_timeout(
Duration::from_secs(30), // Allows us to observe the pings.
)
})
.build();

let address_webrtc = Multiaddr::from(Ipv4Addr::UNSPECIFIED)
.with(Protocol::Udp(0))
Expand Down
88 changes: 35 additions & 53 deletions examples/chat/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -20,14 +20,8 @@

#![doc = include_str!("../README.md")]

use futures::{future::Either, stream::StreamExt};
use libp2p::{
core::{muxing::StreamMuxerBox, transport::OrTransport, upgrade},
gossipsub, identity, mdns, noise, quic,
swarm::NetworkBehaviour,
swarm::{SwarmBuilder, SwarmEvent},
tcp, yamux, PeerId, Transport,
};
use futures::stream::StreamExt;
use libp2p::{gossipsub, mdns, noise, swarm::NetworkBehaviour, swarm::SwarmEvent, tcp, yamux};
use std::collections::hash_map::DefaultHasher;
use std::error::Error;
use std::hash::{Hash, Hasher};
Expand All @@ -43,58 +37,46 @@ struct MyBehaviour {

#[tokio::main]
async fn main() -> Result<(), Box<dyn Error>> {
// Create a random PeerId
env_logger::init();
let id_keys = identity::Keypair::generate_ed25519();
let local_peer_id = PeerId::from(id_keys.public());
let mut swarm = libp2p::SwarmBuilder::with_new_identity()
.with_tokio()
.with_tcp(
tcp::Config::default(),
noise::Config::new,
yamux::Config::default,
)?
.with_quic()
.with_behaviour(|key| {
// To content-address message, we can take the hash of message and use it as an ID.
let message_id_fn = |message: &gossipsub::Message| {
let mut s = DefaultHasher::new();
message.data.hash(&mut s);
gossipsub::MessageId::from(s.finish().to_string())
};

// Set up an encrypted DNS-enabled TCP Transport over the yamux protocol.
let tcp_transport = tcp::tokio::Transport::new(tcp::Config::default().nodelay(true))
.upgrade(upgrade::Version::V1Lazy)
.authenticate(noise::Config::new(&id_keys).expect("signing libp2p-noise static keypair"))
.multiplex(yamux::Config::default())
.timeout(std::time::Duration::from_secs(20))
.boxed();
let quic_transport = quic::tokio::Transport::new(quic::Config::new(&id_keys));
let transport = OrTransport::new(quic_transport, tcp_transport)
.map(|either_output, _| match either_output {
Either::Left((peer_id, muxer)) => (peer_id, StreamMuxerBox::new(muxer)),
Either::Right((peer_id, muxer)) => (peer_id, StreamMuxerBox::new(muxer)),
})
.boxed();
// Set a custom gossipsub configuration
let gossipsub_config = gossipsub::ConfigBuilder::default()
.heartbeat_interval(Duration::from_secs(10)) // This is set to aid debugging by not cluttering the log space
.validation_mode(gossipsub::ValidationMode::Strict) // This sets the kind of message validation. The default is Strict (enforce message signing)
.message_id_fn(message_id_fn) // content-address messages. No two messages of the same content will be propagated.
.build()
.map_err(|msg| io::Error::new(io::ErrorKind::Other, msg))?; // Temporary hack because `build` does not return a proper `std::error::Error`.

// To content-address message, we can take the hash of message and use it as an ID.
let message_id_fn = |message: &gossipsub::Message| {
let mut s = DefaultHasher::new();
message.data.hash(&mut s);
gossipsub::MessageId::from(s.finish().to_string())
};
// build a gossipsub network behaviour
let gossipsub = gossipsub::Behaviour::new(
gossipsub::MessageAuthenticity::Signed(key.clone()),
gossipsub_config,
)?;

// Set a custom gossipsub configuration
let gossipsub_config = gossipsub::ConfigBuilder::default()
.heartbeat_interval(Duration::from_secs(10)) // This is set to aid debugging by not cluttering the log space
.validation_mode(gossipsub::ValidationMode::Strict) // This sets the kind of message validation. The default is Strict (enforce message signing)
.message_id_fn(message_id_fn) // content-address messages. No two messages of the same content will be propagated.
.build()
.expect("Valid config");
let mdns =
mdns::tokio::Behaviour::new(mdns::Config::default(), key.public().to_peer_id())?;
Ok(MyBehaviour { gossipsub, mdns })
})?
.build();

// build a gossipsub network behaviour
let mut gossipsub = gossipsub::Behaviour::new(
gossipsub::MessageAuthenticity::Signed(id_keys),
gossipsub_config,
)
.expect("Correct configuration");
// Create a Gossipsub topic
let topic = gossipsub::IdentTopic::new("test-net");
// subscribes to our topic
gossipsub.subscribe(&topic)?;

// Create a Swarm to manage peers and events
let mut swarm = {
let mdns = mdns::tokio::Behaviour::new(mdns::Config::default(), local_peer_id)?;
let behaviour = MyBehaviour { gossipsub, mdns };
SwarmBuilder::with_tokio_executor(transport, behaviour, local_peer_id).build()
};
swarm.behaviour_mut().gossipsub.subscribe(&topic)?;

// Read full lines from stdin
let mut stdin = io::BufReader::new(io::stdin()).lines();
Expand Down
3 changes: 2 additions & 1 deletion examples/dcutr/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -10,5 +10,6 @@ clap = { version = "4.3.23", features = ["derive"] }
env_logger = "0.10.0"
futures = "0.3.28"
futures-timer = "3.0"
libp2p = { path = "../../libp2p", features = ["async-std", "dns", "dcutr", "identify", "macros", "noise", "ping", "quic", "relay", "rendezvous", "tcp", "tokio", "yamux"] }
libp2p = { path = "../../libp2p", features = ["dns", "dcutr", "identify", "macros", "noise", "ping", "quic", "relay", "rendezvous", "tcp", "tokio", "yamux"] }
log = "0.4"
tokio = { version = "1.29", features = ["macros", "net", "rt", "signal"] }
Loading
Loading