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

protocols/relay: Implement circuit relay v2 protocol #2059

Merged
merged 129 commits into from
Jan 14, 2022
Merged
Show file tree
Hide file tree
Changes from 110 commits
Commits
Show all changes
129 commits
Select commit Hold shift + click to select a range
3bd6602
protocols/relay: Implement circuit relay v2 protocol
mxinden Apr 16, 2021
125e3c3
misc/multistream-select: Ignore simultaneous open 'iamclient'
mxinden Apr 26, 2021
4281bd5
protocols/relay: Ensure connections of HOP connect are kept alive
mxinden Apr 30, 2021
778512d
protocols/relay: Improve documentation
mxinden May 3, 2021
dfe1285
protocols/relay: Implement v2 client logic
mxinden May 8, 2021
ca19fe4
Merge branch 'libp2p/master' into relay-v2
mxinden May 16, 2021
59c8741
protocols/relay: Handle dial failure
mxinden May 16, 2021
54cc9db
protocols/relay: Reuse connection
mxinden May 16, 2021
8e7b6a0
protocols/relay: Rename Connection to RelayedConnection
mxinden May 17, 2021
a1589cc
protocols/relay: Update transport doc examples
mxinden May 17, 2021
4af855e
protocols/relay: Pass relay addr to transport
mxinden May 17, 2021
8934664
protocols/relay: Implement inbound stop denial
mxinden May 18, 2021
79fd6be
protocols/relay: Renew reservations
mxinden May 18, 2021
0ed3153
protocols/relay: Handle invalid expiration in the past
mxinden May 18, 2021
1318636
protocols/relay: Handle in and outbound failure
mxinden May 18, 2021
5df655e
protocols/relay: Implement client handler keep alive
mxinden May 18, 2021
643ffb0
protocols/relay: Handle handler listener closed channel
mxinden May 19, 2021
570980d
protocols/relay: Handle handler to listener failure
mxinden May 19, 2021
037a398
protocols/relay: Return all new listener addresses
mxinden May 19, 2021
806fd93
protocols/relay/v2: Update to latest protobuf definition
mxinden Jul 1, 2021
5b170d7
Merge branch 'libp2p/master' into relay-v2
mxinden Jul 1, 2021
1723e92
Revert "misc/multistream-select: Ignore simultaneous open 'iamclient'"
mxinden Jul 2, 2021
cfcb810
Merge branch 'libp2p/master' into relay-v2
mxinden Jul 9, 2021
ea53ad7
protocols/relay/v2: Report back to transport
mxinden Jul 9, 2021
599aa09
protocols/relay/v2: Disconnect when stop protocol not supported
mxinden Jul 9, 2021
0b8d54c
protocols/relay/v2: Document max_duration not exceed u32::MAX
mxinden Jul 9, 2021
3082efb
protocols/relay/v2: Don't append p2p-circuit as relay
mxinden Jul 9, 2021
5f073c6
protocols/relay/v2: Implement rate limiter
mxinden Jul 11, 2021
fdacc1b
protocols/relay/v2: Document caveats on rate limiter with high volume
mxinden Jul 21, 2021
93f0979
protocols/relay: Prevent possible false positive in quickcheck
mxinden Jul 21, 2021
334ffc6
protocols/relay: Reword Prost error message
mxinden Jul 21, 2021
8803bd0
protocols/relay: Allow users to specify generic rate limiters
mxinden Jul 21, 2021
c51f9e2
protocols/relay: Move rate limiting logic into module
mxinden Jul 22, 2021
8777d70
protocols/relay: Prevent reservation and connection over relayed conn
mxinden Jul 22, 2021
4e5f99d
protocols/relay: Add circuit src rate limiting
mxinden Jul 22, 2021
d55a5b9
protocols/relay/v2: Simplify example
mxinden Jul 22, 2021
e5f63bc
protocols/relay: Add myself to authors
mxinden Jul 22, 2021
f8d0047
protocols/relay: Use thiserror
mxinden Jul 22, 2021
55dd0a2
protocols/relay/v2: Set rate limits
mxinden Jul 22, 2021
7e11439
Merge branch 'libp2p/master' into relay-v2
mxinden Jul 22, 2021
126f971
protocols/relay: Use wasm_timer::Instant
mxinden Jul 22, 2021
75f5616
protocols/relay/v2: Apply clippy suggestions
mxinden Jul 22, 2021
6dc961a
protocols/relay: Fix intra doc link
mxinden Jul 22, 2021
2ef7050
Merge branch 'libp2p/master' into relay-v2
mxinden Jul 23, 2021
b07257d
Merge branch 'libp2p/master' into relay-v2
mxinden Jul 28, 2021
31f8424
protocols/relay: Fix clippy warnings
mxinden Jul 28, 2021
8dc98bf
Merge branch 'libp2p/master' into relay-v2
mxinden Aug 13, 2021
cfa459d
Merge branch 'libp2p/master' into relay-v2
mxinden Aug 23, 2021
7e51e54
Merge branch 'libp2p/master' into relay-v2
mxinden Sep 26, 2021
832f069
Merge branch 'libp2p/master' into relay-v2
mxinden Oct 7, 2021
2c79813
misc/metrics: Add basic instrumentation for libp2p-relay
mxinden Oct 7, 2021
fa82385
Merge branch 'libp2p/master' into relay-v2
mxinden Nov 18, 2021
d51fa72
protocols/relay: Return NetworkBehaviourAction::NotifyHandler right away
mxinden Nov 19, 2021
c742335
protocols/relay: Run rust fmt
mxinden Nov 20, 2021
0780206
Merge branch 'master' into relay-v2
mxinden Nov 25, 2021
69b2fc1
protocols/relay/src/v2/relay: Accept mutable config
mxinden Nov 20, 2021
580f668
protocols/relay/examples: Structure command line args
r-zig Nov 4, 2021
7c9f3bc
protocols/relay/src/v2/client: Return NetworkBehaviourAction on Liste…
mxinden Dec 7, 2021
ad79422
Refactor suggestion
MarcoPolo Dec 6, 2021
517075d
protocols/relay/src/v2/client/handler: Check status of lend out subst…
mxinden Dec 7, 2021
da7f5e4
protocols/relay/src/v2/client: Use void::Void for drop_notifer
mxinden Dec 7, 2021
45163df
protocols/relay/src/v2/client/handler: Log dropped oneshot Sender to …
mxinden Dec 7, 2021
1d20392
protocols/relay/src/v2/client/handler: Await send call to transport l…
mxinden Dec 7, 2021
395f43a
protocols/relay/src/v2/client/handler: Remove unnecessary boxing
mxinden Dec 7, 2021
2de96d6
Merge branch 'libp2p/master' into relay-v2
mxinden Dec 7, 2021
c0c0880
protocols/relay/src/v2/client: Extend unreacheable! text
mxinden Dec 9, 2021
746c75e
protocols/relay/src/v2/: Document pending_error and send_error_futs
mxinden Dec 9, 2021
08d6637
protocols/relay/src/v2: Use OrTransport
mxinden Dec 9, 2021
bfd92a1
protocols/relay/src/v2: Fix typo
mxinden Dec 9, 2021
a60ffba
protocols/relay/src/v2: Renew reservation after 3/4 of expiration
mxinden Dec 9, 2021
1123952
protocols/relay/v2: Use AcceptReservationReqBuilder concept
mxinden Dec 8, 2021
1af928a
protocols/relay: Capitalize I in NoAddressesInReservation
mxinden Dec 12, 2021
a9d9b41
misc/metrics: Derive Debug for event types
mxinden Dec 12, 2021
a8f21ae
protocols/relay/src/v2/client/handler: Consistent mpsc and oneshot im…
mxinden Dec 12, 2021
daa0686
protocols/relay/src/v2/client/transport: Loop on from_behaviour
mxinden Dec 12, 2021
8856fde
protocols/relay: Fix intra doc link
mxinden Dec 12, 2021
a1fad8c
protocols/relay/: Allow large enum variant
mxinden Dec 12, 2021
5d9f95a
protocols/relay/src/v2/client/transport: Remove destination address
mxinden Dec 13, 2021
eaab34e
protocols/relay/src/v2: Don't override NetworkBehaviour methods with …
mxinden Dec 13, 2021
26aaa6e
protocols/relay/src/v2/client: Pass event at handler initialization
mxinden Dec 13, 2021
49a6327
protocols/relay/src/v2: Use lent instead of lend
mxinden Dec 13, 2021
2e4e743
protocols/relay/v2: Use Renewing instead of Renewal
mxinden Dec 13, 2021
bce3ba0
protocols/relay/src/v2/client: Introduce Reservation::None
thomaseizinger Dec 8, 2021
01e12f7
protocols/relay/src/v2: Fix intra doc link
mxinden Dec 13, 2021
b1646f4
Merge branch 'libp2p/master' into relay-v2
mxinden Dec 13, 2021
912d314
protocols/relay/src/v2/client/handler: Inject event at creation time
mxinden Dec 15, 2021
dbfe25b
protocols/relay/src/v2/client/handler: Refactor Reservation::poll
MarcoPolo Dec 15, 2021
c09861b
protocols/relay/src/v2/client/handler.rs: Fix typo
mxinden Dec 16, 2021
5afa13b
protocols/relay/src/v2/client/transport.rs: Make doc examples consistent
mxinden Dec 16, 2021
9a0f886
protocols/relay/src/v2: Stress required usage of other Transport
mxinden Dec 16, 2021
a15bf3d
protocols/relay/src/v2/protocol/inbound_stop.rs: Remove src_peer_id p…
mxinden Dec 16, 2021
7b2eeb5
protocols/relay/src/v2/relay/handler: Remove wrong unused variable as…
mxinden Dec 16, 2021
8e6ce38
protocols/relay/src/v2/client: Garbage collect unconnected nodes
mxinden Dec 17, 2021
451d86c
protocols/relay/src/v2: Prevent nested relay on incoming relayed conn
mxinden Dec 17, 2021
a0750ef
protocols/relay/tests/v2: Test new reservation replacing old
mxinden Dec 17, 2021
4b90626
protocols/relay/src/v2: Close listener when channel from behaviour dr…
mxinden Dec 17, 2021
45f7e21
protocols/relay/src/v2: Expose connection limit via OutEvent
mxinden Dec 17, 2021
1b5cb8e
protocols/relay/v2: Use Option::transpose
mxinden Dec 17, 2021
2f5b8e6
protocols/relay/src/v2: Rework outbound_hop error types
mxinden Dec 17, 2021
a056b4b
protocols/relay/src/v2/client: Queue Event and not Action
mxinden Dec 18, 2021
7a4cf0a
protocols/relay/src/v2/client: Remove loop in NetworkBehaviour::poll
mxinden Dec 18, 2021
ed79c72
protocols/relay/src/v2/client/: Refactor parse_relayed_multiaddr
mxinden Dec 18, 2021
0b6aca3
protocols/relay/src/v2: Use ready! in RelayListener as Stream
mxinden Dec 18, 2021
0e17512
protocols/relay/src/v2: Remove unnecessary else
mxinden Dec 18, 2021
be9b94e
protocols/relay/src/v2/protocol: Use Vec::with_capacity
mxinden Dec 18, 2021
b9eb0f0
protocols/relay/src/v2: Separate error paths and happy path
mxinden Dec 18, 2021
93691a8
protocols/relay/src/v2/copy_future.rs: Add unit tests
mxinden Dec 18, 2021
0cdb1b6
protocols/relay/src/v2/relay: Remove unnecessary unwrap_or
mxinden Dec 18, 2021
b68f5a2
Merge remote-tracking branch 'libp2p/master' into relay-v2
mxinden Dec 19, 2021
040909e
protocols/relay/src/v2: Use ConnectedPoint::is_relayed
mxinden Dec 19, 2021
d5ee477
protocols/relay/src/v2: Make reservation expiration required
mxinden Dec 19, 2021
3627610
protocols/relay/src/v2: Refactor inbound_stop error handling
mxinden Dec 21, 2021
9a4ad18
protocols/relay/src/v2: Refactor outbound_stop error handling
mxinden Dec 21, 2021
2aa6e94
protocols/relay/src/v2: Refactor inbound_hop error handling
mxinden Dec 21, 2021
6916384
misc/metrics/src/relay: Update to error handling refactoring
mxinden Dec 21, 2021
8aa3867
Separate control flow as much as possible
thomaseizinger Dec 19, 2021
ca5aaed
protocols/relay/src/v2: Implement max_reservations_per_peer
mxinden Dec 21, 2021
48f7f68
protocols/relay/src/v2: Implement max_circuits_per_peer
mxinden Dec 21, 2021
58daa47
protocols/relay/src/v2: Deny duplicate reservation denial
mxinden Dec 21, 2021
00c98d5
Merge branch 'libp2p/master' into relay-v2
mxinden Dec 21, 2021
14e7912
Merge branch 'mxinden/relay-v2' into relay-v2-refactor-error
mxinden Dec 27, 2021
3f8e772
protocols/relay/src/v2: Use DummyProtocolsHandler on relayed connection
mxinden Dec 29, 2021
b6dbf82
Merge branch 'libp2p/master' into relay-v2
mxinden Dec 29, 2021
80a9e76
protocols/relay/tests/v2: Use wait_for_dial to ensure connection reuse
mxinden Jan 14, 2022
b1cb684
protocols/relay/: Only emit CircuitEstablished when transport notified
mxinden Jan 14, 2022
4212777
Merge branch 'libp2p/master' into relay-v2
mxinden Jan 14, 2022
00dbcc8
protocols/relay-src/v2: Fix Rust fmt complaint
mxinden Jan 14, 2022
56ce0a3
Merge branch 'master' into relay-v2
mxinden Jan 14, 2022
ab619c9
Merge branch 'master' into relay-v2
mxinden Jan 14, 2022
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
2 changes: 1 addition & 1 deletion Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -48,7 +48,7 @@ noise = ["libp2p-noise"]
ping = ["libp2p-ping", "libp2p-metrics/ping"]
plaintext = ["libp2p-plaintext"]
pnet = ["libp2p-pnet"]
relay = ["libp2p-relay"]
relay = ["libp2p-relay", "libp2p-metrics/relay"]
request-response = ["libp2p-request-response"]
rendezvous = ["libp2p-rendezvous"]
tcp-async-io = ["libp2p-tcp", "libp2p-tcp/async-io"]
Expand Down
2 changes: 2 additions & 0 deletions misc/metrics/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -15,13 +15,15 @@ gossipsub = ["libp2p-gossipsub"]
identify = ["libp2p-identify"]
kad = ["libp2p-kad"]
ping = ["libp2p-ping"]
relay = ["libp2p-relay"]

