Skip to main content

P2PNode

Struct P2PNode 

Source
pub struct P2PNode {
    pub security_dashboard: Option<Arc<SecurityDashboard>>,
    /* private fields */
}
Expand description

Main P2P network node that manages connections, routing, and communication

This struct represents a complete P2P network participant that can:

  • Connect to other peers via QUIC transport
  • Participate in distributed hash table (DHT) operations
  • Send and receive messages through various protocols
  • Handle network events and peer lifecycle

Transport concerns (connections, messaging, events) are delegated to TransportHandle.

Fields§

§security_dashboard: Option<Arc<SecurityDashboard>>

Security dashboard for monitoring

Implementations§

Source§

impl P2PNode

Source

pub async fn new(config: NodeConfig) -> Result<Self>

Create a new P2P node with the given configuration

Source

pub fn builder() -> NodeBuilder

Create a new node builder

Source

pub fn peer_id(&self) -> &PeerId

Get the peer ID of this node

Source

pub fn transport(&self) -> &Arc<TransportHandle>

Get the transport handle for sharing with other components.

Source

pub fn transport_peer_id(&self) -> Option<String>

Get the hex-encoded transport-level peer ID.

Source

pub fn local_addr(&self) -> Option<String>

Source

pub fn is_bootstrapped(&self) -> bool

Check if the node has completed the initial bootstrap process

Returns true if the node has successfully connected to at least one bootstrap peer and performed peer discovery (FIND_NODE).

Source

pub async fn re_bootstrap(&self) -> Result<()>

Manually trigger re-bootstrap (useful for recovery or network rejoin)

This clears the bootstrapped state and attempts to reconnect to bootstrap peers and discover new peers.

Source

pub fn trust_engine(&self) -> Option<Arc<EigenTrustEngine>>

Get the EigenTrust engine for direct trust operations

This provides access to the underlying trust engine for advanced use cases. For simple success/failure reporting, prefer report_peer_success() and report_peer_failure().

§Example
if let Some(engine) = node.trust_engine() {
    // Update node statistics directly
    engine.update_node_stats(&peer_id, NodeStatisticsUpdate::StorageContributed(1024)).await;

    // Get global trust scores
    let scores = engine.compute_global_trust().await;
}
Source

pub async fn report_peer_success(&self, peer_id: &str) -> Result<()>

Report a successful interaction with a peer

Call this after successful data operations to increase the peer’s trust score. This is the primary method for saorsa-node to report positive outcomes.

§Arguments
  • peer_id - The peer ID (as a string) of the node that performed well
§Example
// After successfully retrieving a chunk from a peer
if let Ok(chunk) = fetch_chunk_from(&peer_id).await {
    node.report_peer_success(&peer_id).await?;
}
Source

pub async fn report_peer_failure(&self, peer_id: &str) -> Result<()>

Report a failed interaction with a peer

Call this after failed data operations to decrease the peer’s trust score. This includes timeouts, corrupted data, or refused connections.

§Arguments
  • peer_id - The peer ID (as a string) of the node that failed
§Example
// After a chunk retrieval fails
match fetch_chunk_from(&peer_id).await {
    Ok(chunk) => node.report_peer_success(&peer_id).await?,
    Err(_) => node.report_peer_failure(&peer_id).await?,
}
Source

pub async fn report_peer_failure_with_reason( &self, peer_id: &str, reason: PeerFailureReason, ) -> Result<()>

Report a failed interaction with a peer, providing a specific failure reason.

This is the enriched version of P2PNode::report_peer_failure that maps the failure reason to the appropriate trust penalty. Use this when you know why the interaction failed to give the trust engine more accurate data.

  • Transport-level failures (Timeout, ConnectionFailed) map to FailedResponse
  • DataUnavailable maps to DataUnavailable
  • CorruptedData maps to CorruptedData (counts as 2 failures)
  • ProtocolError maps to ProtocolViolation (counts as 2 failures)
  • Refused maps to FailedResponse

Requires the adaptive-ml feature to be enabled.

§Arguments
  • peer_id - The peer ID of the node that failed
  • reason - Why the interaction failed
