From dcc73346df90840c4dfc7a3fdeacf86f2655b101 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=C3=87a=C4=9Fla=20=C3=87elik?= Date: Wed, 16 Oct 2024 13:28:22 +0300 Subject: [PATCH 1/6] used eyre:Result instead of expect --- p2p/src/behaviour.rs | 54 +++++++++++++++++++++++++------------------- p2p/src/client.rs | 12 ++++------ 2 files changed, 36 insertions(+), 30 deletions(-) diff --git a/p2p/src/behaviour.rs b/p2p/src/behaviour.rs index bf64399..37498fd 100644 --- a/p2p/src/behaviour.rs +++ b/p2p/src/behaviour.rs @@ -6,6 +6,7 @@ use libp2p::identity::{Keypair, PeerId, PublicKey}; use libp2p::kad::store::MemoryStore; use libp2p::StreamProtocol; use libp2p::{autonat, dcutr, gossipsub, identify, kad, relay}; +use eyre::{eyre, Result}; #[derive(libp2p::swarm::NetworkBehaviour)] pub struct DriaBehaviour { @@ -23,17 +24,17 @@ impl DriaBehaviour { relay_behavior: relay::client::Behaviour, identity_protocol: String, kademlia_protocol: StreamProtocol, - ) -> Self { + ) -> Result { let public_key = key.public(); let peer_id = public_key.to_peer_id(); - Self { + Ok(Self { relay: relay_behavior, - gossipsub: create_gossipsub_behavior(peer_id), + gossipsub: create_gossipsub_behavior(peer_id)?, kademlia: create_kademlia_behavior(peer_id, kademlia_protocol), autonat: create_autonat_behavior(peer_id), dcutr: create_dcutr_behavior(peer_id), identify: create_identify_behavior(public_key, identity_protocol), - } + }) } } @@ -42,7 +43,7 @@ impl DriaBehaviour { fn create_kademlia_behavior( local_peer_id: PeerId, protocol_name: StreamProtocol, -) -> kad::Behaviour { +) -> kad::Behaviour{ use kad::{Behaviour, Config}; const QUERY_TIMEOUT_SECS: u64 = 5 * 60; @@ -94,7 +95,7 @@ fn create_autonat_behavior(local_peer_id: PeerId) -> autonat::Behaviour { /// Configures the Gossipsub behavior for pub/sub messaging across peers. #[inline] -fn create_gossipsub_behavior(author: PeerId) -> gossipsub::Behaviour { +fn create_gossipsub_behavior(author: PeerId) -> Result { use gossipsub::{ Behaviour, ConfigBuilder, Message, MessageAuthenticity, MessageId, ValidationMode, }; @@ -138,23 +139,30 @@ fn create_gossipsub_behavior(author: PeerId) -> gossipsub::Behaviour { }; // TODO: add data transform here later + let config = match ConfigBuilder::default() + .heartbeat_interval(Duration::from_secs(HEARTBEAT_INTERVAL_SECS)) + .max_transmit_size(MAX_TRANSMIT_SIZE) + .message_id_fn(message_id_fn) + .message_capacity(MESSAGE_CAPACITY) + .message_ttl(Duration::from_secs(MESSAGE_TTL_SECS)) + .gossip_ttl(Duration::from_secs(GOSSIP_TTL_SECS)) + .duplicate_cache_time(Duration::from_secs(DUPLICATE_CACHE_TIME_SECS)) + .max_ihave_length(MAX_IHAVE_LENGTH) + .send_queue_size(MAX_SEND_QUEUE_SIZE) + .validation_mode(VALIDATION_MODE) + .validate_messages() + .build() { + Ok(config) => config, + Err(e) => { + return Err(eyre!("Failed to create gossipsub config: {}", e)); + } + }; - Behaviour::new( + match Behaviour::new( MessageAuthenticity::Author(author), - ConfigBuilder::default() - .heartbeat_interval(Duration::from_secs(HEARTBEAT_INTERVAL_SECS)) - .max_transmit_size(MAX_TRANSMIT_SIZE) - .message_id_fn(message_id_fn) - .message_capacity(MESSAGE_CAPACITY) - .message_ttl(Duration::from_secs(MESSAGE_TTL_SECS)) - .gossip_ttl(Duration::from_secs(GOSSIP_TTL_SECS)) - .duplicate_cache_time(Duration::from_secs(DUPLICATE_CACHE_TIME_SECS)) - .max_ihave_length(MAX_IHAVE_LENGTH) - .send_queue_size(MAX_SEND_QUEUE_SIZE) - .validation_mode(VALIDATION_MODE) - .validate_messages() - .build() - .expect("Valid config"), // TODO: better error handling - ) - .expect("Valid behaviour") // TODO: better error handling + config + ) { + Ok(behaviour) => Ok(behaviour), + Err(e) => Err(eyre!("Failed to create gossipsub behaviour: {}", e)), + } } diff --git a/p2p/src/client.rs b/p2p/src/client.rs index f388f12..ffaadf5 100644 --- a/p2p/src/client.rs +++ b/p2p/src/client.rs @@ -1,5 +1,5 @@ use super::*; -use eyre::Result; +use eyre::{eyre, Result}; use libp2p::futures::StreamExt; use libp2p::gossipsub::{ Message, MessageAcceptance, MessageId, PublishError, SubscriptionError, TopicHash, @@ -72,13 +72,13 @@ impl DriaP2PClient { )? .with_quic() .with_relay_client(noise::Config::new, yamux::Config::default)? - .with_behaviour(|key, relay_behavior| { - Ok(DriaBehaviour::new( + .with_behaviour(|key, relay_behavior: libp2p::relay::client::Behaviour| { + DriaBehaviour::new( key, relay_behavior, identity_protocol.clone(), kademlia_protocol.clone(), - )) + ).unwrap() })? .with_swarm_config(|c| { c.with_idle_connection_timeout(Duration::from_secs(IDLE_CONNECTION_TIMEOUT_SECS)) @@ -135,9 +135,7 @@ impl DriaP2PClient { identity_protocol, kademlia_protocol, }) - } - - /// Subscribe to a topic. + } /// Subscribe to a topic. pub fn subscribe(&mut self, topic_name: &str) -> Result { log::debug!("Subscribing to {}", topic_name); From 41d6206b0e649b77610daddfb8ae3166ed21c2b2 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=C3=87a=C4=9Fla=20=C3=87elik?= Date: Wed, 16 Oct 2024 13:33:16 +0300 Subject: [PATCH 2/6] fix format --- p2p/src/behaviour.rs | 40 +++++++++++++++++++--------------------- p2p/src/client.rs | 8 +++++--- 2 files changed, 24 insertions(+), 24 deletions(-) diff --git a/p2p/src/behaviour.rs b/p2p/src/behaviour.rs index 37498fd..fddaffe 100644 --- a/p2p/src/behaviour.rs +++ b/p2p/src/behaviour.rs @@ -2,11 +2,11 @@ use std::collections::hash_map; use std::hash::{Hash, Hasher}; use std::time::Duration; +use eyre::{eyre, Result}; use libp2p::identity::{Keypair, PeerId, PublicKey}; use libp2p::kad::store::MemoryStore; use libp2p::StreamProtocol; use libp2p::{autonat, dcutr, gossipsub, identify, kad, relay}; -use eyre::{eyre, Result}; #[derive(libp2p::swarm::NetworkBehaviour)] pub struct DriaBehaviour { @@ -43,7 +43,7 @@ impl DriaBehaviour { fn create_kademlia_behavior( local_peer_id: PeerId, protocol_name: StreamProtocol, -) -> kad::Behaviour{ +) -> kad::Behaviour { use kad::{Behaviour, Config}; const QUERY_TIMEOUT_SECS: u64 = 5 * 60; @@ -140,29 +140,27 @@ fn create_gossipsub_behavior(author: PeerId) -> Result { // TODO: add data transform here later let config = match ConfigBuilder::default() - .heartbeat_interval(Duration::from_secs(HEARTBEAT_INTERVAL_SECS)) - .max_transmit_size(MAX_TRANSMIT_SIZE) - .message_id_fn(message_id_fn) - .message_capacity(MESSAGE_CAPACITY) - .message_ttl(Duration::from_secs(MESSAGE_TTL_SECS)) - .gossip_ttl(Duration::from_secs(GOSSIP_TTL_SECS)) - .duplicate_cache_time(Duration::from_secs(DUPLICATE_CACHE_TIME_SECS)) - .max_ihave_length(MAX_IHAVE_LENGTH) - .send_queue_size(MAX_SEND_QUEUE_SIZE) - .validation_mode(VALIDATION_MODE) - .validate_messages() - .build() { + .heartbeat_interval(Duration::from_secs(HEARTBEAT_INTERVAL_SECS)) + .max_transmit_size(MAX_TRANSMIT_SIZE) + .message_id_fn(message_id_fn) + .message_capacity(MESSAGE_CAPACITY) + .message_ttl(Duration::from_secs(MESSAGE_TTL_SECS)) + .gossip_ttl(Duration::from_secs(GOSSIP_TTL_SECS)) + .duplicate_cache_time(Duration::from_secs(DUPLICATE_CACHE_TIME_SECS)) + .max_ihave_length(MAX_IHAVE_LENGTH) + .send_queue_size(MAX_SEND_QUEUE_SIZE) + .validation_mode(VALIDATION_MODE) + .validate_messages() + .build() + { Ok(config) => config, Err(e) => { return Err(eyre!("Failed to create gossipsub config: {}", e)); } }; - match Behaviour::new( - MessageAuthenticity::Author(author), - config - ) { - Ok(behaviour) => Ok(behaviour), - Err(e) => Err(eyre!("Failed to create gossipsub behaviour: {}", e)), - } + match Behaviour::new(MessageAuthenticity::Author(author), config) { + Ok(behaviour) => Ok(behaviour), + Err(e) => Err(eyre!("Failed to create gossipsub behaviour: {}", e)), + } } diff --git a/p2p/src/client.rs b/p2p/src/client.rs index ffaadf5..f143097 100644 --- a/p2p/src/client.rs +++ b/p2p/src/client.rs @@ -1,5 +1,5 @@ use super::*; -use eyre::{eyre, Result}; +use eyre::Result; use libp2p::futures::StreamExt; use libp2p::gossipsub::{ Message, MessageAcceptance, MessageId, PublishError, SubscriptionError, TopicHash, @@ -78,7 +78,8 @@ impl DriaP2PClient { relay_behavior, identity_protocol.clone(), kademlia_protocol.clone(), - ).unwrap() + ) + .unwrap() })? .with_swarm_config(|c| { c.with_idle_connection_timeout(Duration::from_secs(IDLE_CONNECTION_TIMEOUT_SECS)) @@ -135,7 +136,8 @@ impl DriaP2PClient { identity_protocol, kademlia_protocol, }) - } /// Subscribe to a topic. + } + /// Subscribe to a topic. pub fn subscribe(&mut self, topic_name: &str) -> Result { log::debug!("Subscribing to {}", topic_name); From e9f3c3ce9ef9818d974f5d6e36fb9211d2da2292 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=C3=87a=C4=9Fla=20=C3=87elik?= Date: Wed, 16 Oct 2024 17:52:15 +0300 Subject: [PATCH 3/6] refactoring --- p2p/src/behaviour.rs | 44 +++++++++++++++++++------------------------- p2p/src/client.rs | 8 ++++++-- 2 files changed, 25 insertions(+), 27 deletions(-) diff --git a/p2p/src/behaviour.rs b/p2p/src/behaviour.rs index fddaffe..3572fcf 100644 --- a/p2p/src/behaviour.rs +++ b/p2p/src/behaviour.rs @@ -2,7 +2,7 @@ use std::collections::hash_map; use std::hash::{Hash, Hasher}; use std::time::Duration; -use eyre::{eyre, Result}; +use eyre::{eyre, Context, Result}; use libp2p::identity::{Keypair, PeerId, PublicKey}; use libp2p::kad::store::MemoryStore; use libp2p::StreamProtocol; @@ -139,28 +139,22 @@ fn create_gossipsub_behavior(author: PeerId) -> Result { }; // TODO: add data transform here later - let config = match ConfigBuilder::default() - .heartbeat_interval(Duration::from_secs(HEARTBEAT_INTERVAL_SECS)) - .max_transmit_size(MAX_TRANSMIT_SIZE) - .message_id_fn(message_id_fn) - .message_capacity(MESSAGE_CAPACITY) - .message_ttl(Duration::from_secs(MESSAGE_TTL_SECS)) - .gossip_ttl(Duration::from_secs(GOSSIP_TTL_SECS)) - .duplicate_cache_time(Duration::from_secs(DUPLICATE_CACHE_TIME_SECS)) - .max_ihave_length(MAX_IHAVE_LENGTH) - .send_queue_size(MAX_SEND_QUEUE_SIZE) - .validation_mode(VALIDATION_MODE) - .validate_messages() - .build() - { - Ok(config) => config, - Err(e) => { - return Err(eyre!("Failed to create gossipsub config: {}", e)); - } - }; - - match Behaviour::new(MessageAuthenticity::Author(author), config) { - Ok(behaviour) => Ok(behaviour), - Err(e) => Err(eyre!("Failed to create gossipsub behaviour: {}", e)), - } + Behaviour::new( + MessageAuthenticity::Author(author), + ConfigBuilder::default() + .heartbeat_interval(Duration::from_secs(HEARTBEAT_INTERVAL_SECS)) + .max_transmit_size(MAX_TRANSMIT_SIZE) + .message_id_fn(message_id_fn) + .message_capacity(MESSAGE_CAPACITY) + .message_ttl(Duration::from_secs(MESSAGE_TTL_SECS)) + .gossip_ttl(Duration::from_secs(GOSSIP_TTL_SECS)) + .duplicate_cache_time(Duration::from_secs(DUPLICATE_CACHE_TIME_SECS)) + .max_ihave_length(MAX_IHAVE_LENGTH) + .send_queue_size(MAX_SEND_QUEUE_SIZE) + .validation_mode(VALIDATION_MODE) + .validate_messages() + .build() + .wrap_err(eyre!("Failed to create config"))?, + ) + .map_err(|e| eyre!(e)) } diff --git a/p2p/src/client.rs b/p2p/src/client.rs index f143097..4718149 100644 --- a/p2p/src/client.rs +++ b/p2p/src/client.rs @@ -72,14 +72,17 @@ impl DriaP2PClient { )? .with_quic() .with_relay_client(noise::Config::new, yamux::Config::default)? - .with_behaviour(|key, relay_behavior: libp2p::relay::client::Behaviour| { + .with_behaviour(|key, relay_behavior| { DriaBehaviour::new( key, relay_behavior, identity_protocol.clone(), kademlia_protocol.clone(), ) - .unwrap() + .unwrap_or_else(|e| { + log::error!("Error creating Dria Behaviour: {:?}", e); + panic!("Failed to create Dria Behaviour: {:?}", e); + }) })? .with_swarm_config(|c| { c.with_idle_connection_timeout(Duration::from_secs(IDLE_CONNECTION_TIMEOUT_SECS)) @@ -137,6 +140,7 @@ impl DriaP2PClient { kademlia_protocol, }) } + /// Subscribe to a topic. pub fn subscribe(&mut self, topic_name: &str) -> Result { log::debug!("Subscribing to {}", topic_name); From 9ebf4a1eac4ab9a4c93c03e7a5417893f5e76a09 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=C3=87a=C4=9Fla=20=C3=87elik?= Date: Wed, 16 Oct 2024 17:54:09 +0300 Subject: [PATCH 4/6] format --- p2p/src/client.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/p2p/src/client.rs b/p2p/src/client.rs index 4718149..0afb179 100644 --- a/p2p/src/client.rs +++ b/p2p/src/client.rs @@ -141,7 +141,7 @@ impl DriaP2PClient { }) } - /// Subscribe to a topic. + /// Subscribe to a topic. pub fn subscribe(&mut self, topic_name: &str) -> Result { log::debug!("Subscribing to {}", topic_name); From 8043106692d9ff235028ed4db181c8ed92d78eb9 Mon Sep 17 00:00:00 2001 From: erhant Date: Thu, 17 Oct 2024 10:36:27 +0300 Subject: [PATCH 5/6] better error handling in Behaviour, consistent names --- p2p/src/behaviour.rs | 25 +++++++++++++------------ p2p/src/client.rs | 10 +++------- 2 files changed, 16 insertions(+), 19 deletions(-) diff --git a/p2p/src/behaviour.rs b/p2p/src/behaviour.rs index 3572fcf..e00918c 100644 --- a/p2p/src/behaviour.rs +++ b/p2p/src/behaviour.rs @@ -21,26 +21,27 @@ pub struct DriaBehaviour { impl DriaBehaviour { pub fn new( key: &Keypair, - relay_behavior: relay::client::Behaviour, + relay_behaviour: relay::client::Behaviour, identity_protocol: String, kademlia_protocol: StreamProtocol, ) -> Result { let public_key = key.public(); let peer_id = public_key.to_peer_id(); + Ok(Self { - relay: relay_behavior, - gossipsub: create_gossipsub_behavior(peer_id)?, - kademlia: create_kademlia_behavior(peer_id, kademlia_protocol), - autonat: create_autonat_behavior(peer_id), - dcutr: create_dcutr_behavior(peer_id), - identify: create_identify_behavior(public_key, identity_protocol), + relay: relay_behaviour, + gossipsub: create_gossipsub_behaviour(peer_id)?, + kademlia: create_kademlia_behaviour(peer_id, kademlia_protocol), + autonat: create_autonat_behaviour(peer_id), + dcutr: create_dcutr_behaviour(peer_id), + identify: create_identify_behaviour(public_key, identity_protocol), }) } } /// Configures the Kademlia DHT behavior for the node. #[inline] -fn create_kademlia_behavior( +fn create_kademlia_behaviour( local_peer_id: PeerId, protocol_name: StreamProtocol, ) -> kad::Behaviour { @@ -58,7 +59,7 @@ fn create_kademlia_behavior( /// Configures the Identify behavior to allow nodes to exchange information like supported protocols. #[inline] -fn create_identify_behavior( +fn create_identify_behaviour( local_public_key: PublicKey, protocol_version: String, ) -> identify::Behaviour { @@ -73,7 +74,7 @@ fn create_identify_behavior( /// It uses a Relay for the hole-punching process, and if it succeeds the peers are /// connected directly without the need for the relay; otherwise, they keep using the relay. #[inline] -fn create_dcutr_behavior(local_peer_id: PeerId) -> dcutr::Behaviour { +fn create_dcutr_behaviour(local_peer_id: PeerId) -> dcutr::Behaviour { use dcutr::Behaviour; Behaviour::new(local_peer_id) @@ -81,7 +82,7 @@ fn create_dcutr_behavior(local_peer_id: PeerId) -> dcutr::Behaviour { /// Configures the Autonat behavior to assist in network address translation detection. #[inline] -fn create_autonat_behavior(local_peer_id: PeerId) -> autonat::Behaviour { +fn create_autonat_behaviour(local_peer_id: PeerId) -> autonat::Behaviour { use autonat::{Behaviour, Config}; Behaviour::new( @@ -95,7 +96,7 @@ fn create_autonat_behavior(local_peer_id: PeerId) -> autonat::Behaviour { /// Configures the Gossipsub behavior for pub/sub messaging across peers. #[inline] -fn create_gossipsub_behavior(author: PeerId) -> Result { +fn create_gossipsub_behaviour(author: PeerId) -> Result { use gossipsub::{ Behaviour, ConfigBuilder, Message, MessageAuthenticity, MessageId, ValidationMode, }; diff --git a/p2p/src/client.rs b/p2p/src/client.rs index 0afb179..6af488f 100644 --- a/p2p/src/client.rs +++ b/p2p/src/client.rs @@ -35,7 +35,6 @@ pub struct DriaP2PClient { } /// Number of seconds before an idle connection is closed. -/// TODO: default is 0, is 60 a good value? const IDLE_CONNECTION_TIMEOUT_SECS: u64 = 60; /// Number of seconds between refreshing the Kademlia DHT. @@ -72,17 +71,14 @@ impl DriaP2PClient { )? .with_quic() .with_relay_client(noise::Config::new, yamux::Config::default)? - .with_behaviour(|key, relay_behavior| { + .with_behaviour(|key, relay_behaviour| { DriaBehaviour::new( key, - relay_behavior, + relay_behaviour, identity_protocol.clone(), kademlia_protocol.clone(), ) - .unwrap_or_else(|e| { - log::error!("Error creating Dria Behaviour: {:?}", e); - panic!("Failed to create Dria Behaviour: {:?}", e); - }) + .map_err(Into::into) })? .with_swarm_config(|c| { c.with_idle_connection_timeout(Duration::from_secs(IDLE_CONNECTION_TIMEOUT_SECS)) From b80a856865a7c4e2c2a5255e399644c59ed0e91b Mon Sep 17 00:00:00 2001 From: erhant Date: Thu, 17 Oct 2024 10:38:46 +0300 Subject: [PATCH 6/6] add context --- p2p/src/behaviour.rs | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/p2p/src/behaviour.rs b/p2p/src/behaviour.rs index e00918c..6bfbc75 100644 --- a/p2p/src/behaviour.rs +++ b/p2p/src/behaviour.rs @@ -30,7 +30,8 @@ impl DriaBehaviour { Ok(Self { relay: relay_behaviour, - gossipsub: create_gossipsub_behaviour(peer_id)?, + gossipsub: create_gossipsub_behaviour(peer_id) + .wrap_err("could not create Gossipsub behaviour")?, kademlia: create_kademlia_behaviour(peer_id, kademlia_protocol), autonat: create_autonat_behaviour(peer_id), dcutr: create_dcutr_behaviour(peer_id), @@ -155,7 +156,7 @@ fn create_gossipsub_behaviour(author: PeerId) -> Result { .validation_mode(VALIDATION_MODE) .validate_messages() .build() - .wrap_err(eyre!("Failed to create config"))?, + .wrap_err(eyre!("could not create Gossipsub config"))?, ) .map_err(|e| eyre!(e)) }