[dependencies]
libp2p-core = { version = "0.31.0", path = "../../core" }
libp2p-gossipsub = { version = "0.35.0", path = "../../protocols/gossipsub", optional = true }
libp2p-identify = { version = "0.33.0", path = "../../protocols/identify", optional = true }
libp2p-kad = { version = "0.34.0", path = "../../protocols/kad", optional = true }
libp2p-ping = { version = "0.33.0", path = "../../protocols/ping", optional = true }
libp2p-relay = { version = "0.6.0", path = "../../protocols/relay", optional = true }
libp2p-swarm = { version = "0.33.0", path = "../../swarm" }
open-metrics-client = "0.13.0"

Expand Down
6 changes: 6 additions & 0 deletions misc/metrics/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,8 @@ mod identify;
mod kad;
#[cfg(feature = "ping")]
mod ping;
#[cfg(feature = "relay")]
mod relay;
mod swarm;

use open_metrics_client::registry::Registry;
Expand All @@ -47,6 +49,8 @@ pub struct Metrics {
kad: kad::Metrics,
#[cfg(feature = "ping")]
ping: ping::Metrics,
#[cfg(feature = "relay")]
relay: relay::Metrics,
swarm: swarm::Metrics,
}

Expand All @@ -70,6 +74,8 @@ impl Metrics {
kad: kad::Metrics::new(sub_registry),
#[cfg(feature = "ping")]
ping: ping::Metrics::new(sub_registry),
#[cfg(feature = "relay")]
relay: relay::Metrics::new(sub_registry),
swarm: swarm::Metrics::new(sub_registry),
}
}
Expand Down
106 changes: 106 additions & 0 deletions misc/metrics/src/relay.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,106 @@
// Copyright 2021 Protocol Labs.
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the "Software"),
// to deal in the Software without restriction, including without limitation
// the rights to use, copy, modify, merge, publish, distribute, sublicense,
// and/or sell copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.

