Skip to content

Commit 02497da

Browse files
committed
fix: Change request-response type
1 parent 602fd5d commit 02497da

File tree

3 files changed

+60
-39
lines changed

3 files changed

+60
-39
lines changed

node/src/service/p2p/bootstrap.rs

Lines changed: 22 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -14,7 +14,7 @@ use libp2p::{
1414
tcp, yamux, Multiaddr, PeerId, StreamProtocol, Swarm, SwarmBuilder,
1515
};
1616
use log::{debug, error, info, warn};
17-
use primitives::p2p::{PeerInfo, WPeerId};
17+
use primitives::p2p::{PeerIdRequest, PeerInfo, PeerInfoResponse};
1818

1919
use crate::service::p2p::{P2PError, DEFAULT_REGISTRATION_TTL};
2020

@@ -25,7 +25,7 @@ pub struct BootstrapBehaviour {
2525
pub rendezvous: rendezvous::server::Behaviour,
2626
pub identify: identify::Behaviour,
2727
pub gossipsub: gossipsub::Behaviour,
28-
pub request_response: request_response::cbor::Behaviour<WPeerId, PeerInfo>,
28+
pub request_response: request_response::cbor::Behaviour<PeerIdRequest, PeerInfoResponse>,
2929
}
3030

3131
pub struct BootstrapConfig {
@@ -185,7 +185,7 @@ fn on_rendezvous_event(
185185
info.multiaddrs.push(addr.clone())
186186
}
187187
}
188-
} )
188+
})
189189
.or_insert(peer_info);
190190
// Send registration information to other bootstrap nodes.
191191
match swarm
@@ -236,7 +236,7 @@ fn on_gossipsub_event(
236236
info.multiaddrs.push(addr.clone())
237237
}
238238
}
239-
} )
239+
})
240240
.or_insert(peer_info);
241241
}
242242
other => debug!("Encountered other gossipsub event: {other:?}"),
@@ -246,7 +246,7 @@ fn on_gossipsub_event(
246246
/// Handles events within the request_response protocol
247247
fn on_request_response_event(
248248
swarm: &mut Swarm<BootstrapBehaviour>,
249-
event: request_response::Event<WPeerId, PeerInfo>,
249+
event: request_response::Event<PeerIdRequest, PeerInfoResponse>,
250250
registrations: &HashMap<PeerId, PeerInfo>,
251251
) {
252252
match event {
@@ -260,20 +260,25 @@ fn on_request_response_event(
260260
{
261261
info!("Got request with id {request_id} from {peer}");
262262
let id: PeerId = request.into();
263-
match registrations.get(&id) {
263+
let response = match registrations.get(&id) {
264264
Some(peer_info) => {
265-
// Sending the peer information back to the client who opened the channel.
266-
if swarm
267-
.behaviour_mut()
268-
.request_response
269-
.send_response(channel, peer_info.clone())
270-
.is_err()
271-
{
272-
// Could add retries here.
273-
error!("Failed to send peer info to {peer:?}");
274-
}
265+
info!("Peer {id:?} found in registrations");
266+
PeerInfoResponse::Found(peer_info.clone())
275267
}
276-
None => warn!("Peer {id:?} not found in registrations"),
268+
None => {
269+
info!("Peer {id:?} not found in registrations");
270+
PeerInfoResponse::NotFound(id.into())
271+
}
272+
};
273+
// Sending the peer information back to the client who opened the channel.
274+
// Could add retries here.
275+
if swarm
276+
.behaviour_mut()
277+
.request_response
278+
.send_response(channel, response)
279+
.is_err()
280+
{
281+
error!("Failed to send peer info to {peer:?}");
277282
}
278283
}
279284
}

primitives/src/p2p.rs

Lines changed: 26 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -34,34 +34,46 @@ pub struct PeerInfo {
3434
pub multiaddrs: Vec<Multiaddr>,
3535
}
3636

37-
fn deserialize_peer_id<'de, D: de::Deserializer<'de>>(d: D) -> Result<PeerId, D::Error> {
38-
let s: String = de::Deserialize::deserialize(d)?;
39-
PeerId::from_str(&s).map_err(de::Error::custom)
40-
}
41-
42-
fn serialize_peer_id<S: Serializer>(id: &PeerId, serializer: S) -> Result<S::Ok, S::Error> {
43-
let id = id.to_string();
44-
serializer.collect_str(&id)
37+
/// This enum is used in the request response P2P protocol.
38+
/// PeerInfoResponse::NotFound is returned when the requested peer ID was not found.
39+
/// PeerInfoResponse::Found(..) is returned when the requested peer ID was found.
40+
/// The latter holds the relevant [`PeerInfo`] inside.
41+
#[cfg(feature = "std")]
42+
#[derive(Clone, Debug, Serialize, Deserialize)]
43+
pub enum PeerInfoResponse {
44+
Found(PeerInfo),
45+
NotFound(PeerIdRequest),
4546
}
4647

47-
/// Wrapper struct for Peer ID so we can implement `Deserialize` and `Serialize`
48-
/// and use this type in the request response behaviour.
48+
/// The request type used for the request response P2P protocol.
49+
/// We cannot use PeerId directly because it does not implement
50+
/// Serialize and Deserialize.
4951
#[cfg(feature = "std")]
5052
#[derive(Clone, Debug, Serialize, Deserialize)]
51-
pub struct WPeerId(
53+
pub struct PeerIdRequest(
5254
#[serde(serialize_with = "serialize_peer_id")]
5355
#[serde(deserialize_with = "deserialize_peer_id")]
5456
PeerId,
5557
);
5658

57-
impl From<PeerId> for WPeerId {
59+
impl From<PeerId> for PeerIdRequest {
5860
fn from(value: PeerId) -> Self {
5961
Self(value)
6062
}
6163
}
6264

63-
impl Into<PeerId> for WPeerId {
65+
impl Into<PeerId> for PeerIdRequest {
6466
fn into(self) -> PeerId {
6567
self.0
6668
}
67-
}
69+
}
70+
71+
fn deserialize_peer_id<'de, D: de::Deserializer<'de>>(d: D) -> Result<PeerId, D::Error> {
72+
let s: String = de::Deserialize::deserialize(d)?;
73+
PeerId::from_str(&s).map_err(de::Error::custom)
74+
}
75+
76+
fn serialize_peer_id<S: Serializer>(id: &PeerId, serializer: S) -> Result<S::Ok, S::Error> {
77+
let id = id.to_string();
78+
serializer.collect_str(&id)
79+
}

storage-provider/client/examples/peer-resolver.rs

Lines changed: 12 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -16,11 +16,12 @@ use libp2p::swarm::SwarmEvent;
1616
use libp2p::{
1717
noise, request_response, tcp, yamux, Multiaddr, PeerId, StreamProtocol, Swarm, SwarmBuilder,
1818
};
19-
use primitives::p2p::{PeerInfo, WPeerId};
19+
use primitives::p2p::{PeerIdRequest, PeerInfoResponse};
2020
use tracing_subscriber::EnvFilter;
2121

2222
/// Create a discovery swarm
23-
fn create_discover_swarm() -> Result<Swarm<request_response::cbor::Behaviour<WPeerId, PeerInfo>>> {
23+
fn create_discover_swarm(
24+
) -> Result<Swarm<request_response::cbor::Behaviour<PeerIdRequest, PeerInfoResponse>>> {
2425
let swarm = SwarmBuilder::with_new_identity()
2526
.with_tokio()
2627
.with_tcp(
@@ -44,11 +45,11 @@ fn create_discover_swarm() -> Result<Swarm<request_response::cbor::Behaviour<WPe
4445

4546
/// Run the discovery swarm and request the peer ID to multiaddrs mapping.
4647
async fn run_discover(
47-
mut swarm: Swarm<request_response::cbor::Behaviour<WPeerId, PeerInfo>>,
48+
mut swarm: Swarm<request_response::cbor::Behaviour<PeerIdRequest, PeerInfoResponse>>,
4849
bootstrap_addr: Multiaddr,
4950
bootstrap_id: &PeerId,
5051
resolve_id: PeerId,
51-
) -> Result<PeerInfo> {
52+
) -> Result<PeerInfoResponse> {
5253
swarm.dial(bootstrap_addr)?;
5354

5455
loop {
@@ -116,9 +117,12 @@ async fn main() -> Result<()> {
116117
println!("Attempting to get multiaddrs for peer {:?}", cli.resolve_id);
117118
let peer_info =
118119
run_discover(swarm, cli.bootstrap_addr, &cli.bootstrap_id, cli.resolve_id).await?;
119-
println!(
120-
"Got multiaddrs {:#?} for peer {:?}",
121-
peer_info.multiaddrs, peer_info.peer_id
122-
);
120+
match peer_info {
121+
PeerInfoResponse::NotFound(peer) => println!("Peer {:?} is not registered", peer),
122+
PeerInfoResponse::Found(info) => println!(
123+
"Got multiaddrs {:#?} for peer {:?}",
124+
info.multiaddrs, info.peer_id
125+
),
126+
}
123127
Ok(())
124128
}

0 commit comments

Comments
 (0)