1pub mod tcp;
8pub mod tor;
9pub mod udp;
10#[cfg(feature = "webrtc-transport")]
11pub mod webrtc;
12
13#[cfg(feature = "sim-transport")]
14pub mod sim;
15
16#[cfg(any(target_os = "linux", target_os = "macos"))]
17pub mod ethernet;
18
19#[cfg(target_os = "linux")]
20pub mod ble;
21
22mod handle;
23mod packet_channel;
24
25#[cfg(test)]
26mod tests;
27
28pub use handle::TransportHandle;
29pub(crate) use packet_channel::received_timestamp_ms;
30pub use packet_channel::{PacketRx, PacketTx, ReceivedPacket, packet_channel};
31
32use secp256k1::XOnlyPublicKey;
33use std::fmt;
34use std::net::SocketAddr;
35use std::sync::Arc;
36use std::time::Duration;
37use thiserror::Error;
38
39#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
45pub struct TransportId(u32);
46
47impl TransportId {
48 pub fn new(id: u32) -> Self {
50 Self(id)
51 }
52
53 pub fn as_u32(&self) -> u32 {
55 self.0
56 }
57}
58
59impl fmt::Display for TransportId {
60 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
61 write!(f, "transport:{}", self.0)
62 }
63}
64
65#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
67pub struct LinkId(u64);
68
69impl LinkId {
70 pub fn new(id: u64) -> Self {
72 Self(id)
73 }
74
75 pub fn as_u64(&self) -> u64 {
77 self.0
78 }
79}
80
81impl fmt::Display for LinkId {
82 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
83 write!(f, "link:{}", self.0)
84 }
85}
86
87#[derive(Debug, Error)]
93pub enum TransportError {
94 #[error("transport not started")]
95 NotStarted,
96
97 #[error("transport already started")]
98 AlreadyStarted,
99
100 #[error("transport failed to start: {0}")]
101 StartFailed(String),
102
103 #[error("transport shutdown failed: {0}")]
104 ShutdownFailed(String),
105
106 #[error("link failed: {0}")]
107 LinkFailed(String),
108
109 #[error("send failed: {0}")]
110 SendFailed(String),
111
112 #[error("receive failed: {0}")]
113 RecvFailed(String),
114
115 #[error("invalid transport address: {0}")]
116 InvalidAddress(String),
117
118 #[error("mtu exceeded: packet {packet_size} > mtu {mtu}")]
119 MtuExceeded { packet_size: usize, mtu: u16 },
120
121 #[error("transport timeout")]
122 Timeout,
123
124 #[error("connection refused")]
125 ConnectionRefused,
126
127 #[error("transport not supported: {0}")]
128 NotSupported(String),
129
130 #[error("io error: {0}")]
131 Io(#[from] std::io::Error),
132}
133
134impl TransportError {
135 pub fn is_local_route_unavailable(&self) -> bool {
138 match self {
139 TransportError::Io(error) => is_local_route_error_kind(error.kind()),
140 TransportError::SendFailed(message) => is_local_route_error_text(message),
141 _ => false,
142 }
143 }
144}
145
146fn is_local_route_error_kind(kind: std::io::ErrorKind) -> bool {
147 matches!(
148 kind,
149 std::io::ErrorKind::NetworkUnreachable
150 | std::io::ErrorKind::HostUnreachable
151 | std::io::ErrorKind::AddrNotAvailable
152 )
153}
154
155fn is_local_route_error_text(message: &str) -> bool {
156 let lower = message.to_ascii_lowercase();
157 lower.contains("network is unreachable")
158 || lower.contains("no route to host")
159 || lower.contains("host is unreachable")
160 || lower.contains("can't assign requested address")
161 || lower.contains("cannot assign requested address")
162 || lower.contains("os error 51")
163 || lower.contains("os error 65")
164 || lower.contains("os error 49")
165}
166
167#[derive(Clone, Debug, PartialEq, Eq)]
173pub struct TransportType {
174 pub name: &'static str,
176 pub connection_oriented: bool,
178 pub reliable: bool,
180}
181
182impl TransportType {
183 pub const UDP: TransportType = TransportType {
185 name: "udp",
186 connection_oriented: false,
187 reliable: false,
188 };
189
190 pub const TCP: TransportType = TransportType {
192 name: "tcp",
193 connection_oriented: true,
194 reliable: true,
195 };
196
197 pub const ETHERNET: TransportType = TransportType {
199 name: "ethernet",
200 connection_oriented: false,
201 reliable: false,
202 };
203
204 pub const WIFI: TransportType = TransportType {
206 name: "wifi",
207 connection_oriented: false,
208 reliable: false,
209 };
210
211 pub const TOR: TransportType = TransportType {
213 name: "tor",
214 connection_oriented: true,
215 reliable: true,
216 };
217
218 pub const SERIAL: TransportType = TransportType {
220 name: "serial",
221 connection_oriented: false,
222 reliable: true, };
224
225 pub const BLE: TransportType = TransportType {
227 name: "ble",
228 connection_oriented: true,
229 reliable: true, };
231
232 pub const WEBRTC: TransportType = TransportType {
234 name: "webrtc",
235 connection_oriented: true,
236 reliable: false,
237 };
238
239 #[cfg(feature = "sim-transport")]
241 pub const SIM: TransportType = TransportType {
242 name: "sim",
243 connection_oriented: false,
244 reliable: false,
245 };
246
247 pub fn is_connectionless(&self) -> bool {
249 !self.connection_oriented
250 }
251}
252
253impl fmt::Display for TransportType {
254 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
255 write!(f, "{}", self.name)
256 }
257}
258
259#[derive(Clone, Copy, Debug, PartialEq, Eq)]
265pub enum TransportState {
266 Configured,
268 Starting,
270 Up,
272 Down,
274 Failed,
276}
277
278impl TransportState {
279 pub fn is_operational(&self) -> bool {
281 matches!(self, TransportState::Up)
282 }
283
284 pub fn can_start(&self) -> bool {
286 matches!(
287 self,
288 TransportState::Configured | TransportState::Down | TransportState::Failed
289 )
290 }
291
292 pub fn is_terminal(&self) -> bool {
294 matches!(self, TransportState::Failed)
295 }
296}
297
298impl fmt::Display for TransportState {
299 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
300 let s = match self {
301 TransportState::Configured => "configured",
302 TransportState::Starting => "starting",
303 TransportState::Up => "up",
304 TransportState::Down => "down",
305 TransportState::Failed => "failed",
306 };
307 write!(f, "{}", s)
308 }
309}
310
311#[derive(Clone, Copy, Debug, PartialEq, Eq)]
317pub enum LinkState {
318 Connecting,
320 Connected,
322 Disconnected,
324 Failed,
326}
327
328impl LinkState {
329 pub fn is_operational(&self) -> bool {
331 matches!(self, LinkState::Connected)
332 }
333
334 pub fn is_terminal(&self) -> bool {
336 matches!(self, LinkState::Disconnected | LinkState::Failed)
337 }
338}
339
340impl fmt::Display for LinkState {
341 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
342 let s = match self {
343 LinkState::Connecting => "connecting",
344 LinkState::Connected => "connected",
345 LinkState::Disconnected => "disconnected",
346 LinkState::Failed => "failed",
347 };
348 write!(f, "{}", s)
349 }
350}
351
352#[derive(Clone, Copy, Debug, PartialEq, Eq)]
354pub enum LinkDirection {
355 Outbound,
357 Inbound,
359}
360
361impl fmt::Display for LinkDirection {
362 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
363 let s = match self {
364 LinkDirection::Outbound => "outbound",
365 LinkDirection::Inbound => "inbound",
366 };
367 write!(f, "{}", s)
368 }
369}
370
371#[derive(Clone, PartialEq, Eq, Hash)]
384pub struct TransportAddr(Arc<[u8]>);
385
386impl TransportAddr {
387 pub fn new(bytes: Vec<u8>) -> Self {
389 Self(bytes.into())
390 }
391
392 pub fn from_bytes(bytes: &[u8]) -> Self {
394 Self(Arc::from(bytes))
395 }
396
397 pub fn from_string(s: &str) -> Self {
399 Self(Arc::from(s.as_bytes()))
400 }
401
402 pub fn from_socket_addr(addr: std::net::SocketAddr) -> Self {
414 use std::io::Write;
415 let mut buf = Vec::with_capacity(56);
419 write!(&mut buf, "{addr}").expect("Vec<u8>::write_fmt is infallible");
423 Self(buf.into())
424 }
425
426 pub fn as_bytes(&self) -> &[u8] {
428 &self.0
429 }
430
431 pub fn as_str(&self) -> Option<&str> {
433 std::str::from_utf8(&self.0).ok()
434 }
435
436 pub fn len(&self) -> usize {
438 self.0.len()
439 }
440
441 pub fn is_empty(&self) -> bool {
443 self.0.is_empty()
444 }
445}
446
447impl fmt::Debug for TransportAddr {
448 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
449 match self.as_str() {
450 Some(s) => write!(f, "TransportAddr(\"{}\")", s),
451 None => write!(f, "TransportAddr({:?})", self.0),
452 }
453 }
454}
455
456impl fmt::Display for TransportAddr {
457 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
458 match self.as_str() {
460 Some(s) => write!(f, "{}", s),
461 None => {
462 for byte in self.0.iter() {
463 write!(f, "{:02x}", byte)?;
464 }
465 Ok(())
466 }
467 }
468 }
469}
470
471impl From<&str> for TransportAddr {
472 fn from(s: &str) -> Self {
473 Self::from_string(s)
474 }
475}
476
477impl From<String> for TransportAddr {
478 fn from(s: String) -> Self {
479 Self(s.into_bytes().into())
480 }
481}
482
483#[derive(Clone, Debug, Default)]
489pub struct LinkStats {
490 pub packets_sent: u64,
492 pub packets_recv: u64,
494 pub bytes_sent: u64,
496 pub bytes_recv: u64,
498 pub last_recv_ms: u64,
500 rtt_estimate: Option<Duration>,
502 pub loss_rate: f32,
504 pub throughput_estimate: u64,
506}
507
508impl LinkStats {
509 pub fn new() -> Self {
511 Self::default()
512 }
513
514 pub fn record_sent(&mut self, bytes: usize) {
516 self.packets_sent += 1;
517 self.bytes_sent += bytes as u64;
518 }
519
520 pub fn record_recv(&mut self, bytes: usize, timestamp_ms: u64) {
522 self.packets_recv += 1;
523 self.bytes_recv += bytes as u64;
524 self.last_recv_ms = timestamp_ms;
525 }
526
527 pub fn rtt_estimate(&self) -> Option<Duration> {
529 self.rtt_estimate
530 }
531
532 pub fn update_rtt(&mut self, rtt: Duration) {
536 match self.rtt_estimate {
537 Some(old_rtt) => {
538 let alpha = 0.2;
539 let new_rtt_nanos = (alpha * rtt.as_nanos() as f64
540 + (1.0 - alpha) * old_rtt.as_nanos() as f64)
541 as u64;
542 self.rtt_estimate = Some(Duration::from_nanos(new_rtt_nanos));
543 }
544 None => {
545 self.rtt_estimate = Some(rtt);
546 }
547 }
548 }
549
550 pub fn time_since_recv(&self, current_time_ms: u64) -> u64 {
552 if self.last_recv_ms == 0 {
553 return u64::MAX;
554 }
555 current_time_ms.saturating_sub(self.last_recv_ms)
556 }
557
558 pub fn reset(&mut self) {
560 *self = Self::default();
561 }
562}
563
564#[derive(Clone, Debug)]
570pub struct Link {
571 link_id: LinkId,
573 transport_id: TransportId,
575 remote_addr: TransportAddr,
577 direction: LinkDirection,
579 state: LinkState,
581 base_rtt: Duration,
583 stats: LinkStats,
585 created_at: u64,
587}
588
589impl Link {
590 pub fn new(
592 link_id: LinkId,
593 transport_id: TransportId,
594 remote_addr: TransportAddr,
595 direction: LinkDirection,
596 base_rtt: Duration,
597 ) -> Self {
598 Self {
599 link_id,
600 transport_id,
601 remote_addr,
602 direction,
603 state: LinkState::Connecting,
604 base_rtt,
605 stats: LinkStats::new(),
606 created_at: 0,
607 }
608 }
609
610 pub fn new_with_timestamp(
612 link_id: LinkId,
613 transport_id: TransportId,
614 remote_addr: TransportAddr,
615 direction: LinkDirection,
616 base_rtt: Duration,
617 created_at: u64,
618 ) -> Self {
619 let mut link = Self::new(link_id, transport_id, remote_addr, direction, base_rtt);
620 link.created_at = created_at;
621 link
622 }
623
624 pub fn connectionless(
629 link_id: LinkId,
630 transport_id: TransportId,
631 remote_addr: TransportAddr,
632 direction: LinkDirection,
633 base_rtt: Duration,
634 ) -> Self {
635 let mut link = Self::new(link_id, transport_id, remote_addr, direction, base_rtt);
636 link.state = LinkState::Connected;
637 link
638 }
639
640 pub fn link_id(&self) -> LinkId {
642 self.link_id
643 }
644
645 pub fn transport_id(&self) -> TransportId {
647 self.transport_id
648 }
649
650 pub fn remote_addr(&self) -> &TransportAddr {
652 &self.remote_addr
653 }
654
655 pub fn direction(&self) -> LinkDirection {
657 self.direction
658 }
659
660 pub fn state(&self) -> LinkState {
662 self.state
663 }
664
665 pub fn base_rtt(&self) -> Duration {
667 self.base_rtt
668 }
669
670 pub fn stats(&self) -> &LinkStats {
672 &self.stats
673 }
674
675 pub fn stats_mut(&mut self) -> &mut LinkStats {
677 &mut self.stats
678 }
679
680 pub fn created_at(&self) -> u64 {
682 self.created_at
683 }
684
685 pub fn set_created_at(&mut self, timestamp: u64) {
687 self.created_at = timestamp;
688 }
689
690 pub fn set_connected(&mut self) {
692 self.state = LinkState::Connected;
693 }
694
695 pub fn set_disconnected(&mut self) {
697 self.state = LinkState::Disconnected;
698 }
699
700 pub fn set_failed(&mut self) {
702 self.state = LinkState::Failed;
703 }
704
705 pub fn is_operational(&self) -> bool {
707 self.state.is_operational()
708 }
709
710 pub fn is_terminal(&self) -> bool {
712 self.state.is_terminal()
713 }
714
715 pub fn effective_rtt(&self) -> Duration {
717 self.stats.rtt_estimate().unwrap_or(self.base_rtt)
718 }
719
720 pub fn age(&self, current_time_ms: u64) -> u64 {
722 if self.created_at == 0 {
723 return 0;
724 }
725 current_time_ms.saturating_sub(self.created_at)
726 }
727}
728
729#[derive(Clone, Debug)]
735pub struct DiscoveredPeer {
736 pub transport_id: TransportId,
738 pub addr: TransportAddr,
740 pub pubkey_hint: Option<XOnlyPublicKey>,
742}
743
744impl DiscoveredPeer {
745 pub fn new(transport_id: TransportId, addr: TransportAddr) -> Self {
747 Self {
748 transport_id,
749 addr,
750 pubkey_hint: None,
751 }
752 }
753
754 pub fn with_hint(
756 transport_id: TransportId,
757 addr: TransportAddr,
758 pubkey: XOnlyPublicKey,
759 ) -> Self {
760 Self {
761 transport_id,
762 addr,
763 pubkey_hint: Some(pubkey),
764 }
765 }
766}
767
768pub trait Transport {
777 fn transport_id(&self) -> TransportId;
779
780 fn transport_type(&self) -> &TransportType;
782
783 fn state(&self) -> TransportState;
785
786 fn mtu(&self) -> u16;
788
789 fn link_mtu(&self, addr: &TransportAddr) -> u16 {
795 let _ = addr;
796 self.mtu()
797 }
798
799 fn start(&mut self) -> Result<(), TransportError>;
801
802 fn stop(&mut self) -> Result<(), TransportError>;
804
805 fn send(&self, addr: &TransportAddr, data: &[u8]) -> Result<(), TransportError>;
807
808 fn discover(&self) -> Result<Vec<DiscoveredPeer>, TransportError>;
810
811 fn auto_connect(&self) -> bool {
814 false
815 }
816
817 fn accept_connections(&self) -> bool {
820 true
821 }
822
823 fn close_connection(&self, _addr: &TransportAddr) {
829 }
831}
832
833#[derive(Clone, Debug, PartialEq, Eq)]
842pub enum ConnectionState {
843 None,
845 Connecting,
847 Connected,
849 Failed(String),
851}
852
853#[derive(Clone, Debug, Default)]
862pub struct TransportCongestion {
863 pub recv_drops: Option<u64>,
866}
867
868pub(crate) async fn resolve_socket_addr(
879 addr: &TransportAddr,
880) -> Result<SocketAddr, TransportError> {
881 resolve_socket_addrs(addr)
882 .await?
883 .into_iter()
884 .next()
885 .ok_or_else(|| {
886 TransportError::InvalidAddress(format!(
887 "DNS resolution returned no addresses for {}",
888 addr.as_str().unwrap_or("<non-utf8>")
889 ))
890 })
891}
892
893pub(crate) async fn resolve_socket_addrs(
900 addr: &TransportAddr,
901) -> Result<Vec<SocketAddr>, TransportError> {
902 let s = addr
903 .as_str()
904 .ok_or_else(|| TransportError::InvalidAddress("not valid UTF-8".into()))?;
905
906 if let Ok(sock_addr) = s.parse::<SocketAddr>() {
908 return Ok(vec![sock_addr]);
909 }
910
911 let addrs = tokio::net::lookup_host(s)
913 .await
914 .map_err(|e| {
915 TransportError::InvalidAddress(format!("DNS resolution failed for {}: {}", s, e))
916 })?
917 .collect::<Vec<_>>();
918 if addrs.is_empty() {
919 return Err(TransportError::InvalidAddress(format!(
920 "DNS resolution returned no addresses for {}",
921 s
922 )));
923 }
924 Ok(addrs)
925}