use open_metrics_client::encoding::text::Encode;
use open_metrics_client::metrics::counter::Counter;
use open_metrics_client::metrics::family::Family;
use open_metrics_client::registry::Registry;

pub struct Metrics {
events: Family<EventLabels, Counter>,
}

impl Metrics {
pub fn new(registry: &mut Registry) -> Self {
let sub_registry = registry.sub_registry_with_prefix("relay");

let events = Family::default();
sub_registry.register(
"events",
"Events emitted by the relay NetworkBehaviour",
Box::new(events.clone()),
);

Self { events }
}
}

#[derive(Debug, Clone, Hash, PartialEq, Eq, Encode)]
struct EventLabels {
event: EventType,
}

#[derive(Debug, Clone, Hash, PartialEq, Eq, Encode)]
enum EventType {
ReservationReqAccepted,
ReservationReqAcceptFailed,
ReservationReqDenied,
ReservationReqDenyFailed,
ReservationTimedOut,
CircuitReqDenied,
CircuitReqDenyFailed,
CircuitReqAccepted,
CircuitReqAcceptFailed,
CircuitClosed,
}

impl From<&libp2p_relay::v2::relay::Event> for EventType {
fn from(event: &libp2p_relay::v2::relay::Event) -> Self {
match event {
libp2p_relay::v2::relay::Event::ReservationReqAccepted { .. } => {
EventType::ReservationReqAccepted
}
libp2p_relay::v2::relay::Event::ReservationReqAcceptFailed { .. } => {
EventType::ReservationReqAcceptFailed
}
libp2p_relay::v2::relay::Event::ReservationReqDenied { .. } => {
EventType::ReservationReqDenied
}
libp2p_relay::v2::relay::Event::ReservationReqDenyFailed { .. } => {
EventType::ReservationReqDenyFailed
}
libp2p_relay::v2::relay::Event::ReservationTimedOut { .. } => {
EventType::ReservationTimedOut
}
libp2p_relay::v2::relay::Event::CircuitReqDenied { .. } => EventType::CircuitReqDenied,
libp2p_relay::v2::relay::Event::CircuitReqDenyFailed { .. } => {
EventType::CircuitReqDenyFailed
}
libp2p_relay::v2::relay::Event::CircuitReqAccepted { .. } => {
EventType::CircuitReqAccepted
}
libp2p_relay::v2::relay::Event::CircuitReqAcceptFailed { .. } => {
EventType::CircuitReqAcceptFailed
}
libp2p_relay::v2::relay::Event::CircuitClosed { .. } => EventType::CircuitClosed,
}
}
}

