Skip to content

Commit 57f8019

Browse files
committed
feat: enable relay protocol of libp2p
1 parent 20f12a5 commit 57f8019

File tree

7 files changed

+166
-8
lines changed

7 files changed

+166
-8
lines changed

Cargo.lock

Lines changed: 86 additions & 1 deletion
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

Cargo.toml

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,14 +1,14 @@
11
[package]
22
name = "dephy-pproxy"
3-
version = "0.2.1"
3+
version = "0.3.1"
44
edition = "2021"
55

66
[dependencies]
77
async-trait = "0.1.81"
88
clap = "4.5.4"
99
futures = "0.3.30"
1010
hex = "0.4.3"
11-
libp2p = { version = "0.53.2", features = ["tokio", "macros", "yamux", "noise", "tcp", "request-response"] }
11+
libp2p = { version = "0.53.2", features = ["tokio", "macros", "yamux", "noise", "tcp", "request-response", "relay"] }
1212
prost = "0.13.1"
1313
thiserror = "1.0.60"
1414
tokio = { version = "1.37.0", features = ["rt-multi-thread"] }

proto/command_v1.proto

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -20,7 +20,16 @@ message CreateTunnelServerResponse {
2020
string address = 2;
2121
}
2222

23+
message ConnectRelayRequest {
24+
string address = 1;
25+
}
26+
27+
message ConnectRelayResponse {
28+
string relaied_address = 1;
29+
}
30+
2331
service CommandService {
2432
rpc AddPeer(AddPeerRequest) returns (AddPeerResponse);
2533
rpc CreateTunnelServer(CreateTunnelServerRequest) returns (CreateTunnelServerResponse);
34+
rpc ConnectRelay(ConnectRelayRequest) returns (ConnectRelayResponse);
2635
}

src/command.rs

Lines changed: 15 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -28,7 +28,7 @@ impl proto::command_service_server::CommandService for PProxyCommander {
2828
&self,
2929
request: Request<proto::AddPeerRequest>,
3030
) -> Result<Response<proto::AddPeerResponse>, Status> {
31-
tracing::trace!("handle request: {:?}", request);
31+
tracing::debug!("handle request: {:?}", request);
3232

3333
self.handle
3434
.add_peer(request.into_inner())
@@ -42,12 +42,25 @@ impl proto::command_service_server::CommandService for PProxyCommander {
4242
request: tonic::Request<proto::CreateTunnelServerRequest>,
4343
) -> std::result::Result<tonic::Response<proto::CreateTunnelServerResponse>, tonic::Status>
4444
{
45-
tracing::trace!("handle request: {:?}", request);
45+
tracing::debug!("handle request: {:?}", request);
4646

4747
self.handle
4848
.create_tunnel_server(request.into_inner())
4949
.await
5050
.map(Response::new)
5151
.map_err(|e| tonic::Status::internal(format!("{:?}", e)))
5252
}
53+
54+
async fn connect_relay(
55+
&self,
56+
request: tonic::Request<proto::ConnectRelayRequest>,
57+
) -> std::result::Result<tonic::Response<proto::ConnectRelayResponse>, tonic::Status> {
58+
tracing::debug!("handle request: {:?}", request);
59+
60+
self.handle
61+
.connect_relay(request.into_inner())
62+
.await
63+
.map(Response::new)
64+
.map_err(|e| tonic::Status::internal(format!("{:?}", e)))
65+
}
5366
}