§Example
use saorsa_core::error::PeerFailureReason;

// After a chunk retrieval returns corrupted data
node.report_peer_failure_with_reason(&peer_id, PeerFailureReason::CorruptedData).await?;
Source

pub fn peer_trust(&self, peer_id: &str) -> f64

Get the current trust score for a peer

Returns a value between 0.0 (untrusted) and 1.0 (fully trusted). Unknown peers return 0.0 by default.

§Arguments
  • peer_id - The peer ID (as a string) to query
§Example
let trust = node.peer_trust(&peer_id);
if trust < 0.3 {
    tracing::warn!("Low trust peer: {}", peer_id);
}
Source

pub async fn send_request( &self, peer_id: &PeerId, protocol: &str, data: Vec<u8>, timeout: Duration, ) -> Result<PeerResponse>

Send a request to a peer and wait for a response with automatic trust reporting.

Unlike fire-and-forget send_message(), this method:

  1. Wraps the payload in a RequestResponseEnvelope with a unique message ID
  2. Sends it on the /rr/<protocol> protocol prefix
  3. Waits for a matching response (or timeout)
  4. Automatically reports success or failure to the trust engine

The remote peer’s handler should call send_response() with the incoming message ID to route the response back.

§Arguments
  • peer_id - Target peer
  • protocol - Application protocol name (e.g. "chunk_fetch")
  • data - Request payload bytes
  • timeout - Maximum time to wait for a response
§Returns

A PeerResponse on success, or an error on timeout / connection failure.

§Example
let response = node.send_request(&peer_id, "chunk_fetch", chunk_id.to_vec(), Duration::from_secs(10)).await?;
println!("Got {} bytes from {}", response.data.len(), response.peer_id);
Source

pub async fn send_response( &self, peer_id: &PeerId, protocol: &str, message_id: &str, data: Vec<u8>, ) -> Result<()>

Source

pub fn parse_request_envelope(data: &[u8]) -> Option<(String, bool, Vec<u8>)>

Source

pub async fn subscribe(&self, topic: &str) -> Result<()>

Source

pub async fn publish(&self, topic: &str, data: &[u8]) -> Result<()>

Source

pub fn config(&self) -> &NodeConfig

Get the node configuration

Source

pub async fn start(&self) -> Result<()>

Start the P2P node

Source

pub async fn run(&self) -> Result<()>

Run the P2P node (blocks until shutdown)

Source

pub async fn stop(&self) -> Result<()>

Stop the P2P node

Source

pub async fn shutdown(&self) -> Result<()>

Graceful shutdown alias for tests

Source

pub fn is_running(&self) -> bool

Check if the node is running

Source

pub async fn listen_addrs(&self) -> Vec<SocketAddr>

Get the current listen addresses

Source

pub async fn connected_peers(&self) -> Vec<PeerId>

Get connected peers

Source

pub async fn peer_count(&self) -> usize

Get peer count

Source

pub async fn peer_info(&self, peer_id: &PeerId) -> Option<PeerInfo>

Get peer info

Source

pub async fn get_peer_id_by_address(&self, addr: &str) -> Option<PeerId>

Get the peer ID for a given socket address, if connected

Source

pub async fn list_active_connections(&self) -> Vec<(PeerId, Vec<String>)>

List all active connections with their peer IDs and addresses

Source

pub async fn remove_peer(&self, peer_id: &PeerId) -> bool

Remove a peer from the peers map

Source

pub async fn is_peer_connected(&self, peer_id: &PeerId) -> bool

Check if a peer is connected

Source

pub async fn connect_peer(&self, address: &str) -> Result<PeerId>

Connect to a peer

Source

pub async fn disconnect_peer(&self, peer_id: &PeerId) -> Result<()>

Disconnect from a peer

Source

pub async fn is_connection_active(&self, peer_id: &str) -> bool

Check if a connection to a peer is active

Source

pub async fn send_message( &self, peer_id: &PeerId, protocol: &str, data: Vec<u8>, ) -> Result<()>

Send a message to a peer

Source§

impl P2PNode

Source

pub fn subscribe_events(&self) -> Receiver<P2PEvent>