impl super::Recorder<libp2p_relay::v2::relay::Event> for super::Metrics {
fn record(&self, event: &libp2p_relay::v2::relay::Event) {
self.relay
.events
.get_or_create(&EventLabels {
event: event.into(),
})
.inc();
}
}
11 changes: 7 additions & 4 deletions protocols/relay/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ edition = "2021"
rust-version = "1.56.1"
description = "Communications relaying for libp2p"
version = "0.6.0"
authors = ["Parity Technologies <admin@parity.io>"]
authors = ["Parity Technologies <admin@parity.io>", "Max Inden <mail@max-inden.de>"]
license = "MIT"
repository = "https://github.com/libp2p/rust-libp2p"
keywords = ["peer-to-peer", "libp2p", "networking"]
Expand All @@ -21,8 +21,10 @@ libp2p-swarm = { version = "0.33.0", path = "../../swarm" }
log = "0.4"
pin-project = "1"
prost = "0.9"
rand = "0.7"
rand = "0.8.4"
smallvec = "1.6.1"
static_assertions = "1"
thiserror = "1.0"
unsigned-varint = { version = "0.7", features = ["asynchronous_codec"] }
void = "1"

Expand All @@ -31,10 +33,11 @@ prost-build = "0.9"

[dev-dependencies]
env_logger = "0.9.0"
structopt = "0.3.21"
libp2p = { path = "../.." }
libp2p-identify = { path = "../identify" }
libp2p-kad = { path = "../kad" }
libp2p-ping = { path = "../ping" }
libp2p-identify = { path = "../identify" }
libp2p-plaintext = { path = "../../transports/plaintext" }
libp2p-yamux = { path = "../../muxers/yamux" }
quickcheck = "1"
structopt = "0.3.21"
3 changes: 2 additions & 1 deletion protocols/relay/build.rs
Original file line number Diff line number Diff line change
Expand Up @@ -19,5 +19,6 @@
// DEALINGS IN THE SOFTWARE.

