1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
// Copyright 2024 Saorsa Labs Ltd.
//
// This Saorsa Network Software is licensed under the General Public License (GPL), version 3.
// Please see the file LICENSE-GPL, or visit <http://www.gnu.org/licenses/> for the full text.
//
// Full details available at https://saorsalabs.com/licenses
//! Zero-configuration P2P node
//!
//! This module provides [`Node`] - the simple API for creating P2P nodes
//! that work out of the box with zero configuration. Every node automatically:
//!
//! - Uses 100% post-quantum cryptography (ML-KEM-768)
//! - Works behind any NAT via native QUIC hole punching
//! - Can act as coordinator/relay if environment allows
//! - Exposes complete observability via [`NodeStatus`]
//!
//! # Zero Configuration
//!
//! ```rust,ignore
//! use ant_quic::Node;
//!
//! #[tokio::main]
//! async fn main() -> anyhow::Result<()> {
//! // Create a node - that's it!
//! let node = Node::new().await?;
//!
//! println!("I am: {:?}", node.peer_id());
//! println!("Listening on: {:?}", node.local_addr());
//!
//! // Check status
//! let status = node.status().await;
//! println!("NAT type: {}", status.nat_type);
//! println!("Can receive direct: {}", status.can_receive_direct);
//! println!("Acting as relay: {}", status.is_relaying);
//!
//! // Connect to a peer
//! let conn = node.connect_addr("quic.saorsalabs.com:9000".parse()?).await?;
//!
//! // Accept connections
//! let incoming = node.accept().await;
//!
//! Ok(())
//! }
//! ```
use std::net::SocketAddr;
use std::sync::Arc;
use std::time::{Duration, Instant};
use crate::crypto::pqc::types::{MlDsaPublicKey, MlDsaSecretKey};
use tokio::sync::broadcast;
use tracing::info;
use crate::host_identity::HostIdentity;
use crate::nat_traversal_api::PeerId;
use crate::node_config::NodeConfig;
use crate::node_event::NodeEvent;
use crate::node_status::{NatType, NodeStatus};
use crate::p2p_endpoint::{EndpointError, P2pEndpoint, P2pEvent, PeerConnection};
use crate::unified_config::P2pConfig;
use crate::unified_config::load_or_generate_endpoint_keypair;
/// Error type for Node operations
#[derive(Debug, thiserror::Error)]
pub enum NodeError {
/// Failed to create node
#[error("Failed to create node: {0}")]
Creation(String),
/// Connection error
#[error("Connection error: {0}")]
Connection(String),
/// Endpoint error
#[error("Endpoint error: {0}")]
Endpoint(#[from] EndpointError),
/// Shutting down
#[error("Node is shutting down")]
ShuttingDown,
}
/// Zero-configuration P2P node
///
/// This is the primary API for ant-quic. Create a node with zero configuration
/// and it will automatically handle NAT traversal, post-quantum cryptography,
/// and peer discovery.
///
/// # Symmetric P2P
///
/// All nodes are equal - every node can:
/// - Connect to other nodes
/// - Accept incoming connections
/// - Act as coordinator for NAT traversal
/// - Act as relay for peers behind restrictive NATs
///
/// # Post-Quantum Security
///
/// v0.2: Every connection uses pure post-quantum cryptography:
/// - Key Exchange: ML-KEM-768 (FIPS 203)
/// - Authentication: ML-DSA-65 (FIPS 204)
/// - Ed25519 is used ONLY for the 32-byte PeerId compact identifier
///
/// There is no classical crypto fallback - security is quantum-resistant by default.
///
/// # Example
///
/// ```rust,ignore
/// use ant_quic::Node;
///
/// // Zero configuration
/// let node = Node::new().await?;
///
/// // Or with known peers
/// let node = Node::with_peers(vec!["quic.saorsalabs.com:9000".parse()?]).await?;
///
/// // Or with persistent identity
/// let keypair = load_keypair()?;
/// let node = Node::with_keypair(keypair).await?;
/// ```
pub struct Node {
/// Inner P2pEndpoint
inner: Arc<P2pEndpoint>,
/// Start time for uptime calculation
start_time: Instant,
/// Event broadcaster for unified events
event_tx: broadcast::Sender<NodeEvent>,
}
impl std::fmt::Debug for Node {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("Node")
.field("peer_id", &self.peer_id())
.field("local_addr", &self.local_addr())
.finish_non_exhaustive()
}
}
impl Node {
// === Creation ===
/// Create a node with automatic configuration
///
/// This is the recommended way to create a node. It will:
/// - Bind to a random port on all interfaces (0.0.0.0:0)
/// - Generate a fresh Ed25519 keypair
/// - Enable all NAT traversal capabilities
/// - Use 100% post-quantum cryptography
///
/// # Example
///
/// ```rust,ignore
/// let node = Node::new().await?;
/// ```
pub async fn new() -> Result<Self, NodeError> {
Self::with_config(NodeConfig::default()).await
}
/// Create a node with a specific bind address
///
/// Use this when you need a specific port for firewall rules or port forwarding.
///
/// # Example
///
/// ```rust,ignore
/// let node = Node::bind("0.0.0.0:9000".parse()?).await?;
/// ```
pub async fn bind(addr: SocketAddr) -> Result<Self, NodeError> {
Self::with_config(NodeConfig::with_bind_addr(addr)).await
}
/// Create a node with known peers
///
/// Use this when you have a list of known peers to connect to initially.
/// These can be any nodes in the network - they'll help with NAT traversal.
///
/// # Example
///
/// ```rust,ignore
/// let node = Node::with_peers(vec![
/// "quic.saorsalabs.com:9000".parse()?,
/// "peer2.example.com:9000".parse()?,
/// ]).await?;
/// ```
pub async fn with_peers(peers: Vec<SocketAddr>) -> Result<Self, NodeError> {
Self::with_config(NodeConfig::with_known_peers(peers)).await
}
/// Create a node with an existing keypair
///
/// Use this for persistent identity across restarts. The peer ID
/// is derived from the public key, so using the same keypair
/// gives you the same peer ID.
///
/// # Example
///
/// ```rust,ignore
/// let (public_key, secret_key) = load_keypair_from_file("~/.ant-quic/identity.key")?;
/// let node = Node::with_keypair(public_key, secret_key).await?;
/// ```
pub async fn with_keypair(
public_key: MlDsaPublicKey,
secret_key: MlDsaSecretKey,
) -> Result<Self, NodeError> {
Self::with_config(NodeConfig::with_keypair(public_key, secret_key)).await
}
/// Create a node with a HostIdentity for persistent encrypted identity
///
/// This is the recommended way to create a node with persistent identity.
/// The keypair is encrypted at rest using a key derived from the HostIdentity.
///
/// # Arguments
///
/// * `host` - The HostIdentity for key derivation
/// * `network_id` - Network identifier for per-network keypair isolation
/// * `storage_dir` - Directory to store the encrypted keypair
///
/// # Example
///
/// ```rust,ignore
/// use ant_quic::{Node, HostIdentity};
///
/// let host = HostIdentity::generate();
/// let node = Node::with_host_identity(
/// &host,
/// b"my-network",
/// "/var/lib/ant-quic",
/// ).await?;
/// ```
pub async fn with_host_identity(
host: &HostIdentity,
network_id: &[u8],
storage_dir: impl AsRef<std::path::Path>,
) -> Result<Self, NodeError> {
let (public_key, secret_key) =
load_or_generate_endpoint_keypair(host, network_id, storage_dir.as_ref()).map_err(
|e| NodeError::Creation(format!("Failed to load/generate keypair: {e}")),
)?;
Self::with_keypair(public_key, secret_key).await
}
/// Create a node with full configuration
///
/// For power users who need specific settings. Most applications
/// should use `Node::new()` or one of the convenience methods.
///
/// # Example
///
/// ```rust,ignore
/// let config = NodeConfig::builder()
/// .bind_addr("0.0.0.0:9000".parse()?)
/// .known_peer("quic.saorsalabs.com:9000".parse()?)
/// .keypair(load_keypair()?)
/// .build();
///
/// let node = Node::with_config(config).await?;
/// ```
pub async fn with_config(config: NodeConfig) -> Result<Self, NodeError> {
// Convert NodeConfig to P2pConfig
let mut p2p_config = P2pConfig::default();
// Build transport registry first (before any partial moves)
p2p_config.transport_registry = config.build_transport_registry();
if let Some(bind_addr) = config.bind_addr {
p2p_config.bind_addr = Some(bind_addr.into());
}
p2p_config.known_peers = config.known_peers.into_iter().map(Into::into).collect();
p2p_config.keypair = config.keypair;
if let Some(capacity) = config.data_channel_capacity {
p2p_config.data_channel_capacity = capacity;
}
if let Some(streams) = config.max_concurrent_uni_streams {
p2p_config.max_concurrent_uni_streams = streams;
}
// Create event channel
let (event_tx, _) = broadcast::channel(256);
// Create P2pEndpoint
let endpoint = P2pEndpoint::new(p2p_config)
.await
.map_err(NodeError::Endpoint)?;
info!("Node created with peer ID: {:?}", endpoint.peer_id());
let inner = Arc::new(endpoint);
// Spawn event bridge task to forward P2pEvent -> NodeEvent
Self::spawn_event_bridge(Arc::clone(&inner), event_tx.clone());
Ok(Self {
inner,
start_time: Instant::now(),
event_tx,
})
}
/// Spawn a background task to bridge P2pEvents to NodeEvents
fn spawn_event_bridge(endpoint: Arc<P2pEndpoint>, event_tx: broadcast::Sender<NodeEvent>) {
let mut p2p_events = endpoint.subscribe();
tokio::spawn(async move {
loop {
match p2p_events.recv().await {
Ok(p2p_event) => {
if let Some(node_event) = Self::convert_event(p2p_event) {
// Ignore send errors - means no subscribers
let _ = event_tx.send(node_event);
}
}
Err(broadcast::error::RecvError::Closed) => {
// Channel closed, endpoint shutting down
break;
}
Err(broadcast::error::RecvError::Lagged(n)) => {
// Subscriber lagged behind, log and continue
tracing::warn!("Event bridge lagged by {} events", n);
}
}
}
});
}
/// Convert a P2pEvent to a NodeEvent
///
/// Uses the From trait implementation for DisconnectReason conversion.
fn convert_event(p2p_event: P2pEvent) -> Option<NodeEvent> {
match p2p_event {
P2pEvent::PeerConnected {
peer_id,
addr,
side: _,
} => Some(NodeEvent::PeerConnected {
peer_id,
addr,
direct: true, // P2pEvent doesn't distinguish, assume direct
}),
P2pEvent::PeerDisconnected { peer_id, reason } => Some(NodeEvent::PeerDisconnected {
peer_id,
reason: reason.into(), // Use From trait
}),
P2pEvent::ExternalAddressDiscovered { addr } => {
Some(NodeEvent::ExternalAddressDiscovered { addr })
}
P2pEvent::DataReceived { peer_id, bytes } => Some(NodeEvent::DataReceived {
peer_id,
stream_id: 0, // P2pEvent doesn't track stream IDs
bytes,
}),
P2pEvent::ConstrainedDataReceived {
remote_addr,
connection_id,
data,
} => {
// For constrained data, derive a synthetic peer ID from the transport address
let synthetic_peer_id = {
use std::collections::hash_map::DefaultHasher;
use std::hash::{Hash, Hasher};
let synthetic_addr = remote_addr.to_synthetic_socket_addr();
let mut hasher = DefaultHasher::new();
synthetic_addr.hash(&mut hasher);
let hash = hasher.finish();
let mut peer_id_bytes = [0u8; 32];
peer_id_bytes[..8].copy_from_slice(&hash.to_le_bytes());
PeerId(peer_id_bytes)
};
Some(NodeEvent::DataReceived {
peer_id: synthetic_peer_id,
stream_id: connection_id as u64,
bytes: data.len(),
})
}
// Events without direct NodeEvent equivalents are ignored
P2pEvent::NatTraversalProgress { .. }
| P2pEvent::BootstrapStatus { .. }
| P2pEvent::PeerAuthenticated { .. } => None,
}
}
// === Identity ===
/// Get this node's peer ID
///
/// The peer ID is derived from the Ed25519 public key and is
/// the unique identifier for this node on the network.
pub fn peer_id(&self) -> PeerId {
self.inner.peer_id()
}
/// Get the local bind address
///
/// Returns `None` if the endpoint hasn't bound yet.
pub fn local_addr(&self) -> Option<SocketAddr> {
self.inner.local_addr()
}
/// Get the observed external address
///
/// This is the address as seen by other peers on the network.
/// Returns `None` if no external address has been discovered yet.
pub fn external_addr(&self) -> Option<SocketAddr> {
self.inner.external_addr()
}
/// Get the ML-DSA-65 public key bytes (1952 bytes)
pub fn public_key_bytes(&self) -> &[u8] {
self.inner.public_key_bytes()
}
/// Get access to the underlying P2pEndpoint for advanced operations.
pub fn inner_endpoint(&self) -> &Arc<P2pEndpoint> {
&self.inner
}
/// Get the transport registry for this node
///
/// The transport registry contains all registered transport providers (UDP, BLE, etc.)
/// that this node can use for connectivity.
pub fn transport_registry(&self) -> &crate::transport::TransportRegistry {
self.inner.transport_registry()
}
// === Connections ===
/// Connect to a peer by address
///
/// This creates a direct connection to the specified address.
/// NAT traversal is handled automatically if needed.
///
/// # Example
///
/// ```rust,ignore
/// let conn = node.connect_addr("quic.saorsalabs.com:9000".parse()?).await?;
/// println!("Connected to: {:?}", conn.peer_id);
/// ```
pub async fn connect_addr(&self, addr: SocketAddr) -> Result<PeerConnection, NodeError> {
self.inner.connect(addr).await.map_err(NodeError::Endpoint)
}
/// Connect to a peer by ID
///
/// This uses NAT traversal to find and connect to the peer.
/// A coordinator (known peer) is used to help with hole punching.
///
/// # Example
///
/// ```rust,ignore
/// let conn = node.connect(peer_id).await?;
/// ```
pub async fn connect(&self, peer_id: PeerId) -> Result<PeerConnection, NodeError> {
self.inner
.connect_to_peer(peer_id, None)
.await
.map_err(NodeError::Endpoint)
}
/// Accept an incoming connection
///
/// Waits for and accepts the next incoming connection.
/// Returns `None` if the node is shutting down.
///
/// # Example
///
/// ```rust,ignore
/// while let Some(conn) = node.accept().await {
/// println!("Accepted connection from: {:?}", conn.peer_id);
/// // Handle connection...
/// }
/// ```
pub async fn accept(&self) -> Option<PeerConnection> {
self.inner.accept().await
}
/// Add a known peer dynamically
///
/// Known peers help with NAT traversal and peer discovery.
/// You can add more peers at runtime.
pub async fn add_peer(&self, addr: SocketAddr) {
self.inner.add_bootstrap(addr).await;
}
/// Connect to all known peers
///
/// Returns the number of successful connections.
pub async fn connect_known_peers(&self) -> Result<usize, NodeError> {
self.inner
.connect_known_peers()
.await
.map_err(NodeError::Endpoint)
}
/// Disconnect from a peer
pub async fn disconnect(&self, peer_id: &PeerId) -> Result<(), NodeError> {
self.inner
.disconnect(peer_id)
.await
.map_err(NodeError::Endpoint)
}
/// Get list of connected peers
pub async fn connected_peers(&self) -> Vec<PeerConnection> {
self.inner.connected_peers().await
}
/// Check if connected to a peer
pub async fn is_connected(&self, peer_id: &PeerId) -> bool {
self.inner.is_connected(peer_id).await
}
/// Query the health status of a connection to a specific peer.
///
/// Returns `None` if the peer is not connected.
pub async fn connection_health(&self, peer_id: &PeerId) -> Option<crate::ConnectionHealth> {
self.inner.connection_health(peer_id).await
}
// === Messaging ===
/// Send data to a peer
pub async fn send(&self, peer_id: &PeerId, data: &[u8]) -> Result<(), NodeError> {
self.inner
.send(peer_id, data)
.await
.map_err(NodeError::Endpoint)
}
/// Receive data from any peer
pub async fn recv(&self) -> Result<(PeerId, Vec<u8>), NodeError> {
self.inner.recv().await.map_err(NodeError::Endpoint)
}
// === Observability ===
/// Get a snapshot of the node's current status
///
/// This provides complete visibility into the node's state,
/// including NAT type, connectivity, relay status, and performance.
///
/// # Example
///
/// ```rust,ignore
/// let status = node.status().await;
/// println!("NAT type: {}", status.nat_type);
/// println!("Connected peers: {}", status.connected_peers);
/// println!("Acting as relay: {}", status.is_relaying);
/// ```
pub async fn status(&self) -> NodeStatus {
let stats = self.inner.stats().await;
let nat_stats = self.inner.nat_stats().ok();
let connected_peers = self.inner.connected_peers().await;
// Determine NAT type from stats
let nat_type = self.detect_nat_type(&stats, nat_stats.as_ref());
// Check if we have public IP
let local_addr = self.local_addr();
let external_addr = self.external_addr();
let has_public_ip = match (local_addr, external_addr) {
(Some(local), Some(external)) => {
// Public if external matches local (ignoring port differences)
local.ip() == external.ip()
}
_ => false,
};
// Collect ALL external addresses (both IPv4 and IPv6) from all
// connections and QUIC paths. This is critical for dual-stack nodes
// where different peers report different address families.
let mut external_addrs = self.inner.all_external_addrs();
// Ensure the primary external address is included (backward compat)
if let Some(addr) = external_addr {
if !external_addrs.contains(&addr) {
external_addrs.insert(0, addr);
}
}
// Calculate hole punch success rate
let hole_punch_success_rate = if stats.nat_traversal_attempts > 0 {
stats.nat_traversal_successes as f64 / stats.nat_traversal_attempts as f64
} else {
0.0
};
// Determine if we can help with traversal
let can_receive_direct =
has_public_ip || nat_type == NatType::FullCone || nat_type == NatType::None;
// Check relay status from NAT stats
// Currently, relay status is indicated by having relayed_connections > 0
// and active sessions that may be acting as relays
let (is_relaying, relay_sessions, relay_bytes_forwarded) = if let Some(ref nat) = nat_stats
{
// If we have any active sessions and are accepting connections,
// we're potentially relaying
let relaying = nat.relayed_connections > 0 && can_receive_direct;
(
relaying,
if relaying { nat.active_sessions } else { 0 },
0u64, // Not tracked yet - future enhancement
)
} else {
(false, 0, 0)
};
// Check coordination status
// Any node with active sessions is acting as a coordinator
let (is_coordinating, coordination_sessions) = if let Some(ref nat) = nat_stats {
(nat.active_sessions > 0, nat.active_sessions)
} else {
(false, 0)
};
// Calculate average RTT from connected peers
let mut total_rtt = Duration::ZERO;
let mut rtt_count = 0u32;
for peer in &connected_peers {
if let Some(metrics) = self.inner.connection_metrics(&peer.peer_id).await {
if let Some(rtt) = metrics.rtt {
total_rtt += rtt;
rtt_count += 1;
}
}
}
let avg_rtt = if rtt_count > 0 {
total_rtt / rtt_count
} else {
Duration::ZERO
};
NodeStatus {
peer_id: self.peer_id(),
local_addr: local_addr.unwrap_or_else(|| {
"0.0.0.0:0".parse().unwrap_or_else(|_| {
SocketAddr::new(std::net::IpAddr::V4(std::net::Ipv4Addr::UNSPECIFIED), 0)
})
}),
external_addrs,
nat_type,
can_receive_direct,
has_public_ip,
connected_peers: connected_peers.len(),
active_connections: stats.active_connections,
pending_connections: 0, // Not tracked yet
direct_connections: stats.direct_connections,
relayed_connections: stats.relayed_connections,
hole_punch_success_rate,
is_relaying,
relay_sessions,
relay_bytes_forwarded,
is_coordinating,
coordination_sessions,
avg_rtt,
uptime: self.start_time.elapsed(),
}
}
/// Subscribe to node events
///
/// Returns a receiver for all significant node events including
/// connections, disconnections, NAT detection, and relay activity.
///
/// # Example
///
/// ```rust,ignore
/// let mut events = node.subscribe();
/// tokio::spawn(async move {
/// while let Ok(event) = events.recv().await {
/// match event {
/// NodeEvent::PeerConnected { peer_id, .. } => {
/// println!("Connected: {:?}", peer_id);
/// }
/// _ => {}
/// }
/// }
/// });
/// ```
pub fn subscribe(&self) -> broadcast::Receiver<NodeEvent> {
self.event_tx.subscribe()
}
/// Subscribe to raw P2pEvents (for advanced use)
///
/// This provides access to the underlying P2pEndpoint events.
/// Most applications should use `subscribe()` for NodeEvents.
pub fn subscribe_raw(&self) -> broadcast::Receiver<P2pEvent> {
self.inner.subscribe()
}
// === Shutdown ===
/// Gracefully shut down the node
///
/// This closes all connections and releases resources.
pub async fn shutdown(self) {
self.inner.shutdown().await;
}
/// Check if the node is still running
pub fn is_running(&self) -> bool {
self.inner.is_running()
}
// === Private Helpers ===
/// Detect NAT type from statistics
fn detect_nat_type(
&self,
stats: &crate::p2p_endpoint::EndpointStats,
nat_stats: Option<&crate::nat_traversal_api::NatTraversalStatistics>,
) -> NatType {
// If we have lots of direct connections and no relayed, likely no/easy NAT
if stats.direct_connections > 0 && stats.relayed_connections == 0 {
if let Some(nat) = nat_stats {
// Calculate direct connection rate
let total = nat.direct_connections + nat.relayed_connections;
if total > 0 {
let direct_rate = nat.direct_connections as f64 / total as f64;
if direct_rate > 0.9 {
return NatType::FullCone;
}
}
}
return NatType::FullCone; // Assume easy NAT if all direct
}
// If we have mixed connections, harder NAT
if stats.direct_connections > 0 && stats.relayed_connections > 0 {
if let Some(nat) = nat_stats {
// Calculate success rate from total attempts vs successful connections
let success_rate = if nat.total_attempts > 0 {
nat.successful_connections as f64 / nat.total_attempts as f64
} else {
0.0
};
if success_rate > 0.7 {
return NatType::PortRestricted;
} else if success_rate > 0.3 {
return NatType::AddressRestricted;
}
}
return NatType::PortRestricted;
}
// If mostly relayed, likely symmetric NAT
if stats.relayed_connections > stats.direct_connections {
return NatType::Symmetric;
}
// Not enough data yet
NatType::Unknown
}
}
// Enable cloning through Arc
impl Clone for Node {
fn clone(&self) -> Self {
Self {
inner: Arc::clone(&self.inner),
start_time: self.start_time,
event_tx: self.event_tx.clone(),
}
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::derive_peer_id_from_public_key;
#[tokio::test]
async fn test_node_new_default() {
let node = Node::new().await;
assert!(node.is_ok(), "Node::new() should succeed: {:?}", node.err());
let node = node.unwrap();
assert!(node.is_running());
// Peer ID should be valid (non-zero)
let peer_id = node.peer_id();
assert_ne!(peer_id.0, [0u8; 32]);
node.shutdown().await;
}
#[tokio::test]
async fn test_node_bind() {
let addr: SocketAddr = "127.0.0.1:0".parse().unwrap();
let node = Node::bind(addr).await;
assert!(node.is_ok(), "Node::bind() should succeed");
let node = node.unwrap();
assert!(node.local_addr().is_some());
node.shutdown().await;
}
#[tokio::test]
async fn test_node_with_peers() {
let peers = vec!["127.0.0.1:9000".parse().unwrap()];
let node = Node::with_peers(peers).await;
assert!(node.is_ok(), "Node::with_peers() should succeed");
node.unwrap().shutdown().await;
}
#[tokio::test]
async fn test_node_with_config() {
let addr: SocketAddr = "127.0.0.1:0".parse().unwrap();
let config = NodeConfig::builder().bind_addr(addr).build();
let node = Node::with_config(config).await;
assert!(node.is_ok(), "Node::with_config() should succeed");
node.unwrap().shutdown().await;
}
#[tokio::test]
async fn test_node_status() {
let node = Node::new().await.unwrap();
let status = node.status().await;
// Check status fields are populated
assert_ne!(status.peer_id.0, [0u8; 32]);
assert_eq!(status.connected_peers, 0); // No connections yet
node.shutdown().await;
}
#[tokio::test]
async fn test_node_subscribe() {
let node = Node::new().await.unwrap();
let _events = node.subscribe();
// Just verify subscription works
node.shutdown().await;
}
#[tokio::test]
async fn test_node_is_clone() {
let node1 = Node::new().await.unwrap();
let node2 = node1.clone();
// Both should have same peer ID
assert_eq!(node1.peer_id(), node2.peer_id());
node1.shutdown().await;
// node2 still references the same Arc, so shutdown already happened
}
#[tokio::test]
async fn test_node_debug() {
let node = Node::new().await.unwrap();
let debug_str = format!("{:?}", node);
assert!(debug_str.contains("Node"));
assert!(debug_str.contains("peer_id"));
node.shutdown().await;
}
#[tokio::test]
async fn test_node_identity() {
use crate::crypto::raw_public_keys::key_utils::derive_peer_id_from_key_bytes;
let node = Node::new().await.unwrap();
// Verify identity methods
let peer_id = node.peer_id();
let public_key = node.public_key_bytes();
// Peer ID should be derived from public key (ML-DSA-65)
let derived = derive_peer_id_from_key_bytes(public_key).unwrap();
assert_eq!(peer_id, derived);
node.shutdown().await;
}
#[tokio::test]
async fn test_connected_peers_empty() {
let node = Node::new().await.unwrap();
let peers = node.connected_peers().await;
assert!(peers.is_empty());
node.shutdown().await;
}
#[tokio::test]
async fn test_node_error_types() {
// Test error conversions
let err = NodeError::Creation("test".to_string());
assert!(err.to_string().contains("test"));
let err = NodeError::Connection("connection failed".to_string());
assert!(err.to_string().contains("connection"));
let err = NodeError::ShuttingDown;
assert!(err.to_string().contains("shutting down"));
}
#[tokio::test]
async fn test_node_with_keypair_persistence() {
use crate::crypto::raw_public_keys::key_utils::generate_ml_dsa_keypair;
// Generate an ML-DSA-65 keypair
let (public_key, secret_key) = generate_ml_dsa_keypair().unwrap();
let expected_peer_id = derive_peer_id_from_public_key(&public_key);
let expected_public_key_bytes = public_key.as_bytes().to_vec();
// Create node with the keypair
let node = Node::with_keypair(public_key, secret_key).await.unwrap();
// Verify the node uses the same identity
assert_eq!(node.peer_id(), expected_peer_id);
assert_eq!(node.public_key_bytes(), expected_public_key_bytes);
node.shutdown().await;
}
#[tokio::test]
async fn test_node_keypair_via_config() {
use crate::crypto::raw_public_keys::key_utils::generate_ml_dsa_keypair;
// Generate an ML-DSA-65 keypair
let (public_key, secret_key) = generate_ml_dsa_keypair().unwrap();
let expected_peer_id = derive_peer_id_from_public_key(&public_key);
let expected_public_key_bytes = public_key.as_bytes().to_vec();
// Create node via config with keypair
let config = NodeConfig::with_keypair(public_key, secret_key);
let node = Node::with_config(config).await.unwrap();
// Verify the node uses the same identity
assert_eq!(node.peer_id(), expected_peer_id);
assert_eq!(node.public_key_bytes(), expected_public_key_bytes);
node.shutdown().await;
}
#[tokio::test]
async fn test_node_event_bridge_exists() {
let node = Node::new().await.unwrap();
// Subscribe to events - this should work
let mut events = node.subscribe();
// The event channel should be connected (won't receive anything yet,
// but the bridge task should be running)
// We can't easily test event reception without connections,
// but we verify the infrastructure is in place
assert!(events.try_recv().is_err()); // No events yet
node.shutdown().await;
}
#[tokio::test]
async fn test_node_with_host_identity() {
use crate::host_identity::HostIdentity;
// Create a temporary directory for storage
let temp_dir =
std::env::temp_dir().join(format!("ant-quic-test-node-{}", std::process::id()));
let _ = std::fs::create_dir_all(&temp_dir);
// Generate a HostIdentity
let host = HostIdentity::generate();
let network_id = b"test-network";
// Create first node with host identity
let node1 = Node::with_host_identity(&host, network_id, &temp_dir)
.await
.unwrap();
let peer_id_1 = node1.peer_id();
let public_key_1 = node1.public_key_bytes().to_vec();
// Verify the node is running
assert!(node1.is_running());
// Shutdown and cleanup
node1.shutdown().await;
// Create second node with same host identity - should have same identity
let node2 = Node::with_host_identity(&host, network_id, &temp_dir)
.await
.unwrap();
let peer_id_2 = node2.peer_id();
let public_key_2 = node2.public_key_bytes().to_vec();
// Verify both nodes have the same identity
assert_eq!(peer_id_1, peer_id_2);
assert_eq!(public_key_1, public_key_2);
node2.shutdown().await;
// Cleanup temp directory
let _ = std::fs::remove_dir_all(&temp_dir);
}
#[tokio::test]
async fn test_node_host_identity_per_network_isolation() {
use crate::host_identity::HostIdentity;
// Create a temporary directory for storage
let temp_dir =
std::env::temp_dir().join(format!("ant-quic-test-isolation-{}", std::process::id()));
let _ = std::fs::create_dir_all(&temp_dir);
// Generate a HostIdentity
let host = HostIdentity::generate();
// Create nodes with different network IDs
let node1 = Node::with_host_identity(&host, b"network-1", &temp_dir)
.await
.unwrap();
let peer_id_1 = node1.peer_id();
let node2 = Node::with_host_identity(&host, b"network-2", &temp_dir)
.await
.unwrap();
let peer_id_2 = node2.peer_id();
// Different networks should have different identities (privacy)
assert_ne!(peer_id_1, peer_id_2);
node1.shutdown().await;
node2.shutdown().await;
// Cleanup temp directory
let _ = std::fs::remove_dir_all(&temp_dir);
}
}