Subscribe to network events

Source

pub fn events(&self) -> Receiver<P2PEvent>

Backwards-compat event stream accessor for tests

Source

pub fn uptime(&self) -> Duration

Get node uptime

Source

pub async fn resource_metrics(&self) -> Result<ResourceMetrics>

Get production resource metrics

Source

pub async fn health_check(&self) -> Result<()>

Check system health

Source

pub fn production_config(&self) -> Option<&ProductionConfig>

Get production configuration (if enabled)

Source

pub fn is_production_mode(&self) -> bool

Check if production hardening is enabled

Source

pub fn dht_manager(&self) -> &Arc<DhtNetworkManager>

Get the attached DHT manager.

Source

pub fn dht(&self) -> &Arc<DhtNetworkManager>

Backwards-compatible alias for dht_manager().

Source

pub async fn dht_put(&self, key: Key, value: Vec<u8>) -> Result<()>

Store a value in the local DHT

This method stores data in the local DHT core through the attached manager. For network-wide replication across multiple nodes, use DhtNetworkManager::put.

Source

pub async fn dht_get(&self, key: Key) -> Result<Option<Vec<u8>>>

Retrieve a value from the local DHT

This method retrieves data from the local DHT core through the attached manager. For network-wide lookups across multiple nodes, use DhtNetworkManager::get.

Source

pub async fn add_discovered_peer( &self, peer_id: PeerId, addresses: Vec<String>, ) -> Result<()>

Add a discovered peer to the bootstrap cache

Source

pub async fn update_peer_metrics( &self, peer_id: &PeerId, success: bool, latency_ms: Option<u64>, _error: Option<String>, ) -> Result<()>

Update connection metrics for a peer in the bootstrap cache

Source

pub async fn get_bootstrap_cache_stats(&self) -> Result<Option<CacheStats>>

Get bootstrap cache statistics

Source

pub async fn cached_peer_count(&self) -> usize

Get the number of cached bootstrap peers

Auto Trait Implementations§

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T> Instrument for T

Source§

fn instrument(self, span: Span) -> Instrumented<Self>

Instruments this type with the provided Span, returning an Instrumented wrapper. Read more
Source§

fn in_current_span(self) -> Instrumented<Self>

Instruments this type with the current Span, returning an Instrumented wrapper. Read more
Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T> PolicyExt for T
where T: ?Sized,

Source§

fn and<P, B, E>(self, other: P) -> And<T, P>
where T: Policy<B, E>, P: Policy<B, E>,

Create a new Policy that returns Action::Follow only if self and other return Action::Follow. Read more
Source§

fn or<P, B, E>(self, other: P) -> Or<T, P>
where T: Policy<B, E>, P: Policy<B, E>,

Create a new Policy that returns Action::Follow if either self or other returns Action::Follow. Read more
Source§

impl<T> Same for T

Source§

type Output = T

Should always be Self
Source§

impl<SS, SP> SupersetOf<SS> for SP
where SS: SubsetOf<SP>,

Source§

fn to_subset(&self) -> Option<SS>

The inverse inclusion map: attempts to construct self from the equivalent element of its superset. Read more
Source§

fn is_in_subset(&self) -> bool

Checks if self is actually part of its subset T (and can be converted to it).
Source§

fn to_subset_unchecked(&self) -> SS

Use with care! Same as self.to_subset but without any property checks. Always succeeds.
Source§

fn from_subset(element: &SS) -> SP

The inclusion map: converts self to the equivalent element of its superset.
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = Infallible

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
Source§

impl<V, T> VZip<V> for T
where V: MultiLane<T>,

Source§

fn vzip(self) -> V

Source§

impl<T> WithSubscriber for T

Source§

fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self>
where S: Into<Dispatch>,

Attaches the provided Subscriber to this type, returning a WithDispatch wrapper. Read more
Source§

fn with_current_subscriber(self) -> WithDispatch<Self>

Attaches the current default Subscriber to this type, returning a WithDispatch wrapper. Read more
Source§

impl<A, B, T> HttpServerConnExec<A, B> for T
where B: Body,