fn main() {
prost_build::compile_protos(&["src/message.proto"], &["src"]).unwrap();
prost_build::compile_protos(&["src/v1/message.proto"], &["src/v1"]).unwrap();
prost_build::compile_protos(&["src/v2/message.proto"], &["src/v2"]).unwrap();
}
Original file line number Diff line number Diff line change
Expand Up @@ -61,7 +61,7 @@ use futures::executor::block_on;
use futures::stream::StreamExt;
use libp2p::dns::DnsConfig;
use libp2p::plaintext;
use libp2p::relay::{Relay, RelayConfig};
use libp2p::relay::v1::{Relay, RelayConfig};
use libp2p::swarm::SwarmEvent;
use libp2p::tcp::TcpConfig;
use libp2p::Transport;
Expand Down Expand Up @@ -94,7 +94,7 @@ fn main() -> Result<(), Box<dyn Error>> {
..Default::default()
};
let (relay_wrapped_transport, relay_behaviour) =
libp2p_relay::new_transport_and_behaviour(relay_config, transport);
libp2p_relay::v1::new_transport_and_behaviour(relay_config, transport);

let behaviour = Behaviour {
relay: relay_behaviour,
Expand Down
152 changes: 152 additions & 0 deletions protocols/relay/examples/relay_v2.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,152 @@
// Copyright 2020 Parity Technologies (UK) Ltd.
// Copyright 2021 Protocol Labs.
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the "Software"),
// to deal in the Software without restriction, including without limitation
// the rights to use, copy, modify, merge, publish, distribute, sublicense,
// and/or sell copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.