src/error.rs

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -17,6 +17,8 @@ pub enum Error {
1717
EssentialTaskClosed,
1818
#[error("Libp2p swarm create error: {0}")]
1919
Libp2pSwarmCreateError(String),
20+
#[error("Libp2p transport error: {0}")]
21+
Libp2pTransportError(#[from] libp2p::core::transport::TransportError<std::io::Error>),
2022
#[error("Protocol not support: {0}")]
2123
ProtocolNotSupport(String),
2224
#[error("Unexpected response type")]

src/lib.rs

Lines changed: 43 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -17,6 +17,8 @@ use tokio::sync::mpsc;
1717

1818
use crate::command::proto::AddPeerRequest;
1919
use crate::command::proto::AddPeerResponse;
20+
use crate::command::proto::ConnectRelayRequest;
21+
use crate::command::proto::ConnectRelayResponse;
2022
use crate::command::proto::CreateTunnelServerRequest;
2123
use crate::command::proto::CreateTunnelServerResponse;
2224
use crate::p2p::PProxyNetworkBehaviour;
@@ -59,6 +61,9 @@ pub enum PProxyCommand {
5961
address: Multiaddr,
6062
peer_id: PeerId,
6163
},
64+
ConnectRelay {
65+
address: Multiaddr,
66+
},
6267
SendConnectCommand {
6368
peer_id: PeerId,
6469
tunnel_id: TunnelId,
@@ -73,6 +78,7 @@ pub enum PProxyCommand {
7378

7479
pub enum PProxyCommandResponse {
7580
AddPeer { peer_id: PeerId },
81+
ConnectRelay { relaied_address: Multiaddr },
7682
SendConnectCommand {},
7783
SendOutboundPackageCommand {},
7884
}
@@ -293,6 +299,7 @@ impl PProxy {
293299
PProxyCommand::AddPeer { address, peer_id } => {
294300
self.on_add_peer(address, peer_id, tx).await
295301
}
302+
PProxyCommand::ConnectRelay { address } => self.on_connect_relay(address, tx).await,
296303
PProxyCommand::SendConnectCommand {
297304
peer_id,
298305
tunnel_id,
@@ -324,6 +331,17 @@ impl PProxy {
324331
.map_err(|_| Error::EssentialTaskClosed)
325332
}
326333

334+
async fn on_connect_relay(&mut self, address: Multiaddr, tx: CommandNotifier) -> Result<()> {
335+
let relaied_address = address
336+
.with(multiaddr::Protocol::P2pCircuit)
337+
.with(multiaddr::Protocol::P2p(*self.swarm.local_peer_id()));
338+
339+
self.swarm.listen_on(relaied_address.clone())?;
340+
341+
tx.send(Ok(PProxyCommandResponse::ConnectRelay { relaied_address }))
342+
.map_err(|_| Error::EssentialTaskClosed)
343+
}
344+
327345
async fn on_send_connect_command(
328346
&mut self,
329347
peer_id: PeerId,
@@ -437,6 +455,31 @@ impl PProxyHandle {
437455
address: address.to_string(),
438456
})
439457
}
458+
459+
pub async fn connect_relay(
460+
&self,
461+
request: ConnectRelayRequest,
462+
) -> Result<ConnectRelayResponse> {
463+
let (tx, rx) = oneshot::channel();
464+
465+
let address: Multiaddr = request
466+
.address
467+
.parse()
468+
.map_err(|_| Error::MultiaddrParseError(request.address.clone()))?;
469+
470+
self.command_tx
471+
.send((PProxyCommand::ConnectRelay { address }, tx))
472+
.await?;
473+
474+
let response = rx.await??;
475+
476+
match response {
477+
PProxyCommandResponse::ConnectRelay { relaied_address } => Ok(ConnectRelayResponse {
478+
relaied_address: relaied_address.to_string(),
479+
}),
480+
_ => Err(Error::UnexpectedResponseType),
481+
}
482+
}
440483
}
441484

442485
fn extract_peer_id_from_multiaddr(multiaddr: &Multiaddr) -> Result<PeerId> {

src/p2p/behaviour.rs

Lines changed: 9 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
use libp2p::identity::Keypair;
2+
use libp2p::relay;
23
use libp2p::request_response;
34
use libp2p::swarm::NetworkBehaviour;
45
use libp2p::StreamProtocol;
@@ -8,17 +9,22 @@ use crate::p2p::codec::Codec;
89
#[derive(NetworkBehaviour)]
910
pub(crate) struct PProxyNetworkBehaviour {
1011
pub(crate) request_response: request_response::Behaviour<Codec>,
12+
pub(crate) relay: relay::Behaviour,
1113
}
1214

1315
impl PProxyNetworkBehaviour {
14-
pub fn new(_key: &Keypair) -> Self {
16+
pub fn new(key: &Keypair) -> Self {
1517
let request_response = request_response::Behaviour::new(
1618
[(
17-
StreamProtocol::new("/pproxy/1"),
19+
StreamProtocol::new("/pproxy/1.0.0"),
1820
request_response::ProtocolSupport::Full,
1921
)],
2022
request_response::Config::default(),
2123
);
22-
Self { request_response }
24+
let relay = relay::Behaviour::new(key.public().to_peer_id(), Default::default());
25+
Self {
26+
request_response,
27+
relay,
28+
}
2329
}
2430
}

0 commit comments

Comments
 (0)