Skip to main content

fips_core/config/
peer.rs

1//! Peer configuration types.
2//!
3//! Known peer definitions with transport addresses and connection policies.
4
5use serde::{Deserialize, Serialize};
6
7/// Connection policy for a peer.
8///
9/// Determines when and how to establish a connection to a peer.
10#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]
11#[serde(rename_all = "snake_case")]
12pub enum ConnectPolicy {
13    /// Connect to this peer automatically on node startup.
14    /// This is the only policy supported in the initial implementation.
15    #[default]
16    AutoConnect,
17
18    /// Connect only when traffic needs to be routed through this peer (future).
19    OnDemand,
20
21    /// Wait for explicit API call to connect (future).
22    Manual,
23}
24
25/// A transport-specific address for reaching a peer.
26///
27/// Each peer can have multiple addresses across different transports,
28/// allowing fallback if one transport is unavailable.
29#[derive(Debug, Clone, Serialize, Deserialize)]
30#[serde(deny_unknown_fields)]
31pub struct PeerAddress {
32    /// Transport type (e.g., "udp", "tor", "ethernet").
33    pub transport: String,
34
35    /// Transport-specific address string.
36    ///
37    /// Format depends on transport type:
38    /// - UDP/TCP: "host:port" — IP address or DNS hostname
39    ///   (e.g., "192.168.1.1:2121" or "peer1.example.com:2121")
40    /// - Ethernet: "interface/mac" (e.g., "eth0/aa:bb:cc:dd:ee:ff")
41    pub addr: String,
42
43    /// Priority for address selection (lower = preferred).
44    /// When multiple addresses are available, lower priority addresses
45    /// are tried first.
46    #[serde(default = "default_priority")]
47    pub priority: u8,
48
49    /// Wall-clock observation timestamp (Unix ms) for ranking by recency
50    /// within the same priority.
51    ///
52    /// `None` means "no freshness signal" — typically an operator-edited
53    /// static config. The dialer primarily honors explicit address priority
54    /// and only uses this field to order otherwise-equal candidates. Skipped
55    /// from serde so that round-tripping a config file doesn't produce noisy
56    /// empty fields.
57    ///
58    /// Excluded from `PartialEq`: refreshing the timestamp on a peer that's
59    /// otherwise unchanged should not flag it as "updated" in
60    /// [`crate::endpoint::FipsEndpoint::update_peers`]'s diff.
61    #[serde(default, skip_serializing_if = "Option::is_none", skip_deserializing)]
62    pub seen_at_ms: Option<u64>,
63}
64
65impl PartialEq for PeerAddress {
66    fn eq(&self, other: &Self) -> bool {
67        self.transport == other.transport
68            && self.addr == other.addr
69            && self.priority == other.priority
70    }
71}
72
73impl Eq for PeerAddress {}
74
75fn default_priority() -> u8 {
76    100
77}
78
79fn default_auto_reconnect() -> bool {
80    true
81}
82
83fn default_discovery_fallback_transit() -> bool {
84    true
85}
86
87impl PeerAddress {
88    /// Create a new peer address.
89    pub fn new(transport: impl Into<String>, addr: impl Into<String>) -> Self {
90        Self {
91            transport: transport.into(),
92            addr: addr.into(),
93            priority: default_priority(),
94            seen_at_ms: None,
95        }
96    }
97
98    /// Create a new peer address with priority.
99    pub fn with_priority(
100        transport: impl Into<String>,
101        addr: impl Into<String>,
102        priority: u8,
103    ) -> Self {
104        Self {
105            transport: transport.into(),
106            addr: addr.into(),
107            priority,
108            seen_at_ms: None,
109        }
110    }
111
112    /// Tag this address with a freshness timestamp. Used by the dialer to
113    /// rank candidates from multiple sources (overlay advert, recent-peers
114    /// cache, operator hints) by recency without caring where they came
115    /// from. See [`crate::config::PeerAddress::seen_at_ms`].
116    pub fn with_seen_at_ms(mut self, seen_at_ms: u64) -> Self {
117        self.seen_at_ms = Some(seen_at_ms);
118        self
119    }
120}
121
122/// Configuration for a known peer.
123///
124/// Peers are identified by their Nostr public key (npub) and can have
125/// multiple transport addresses for reaching them.
126#[derive(Debug, Clone, Serialize, Deserialize)]
127#[serde(deny_unknown_fields)]
128pub struct PeerConfig {
129    /// The peer's Nostr public key in npub (bech32) or hex format.
130    pub npub: String,
131
132    /// Human-readable alias for the peer (optional).
133    #[serde(default, skip_serializing_if = "Option::is_none")]
134    pub alias: Option<String>,
135
136    /// Transport addresses for reaching this peer.
137    ///
138    /// At least one address is required unless Nostr discovery is enabled,
139    /// in which case the address list may be empty and endpoints are
140    /// resolved from the peer's Nostr advert at dial time.
141    #[serde(default)]
142    pub addresses: Vec<PeerAddress>,
143
144    /// Connection policy for this peer.
145    #[serde(default)]
146    pub connect_policy: ConnectPolicy,
147
148    /// Whether to automatically reconnect after link-dead removal.
149    /// When true (default), the node will retry connecting with exponential
150    /// backoff after MMP removes this peer due to liveness timeout.
151    #[serde(default = "default_auto_reconnect")]
152    pub auto_reconnect: bool,
153
154    /// Whether this peer may be used as an extra reply-learned lookup hop.
155    ///
156    /// Direct lookups to this peer are still allowed when false. This only
157    /// controls opportunistic fallback fanout through the peer for other
158    /// destinations.
159    #[serde(default = "default_discovery_fallback_transit")]
160    pub discovery_fallback_transit: bool,
161}
162
163impl Default for PeerConfig {
164    fn default() -> Self {
165        Self {
166            npub: String::new(),
167            alias: None,
168            addresses: Vec::new(),
169            connect_policy: ConnectPolicy::default(),
170            auto_reconnect: default_auto_reconnect(),
171            discovery_fallback_transit: default_discovery_fallback_transit(),
172        }
173    }
174}
175
176impl PeerConfig {
177    /// Create a new peer config with a single address.
178    pub fn new(
179        npub: impl Into<String>,
180        transport: impl Into<String>,
181        addr: impl Into<String>,
182    ) -> Self {
183        Self {
184            npub: npub.into(),
185            alias: None,
186            addresses: vec![PeerAddress::new(transport, addr)],
187            connect_policy: ConnectPolicy::default(),
188            auto_reconnect: default_auto_reconnect(),
189            discovery_fallback_transit: default_discovery_fallback_transit(),
190        }
191    }
192
193    /// Set an alias for the peer.
194    pub fn with_alias(mut self, alias: impl Into<String>) -> Self {
195        self.alias = Some(alias.into());
196        self
197    }
198
199    /// Add an additional address for the peer.
200    pub fn with_address(mut self, addr: PeerAddress) -> Self {
201        self.addresses.push(addr);
202        self
203    }
204
205    /// Get addresses sorted by priority (lowest first).
206    pub fn addresses_by_priority(&self) -> Vec<&PeerAddress> {
207        let mut addrs: Vec<_> = self.addresses.iter().collect();
208        addrs.sort_by_key(|a| a.priority);
209        addrs
210    }
211
212    /// Check if this peer should auto-connect on startup.
213    pub fn is_auto_connect(&self) -> bool {
214        matches!(self.connect_policy, ConnectPolicy::AutoConnect)
215    }
216}