use futures::executor::block_on;
use futures::stream::StreamExt;
use libp2p::core::upgrade;
use libp2p::identify::{Identify, IdentifyConfig, IdentifyEvent};
use libp2p::multiaddr::Protocol;
use libp2p::ping::{Ping, PingConfig, PingEvent};
use libp2p::relay::v2::relay::{self, Relay};
use libp2p::swarm::{Swarm, SwarmEvent};
use libp2p::tcp::TcpConfig;
use libp2p::Transport;
use libp2p::{identity, NetworkBehaviour, PeerId};
use libp2p::{noise, Multiaddr};
use std::error::Error;
use std::net::{Ipv4Addr, Ipv6Addr};
use structopt::StructOpt;

fn main() -> Result<(), Box<dyn Error>> {
env_logger::init();

let opt = Opt::from_args();
println!("opt: {:?}", opt);

// Create a static known PeerId based on given secret
let local_key: identity::Keypair = generate_ed25519(opt.secret_key_seed);
let local_peer_id = PeerId::from(local_key.public());
println!("Local peer id: {:?}", local_peer_id);

let tcp_transport = TcpConfig::new();

let noise_keys = noise::Keypair::<noise::X25519Spec>::new()
.into_authentic(&local_key)
.expect("Signing libp2p-noise static DH keypair failed.");

let transport = tcp_transport
.upgrade(upgrade::Version::V1)
.authenticate(noise::NoiseConfig::xx(noise_keys).into_authenticated())
.multiplex(libp2p_yamux::YamuxConfig::default())
.boxed();
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

no transport wrapper anymore? 👍

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The relay client and server in the v2 implementation are split. This is the server side only. The server does not require a transport wrapper.

Copy link
Contributor

@MarcoPolo MarcoPolo Dec 3, 2021

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

What is a transport wrapper? Looking at the examples gives me no clues

Edit:

To answer my question, the transport wrapper for the client side of the circuit v2 would be here: https://github.com/libp2p/rust-libp2p/blob/580f6688fd675c698ca918d44808915fa9bda914/protocols/relay/src/v2/client/transport.rs

It wraps the given transport and gives it the ability to do extra stuff. For example, a tcp_transport wouldn't know how to dial another client over a circuit V2 connection, but the wrapped transport adds this ability. It basically sees if the address to dial (or listen on) includes a relay portioned, if it does it does something specific to circuitV2 otherwise it defers to the inner transport.


let behaviour = Behaviour {
relay: Relay::new(local_peer_id, Default::default()),
ping: Ping::new(PingConfig::new()),
identify: Identify::new(IdentifyConfig::new(
"/TODO/0.0.1".to_string(),
local_key.public(),
)),
};

let mut swarm = Swarm::new(transport, behaviour, local_peer_id);

// Listen on all interfaces
let listen_addr = Multiaddr::empty()
.with(match opt.use_ipv6 {
Some(true) => Protocol::from(Ipv6Addr::UNSPECIFIED),
_ => Protocol::from(Ipv4Addr::UNSPECIFIED),
})
.with(Protocol::Tcp(opt.port));
swarm.listen_on(listen_addr)?;

block_on(async {
loop {
match swarm.next().await.expect("Infinite Stream.") {
SwarmEvent::Behaviour(Event::Relay(event)) => {
println!("{:?}", event)
}
SwarmEvent::NewListenAddr { address, .. } => {
println!("Listening on {:?}", address);
}
_ => {}
}
}
})
}

#[derive(NetworkBehaviour)]
#[behaviour(out_event = "Event", event_process = false)]
struct Behaviour {
relay: Relay,
ping: Ping,
identify: Identify,
}

#[derive(Debug)]
enum Event {
Ping(PingEvent),
Identify(IdentifyEvent),
Relay(relay::Event),
}

impl From<PingEvent> for Event {
fn from(e: PingEvent) -> Self {
Event::Ping(e)
}
}

impl From<IdentifyEvent> for Event {
fn from(e: IdentifyEvent) -> Self {
Event::Identify(e)
}
}

impl From<relay::Event> for Event {
fn from(e: relay::Event) -> Self {
Event::Relay(e)
}
}

fn generate_ed25519(secret_key_seed: u8) -> identity::Keypair {
let mut bytes = [0u8; 32];
bytes[0] = secret_key_seed;

let secret_key = identity::ed25519::SecretKey::from_bytes(&mut bytes)
.expect("this returns `Err` only if the length is wrong; the length is correct; qed");
identity::Keypair::Ed25519(secret_key.into())
}

#[derive(Debug, StructOpt)]
#[structopt(name = "libp2p relay")]
struct Opt {
/// Determine if the relay listen on ipv6 or ipv4 loopback address. the default is ipv4
#[structopt(long)]
use_ipv6: Option<bool>,

/// Fixed value to generate deterministic peer id
#[structopt(long)]
secret_key_seed: u8,

/// The port used to listen on all interfaces
#[structopt(long)]
port: u16,
}
Loading