Skip to main content

rings_node/processor/
config.rs

1use std::any::Any;
2use std::collections::BTreeMap;
3use std::fmt;
4use std::sync::OnceLock;
5use std::sync::PoisonError;
6use std::sync::RwLock;
7
8use rings_core::dht::default_storage_virtual_positions_per_owner;
9use rings_core::dht::VirtualNodeConfig;
10use rings_core::dht::DEFAULT_STORAGE_VIRTUAL_POSITIONS_PER_OWNER;
11use rings_core::dht::MAX_STORAGE_VIRTUAL_POSITIONS_PER_OWNER;
12use rings_core::ecc::keys::SigningSecretKey;
13use rings_core::utils::SharedClock;
14use rings_core::utils::SystemClock;
15use rings_runtime::MaybeSendSync;
16use rings_transport::core::transport::SharedTransport;
17pub use rings_transport::network_config::TransportNetworkConfig;
18pub use rings_transport::network_config::UdpPortRange;
19pub use rings_transport::network_config::UdpPortRangeError;
20use rings_turn::TurnCredentialSigner;
21
22use super::*;
23use crate::remote_endpoint::RemoteRpcProxy;
24
25/// Infallible phase-2 commit closure returned by
26/// [`NodeNetworkParameters::prepare_session_key_rotation`].
27///
28/// Executed synchronously after all phase-1 validations and durable key persistence succeed, so
29/// committing the prepared session credentials in memory cannot fail or require rollback.
30pub type SessionRotationCommit = Box<dyn FnOnce()>;
31
32/// Factory closure converting a deserialized `params` JSON value from a [`NetworkConfigDescriptor`]
33/// into a validated [`NodeNetworkParameters`] instance.
34pub type NetworkParametersFactory =
35    Arc<dyn Fn(&serde_json::Value) -> Result<Arc<dyn NodeNetworkParameters>> + Send + Sync>;
36
37fn default_empty_network_params() -> serde_json::Value {
38    serde_json::Value::Object(serde_json::Map::new())
39}
40
41/// Serde-extensible tagged network configuration descriptor (#1291).
42///
43/// Allows native `config.yaml`, [`ProcessorConfigSerialized`], FFI, and browser WASM serialized
44/// configurations to instantiate any registered [`NodeNetworkParameters`] backend (`"webrtc"`,
45/// `"dummy"`, or embedder-registered custom media such as `"quic"`, `"ble"`, or `"packet-radio"`)
46/// without modifying `rings-node`'s configuration structs.
47#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
48#[serde(deny_unknown_fields)]
49pub struct NetworkConfigDescriptor {
50    /// Registered transport backend kind identifier (for example `"webrtc"` or `"quic"`).
51    pub kind: String,
52    /// Backend-specific configuration object decoded by the registered factory.
53    #[serde(default = "default_empty_network_params")]
54    pub params: serde_json::Value,
55}
56
57/// Explicit TURN credential signing mode for WebRTC network parameters (#1291).
58#[derive(Clone, Debug)]
59pub enum TurnCredentialMode {
60    /// Default session-scoped mode: signs `?pubkey=` TURN URLs with the active [`DelegateeKey`]
61    /// and rotates TURN credentials in lockstep whenever `renew_delegatee_key` commits.
62    Delegatee,
63    /// Static account-scoped mode: signs `?pubkey=` TURN URLs directly with a non-expiring
64    /// [`SigningSecretKey`] (`Did` / `Account`) at startup and leaves credentials unchanged across
65    /// session-key rotations.
66    ///
67    /// Note: `Account`-mode [`WebrtcNetworkParameters`] intentionally return `None` from
68    /// [`NodeNetworkParameters::to_network_descriptor`] so long-lived account secret keys are never
69    /// serialized into [`ProcessorConfigSerialized`] documents.
70    Account(Arc<SigningSecretKey>),
71}
72
73/// Validate that every `turn://`, `turns://`, RFC 7065 `turn:`, or `turns:` entry carrying a
74/// `pubkey` query parameter encodes a valid secp256k1 server public key, rather than silently
75/// leaving a malformed `?pubkey=` template unsigned.
76fn validate_turn_pubkey_templates(spec: &str) -> Result<()> {
77    let trimmed = spec.trim();
78    if trimmed.is_empty() {
79        return Ok(());
80    }
81    for entry in trimmed.split(';') {
82        let entry = entry.trim();
83        if rings_turn::has_turn_pubkey_query_param(entry)
84            && rings_turn::extract_turn_server_pubkey(entry).is_none()
85        {
86            return Err(Error::InvalidConfig(format!(
87                "invalid TURN server pubkey in '{entry}'"
88            )));
89        }
90    }
91    Ok(())
92}
93
94/// Derive session-scoped ICE/TURN credentials from `spec` using `delegatee_key`, failing closed
95/// if any `?pubkey=` template is malformed or if credential signing fails.
96fn derive_session_ice_servers(spec: &str, delegatee_key: &DelegateeKey) -> Result<String> {
97    validate_turn_pubkey_templates(spec)?;
98    delegatee_key
99        .sign_ice_servers(spec)
100        .map_err(Error::CoreError)
101}
102
103/// Derive static account-scoped ICE/TURN credentials from `spec` using `account_key`, failing
104/// closed if any `?pubkey=` template is malformed or if credential signing fails.
105fn derive_account_ice_servers(spec: &str, account_key: &SigningSecretKey) -> Result<String> {
106    validate_turn_pubkey_templates(spec)?;
107    account_key.sign_ice_servers(spec).map_err(Error::CoreError)
108}
109
110fn instantiate_builtin_transport(
111    config: &TransportNetworkConfig,
112    signed_credentials: &str,
113) -> Result<SharedTransport> {
114    #[cfg(all(feature = "dummy", not(target_family = "wasm")))]
115    {
116        config
117            .try_build_dummy_transport(Some(signed_credentials))
118            .map_err(|err| Error::InvalidConfig(err.to_string()))
119    }
120    #[cfg(not(all(feature = "dummy", not(target_family = "wasm"))))]
121    {
122        config
123            .try_build_shared_transport(Some(signed_credentials))
124            .map_err(|err| Error::InvalidConfig(err.to_string()))
125    }
126}
127
128/// Trait defining the network parameters that customize and instantiate a node's transport (#1291).
129///
130/// From first principles, every interaction between a node (`Processor`, `ProcessorBuilder`,
131/// `ProcessorConfig`) and its network parameters reduces to three orthogonal operations plus
132/// optional config-descriptor projection:
133/// 1. **Transport instantiation** ([`build_transport`](Self::build_transport)): validates the
134///    medium's parameters (failing closed on malformed configuration) and constructs a
135///    [`SharedTransport`] bound to the node's initial [`DelegateeKey`].
136/// 2. **Advertised locator hint** ([`endpoint_hint`](Self::endpoint_hint)): returns an optional
137///    external locator published in the node's online presence descriptor (`None` by default for
138///    proximity ad-hoc media such as packet radio, Bluetooth ad-hoc, ultrasonic ad-hoc, or
139///    unaddressed client nodes).
140/// 3. **Two-phase session-key rotation**
141///    ([`prepare_session_key_rotation`](Self::prepare_session_key_rotation)): phase 1 validates and
142///    prepares any session-bound transport credentials **without mutating** `transport`, returning
143///    an infallible [`SessionRotationCommit`] closure that phase 2 executes only after all pure
144///    validations and durable disk persistence succeed.
145pub trait NodeNetworkParameters: Any + fmt::Debug + MaybeSendSync {
146    /// Validate these network parameters and instantiate a [`SharedTransport`] bound to
147    /// `delegatee_key`.
148    fn build_transport(&self, delegatee_key: &DelegateeKey) -> Result<SharedTransport>;
149
150    /// Return the external endpoint or locator hint advertised in the node's online presence
151    /// descriptor, if any.
152    ///
153    /// Defaults to `None` (appropriate for proximity ad-hoc media or nodes without a public locator).
154    fn endpoint_hint(&self) -> Option<&str> {
155        None
156    }
157
158    /// Phase 1 of two-phase session-key rotation: derive and validate transport state for
159    /// `next_key` **without mutating** `transport`, returning an infallible phase-2 commit closure.
160    ///
161    /// # Concurrency & Lock-Ordering Contract
162    ///
163    /// Both `prepare_session_key_rotation` and the returned [`SessionRotationCommit`] closure run
164    /// synchronously while `Processor`'s internal `SessionKeyRing` write lock is held:
165    /// - Implementations **must** remain synchronous and non-blocking (never awaiting network I/O).
166    /// - Implementations **must not** re-enter `Processor` methods that read or write the session
167    ///   key ring (such as `Processor::signing_horizon` or `Processor::renew_delegatee_key`).
168    /// - Phase 1 (`prepare_session_key_rotation`) **must not** mutate `transport` before returning,
169    ///   and Phase 2 (`SessionRotationCommit`) **must** be infallible.
170    ///
171    /// Defaults to an empty no-op commit closure for media whose link layer does not carry
172    /// session-signed credentials.
173    fn prepare_session_key_rotation(
174        &self,
175        _transport: &SharedTransport,
176        _next_key: &DelegateeKey,
177    ) -> Result<SessionRotationCommit> {
178        Ok(Box::new(|| {}))
179    }
180
181    /// Project these network parameters into a tagged [`NetworkConfigDescriptor`] for lossless
182    /// serialization into [`ProcessorConfigSerialized`], returning `None` if this parameter type is
183    /// purely programmatic.
184    fn to_network_descriptor(&self) -> Option<NetworkConfigDescriptor> {
185        None
186    }
187}
188
189/// Implementation of [`NodeNetworkParameters`] for the built-in [`TransportNetworkConfig`].
190impl NodeNetworkParameters for TransportNetworkConfig {
191    /// Strictly derive session-signed traversal credentials from `delegatee_key` and construct the
192    /// platform's [`SharedTransport`], failing closed if any ICE/TURN URL or server public key is
193    /// malformed.
194    fn build_transport(&self, delegatee_key: &DelegateeKey) -> Result<SharedTransport> {
195        let signed = derive_session_ice_servers(self.traversal_servers(), delegatee_key)?;
196        instantiate_builtin_transport(self, &signed)
197    }
198
199    /// Return the configured external endpoint hint, if any.
200    fn endpoint_hint(&self) -> Option<&str> {
201        TransportNetworkConfig::endpoint_hint(self)
202    }
203
204    /// Re-sign the configured traversal server template with `next_key`, strictly parse the
205    /// resulting ICE server list in phase 1 without mutating `transport`, and return an infallible
206    /// phase-2 closure that atomically commits `(raw_credentials, parsed_ice_servers)`.
207    fn prepare_session_key_rotation(
208        &self,
209        transport: &SharedTransport,
210        next_key: &DelegateeKey,
211    ) -> Result<SessionRotationCommit> {
212        let signed = derive_session_ice_servers(self.traversal_servers(), next_key)?;
213        TransportNetworkConfig::prepare_ice_server_rotation(transport, signed)
214            .map_err(|err| Error::InvalidConfig(err.to_string()))
215    }
216}
217
218/// Built-in WebRTC network parameters pairing [`TransportNetworkConfig`] with an explicit
219/// [`TurnCredentialMode`] (`Delegatee` by default, or `Account` for non-expiring account-signed
220/// TURN credentials).
221#[derive(Clone, Debug)]
222pub struct WebrtcNetworkParameters {
223    config: TransportNetworkConfig,
224    credential_mode: TurnCredentialMode,
225}
226
227impl WebrtcNetworkParameters {
228    /// Create [`WebrtcNetworkParameters`] using default session-scoped [`TurnCredentialMode::Delegatee`].
229    pub const fn new(config: TransportNetworkConfig) -> Self {
230        Self {
231            config,
232            credential_mode: TurnCredentialMode::Delegatee,
233        }
234    }
235
236    /// Override the [`TurnCredentialMode`] used to sign `?pubkey=` TURN server URLs.
237    pub fn with_credential_mode(mut self, credential_mode: TurnCredentialMode) -> Self {
238        self.credential_mode = credential_mode;
239        self
240    }
241
242    /// Borrow the underlying [`TransportNetworkConfig`].
243    pub const fn transport_config(&self) -> &TransportNetworkConfig {
244        &self.config
245    }
246
247    /// Return the configured [`TurnCredentialMode`].
248    pub const fn credential_mode(&self) -> &TurnCredentialMode {
249        &self.credential_mode
250    }
251}
252
253impl NodeNetworkParameters for WebrtcNetworkParameters {
254    fn build_transport(&self, delegatee_key: &DelegateeKey) -> Result<SharedTransport> {
255        let signed = match &self.credential_mode {
256            TurnCredentialMode::Delegatee => {
257                derive_session_ice_servers(self.config.traversal_servers(), delegatee_key)?
258            }
259            TurnCredentialMode::Account(account_key) => {
260                derive_account_ice_servers(self.config.traversal_servers(), account_key)?
261            }
262        };
263        self.config
264            .try_build_shared_transport(Some(&signed))
265            .map_err(|err| Error::InvalidConfig(err.to_string()))
266    }
267
268    fn endpoint_hint(&self) -> Option<&str> {
269        self.config.endpoint_hint()
270    }
271
272    fn prepare_session_key_rotation(
273        &self,
274        transport: &SharedTransport,
275        next_key: &DelegateeKey,
276    ) -> Result<SessionRotationCommit> {
277        match &self.credential_mode {
278            TurnCredentialMode::Delegatee => self
279                .config
280                .prepare_session_key_rotation(transport, next_key),
281            TurnCredentialMode::Account(_) => Ok(Box::new(|| {})),
282        }
283    }
284
285    fn to_network_descriptor(&self) -> Option<NetworkConfigDescriptor> {
286        match &self.credential_mode {
287            TurnCredentialMode::Delegatee => Some(webrtc_descriptor_from_config(&self.config)),
288            TurnCredentialMode::Account(_) => None,
289        }
290    }
291}
292
293#[derive(Clone, Debug, Default, Serialize, Deserialize)]
294#[serde(deny_unknown_fields)]
295struct WebrtcDescriptorParams {
296    #[serde(default)]
297    ice_servers: String,
298    #[serde(default, skip_serializing_if = "Option::is_none")]
299    external_address: Option<String>,
300    #[serde(
301        default,
302        alias = "webrtc_udp_port_min",
303        skip_serializing_if = "Option::is_none"
304    )]
305    udp_port_min: Option<u16>,
306    #[serde(
307        default,
308        alias = "webrtc_udp_port_max",
309        skip_serializing_if = "Option::is_none"
310    )]
311    udp_port_max: Option<u16>,
312}
313
314fn webrtc_descriptor_from_config(config: &TransportNetworkConfig) -> NetworkConfigDescriptor {
315    let range = config.udp_port_range();
316    let params = serde_json::to_value(WebrtcDescriptorParams {
317        ice_servers: config.traversal_servers().to_owned(),
318        external_address: config.endpoint_hint().map(str::to_owned),
319        udp_port_min: range.map(UdpPortRange::min),
320        udp_port_max: range.map(UdpPortRange::max),
321    })
322    .unwrap_or_else(|_| default_empty_network_params());
323    NetworkConfigDescriptor {
324        kind: "webrtc".to_string(),
325        params,
326    }
327}
328
329#[cfg(all(feature = "dummy", not(target_family = "wasm")))]
330#[derive(Clone, Debug)]
331struct DummyNetworkParameters {
332    config: TransportNetworkConfig,
333}
334
335#[cfg(all(feature = "dummy", not(target_family = "wasm")))]
336impl NodeNetworkParameters for DummyNetworkParameters {
337    fn build_transport(&self, delegatee_key: &DelegateeKey) -> Result<SharedTransport> {
338        let signed = derive_session_ice_servers(self.config.traversal_servers(), delegatee_key)?;
339        self.config
340            .try_build_dummy_transport(Some(&signed))
341            .map_err(|err| Error::InvalidConfig(err.to_string()))
342    }
343
344    fn endpoint_hint(&self) -> Option<&str> {
345        self.config.endpoint_hint()
346    }
347
348    fn prepare_session_key_rotation(
349        &self,
350        transport: &SharedTransport,
351        next_key: &DelegateeKey,
352    ) -> Result<SessionRotationCommit> {
353        let signed = derive_session_ice_servers(self.config.traversal_servers(), next_key)?;
354        TransportNetworkConfig::prepare_ice_server_rotation(transport, signed)
355            .map_err(|err| Error::InvalidConfig(err.to_string()))
356    }
357
358    fn to_network_descriptor(&self) -> Option<NetworkConfigDescriptor> {
359        let mut desc = webrtc_descriptor_from_config(&self.config);
360        desc.kind = "dummy".to_string();
361        Some(desc)
362    }
363}
364
365fn network_transport_registry() -> &'static RwLock<BTreeMap<String, NetworkParametersFactory>> {
366    static REGISTRY: OnceLock<RwLock<BTreeMap<String, NetworkParametersFactory>>> = OnceLock::new();
367    REGISTRY.get_or_init(|| {
368        let mut map: BTreeMap<String, NetworkParametersFactory> = BTreeMap::new();
369        map.insert(
370            "webrtc".to_string(),
371            Arc::new(|params| {
372                let decoded: WebrtcDescriptorParams = serde_json::from_value(params.clone())
373                    .map_err(|err| {
374                        Error::InvalidConfig(format!("invalid 'webrtc' network params: {err}"))
375                    })?;
376                let range = parse_udp_port_range(decoded.udp_port_min, decoded.udp_port_max)?;
377                Ok(Arc::new(WebrtcNetworkParameters::new(
378                    TransportNetworkConfig::new(
379                        decoded.ice_servers,
380                        decoded.external_address,
381                        range,
382                    ),
383                )))
384            }),
385        );
386        #[cfg(all(feature = "dummy", not(target_family = "wasm")))]
387        map.insert(
388            "dummy".to_string(),
389            Arc::new(|params| {
390                let decoded: WebrtcDescriptorParams = serde_json::from_value(params.clone())
391                    .map_err(|err| {
392                        Error::InvalidConfig(format!("invalid 'dummy' network params: {err}"))
393                    })?;
394                let range = parse_udp_port_range(decoded.udp_port_min, decoded.udp_port_max)?;
395                Ok(Arc::new(DummyNetworkParameters {
396                    config: TransportNetworkConfig::new(
397                        decoded.ice_servers,
398                        decoded.external_address,
399                        range,
400                    ),
401                }))
402            }),
403        );
404        RwLock::new(map)
405    })
406}
407
408/// Register a custom [`NodeNetworkParameters`] factory under `kind` so native `config.yaml`,
409/// [`ProcessorConfigSerialized`], FFI, and browser WASM serialized configurations can instantiate
410/// `network: { kind: "<kind>", params: { ... } }` (#1291).
411///
412/// Built-in transport kinds (`"webrtc"` and `"dummy"`) are reserved and cannot be overwritten,
413/// and duplicate registrations for an already-registered custom `kind` fail with
414/// [`Error::InvalidConfig`] rather than silently hijacking an existing factory.
415pub fn register_network_transport_factory<F>(kind: impl Into<String>, factory: F) -> Result<()>
416where F: Fn(&serde_json::Value) -> Result<Arc<dyn NodeNetworkParameters>> + Send + Sync + 'static {
417    let kind = kind.into();
418    let normalized = kind.trim();
419    if normalized.is_empty() {
420        return Err(Error::InvalidConfig(
421            "network transport kind must not be empty".to_string(),
422        ));
423    }
424    if matches!(normalized, "webrtc" | "dummy") {
425        return Err(Error::InvalidConfig(format!(
426            "cannot overwrite reserved built-in network transport kind '{normalized}'"
427        )));
428    }
429    let mut guard = network_transport_registry()
430        .write()
431        .unwrap_or_else(PoisonError::into_inner);
432    match guard.entry(normalized.to_owned()) {
433        std::collections::btree_map::Entry::Occupied(_) => Err(Error::InvalidConfig(format!(
434            "network transport kind '{normalized}' is already registered"
435        ))),
436        std::collections::btree_map::Entry::Vacant(vacant) => {
437            vacant.insert(Arc::new(factory));
438            Ok(())
439        }
440    }
441}
442
443/// Resolve a deserialized [`NetworkConfigDescriptor`] into a concrete [`NodeNetworkParameters`]
444/// instance via the process-wide transport registry.
445pub fn resolve_network_config_descriptor(
446    descriptor: &NetworkConfigDescriptor,
447) -> Result<Arc<dyn NodeNetworkParameters>> {
448    let kind = descriptor.kind.trim();
449    let factory = network_transport_registry()
450        .read()
451        .unwrap_or_else(PoisonError::into_inner)
452        .get(kind)
453        .cloned()
454        .ok_or_else(|| Error::InvalidConfig(format!("unknown network transport kind '{kind}'")))?;
455    factory(&descriptor.params)
456}
457
458/// ProcessorConfig is usually serialized as json or yaml.
459/// There is a `from_config` method in [ProcessorBuilder] used to initialize the Builder with a serialized ProcessorConfig.
460#[derive(Clone, Debug)]
461#[wasm_export]
462pub struct ProcessorConfig {
463    /// The network_id is used to distinguish different networks.
464    /// Use 1 for main network.
465    pub(in crate::processor) network_id: u32,
466    /// Abstract network parameters customizing the transport layer (#1291).
467    pub(in crate::processor) network_parameters: Arc<dyn NodeNetworkParameters>,
468    /// [DelegateeKey].
469    pub(in crate::processor) delegatee_key: DelegateeKey,
470    /// Stabilization interval.
471    pub(in crate::processor) stabilize_interval: Duration,
472    /// Online-node registry heartbeat interval.
473    pub(in crate::processor) online_node_heartbeat_interval: Duration,
474    /// Online-node registry descriptor TTL.
475    pub(in crate::processor) online_node_ttl: Duration,
476    /// Runtime family advertised in the online-node registry.
477    pub(in crate::processor) online_node_type: OnlineNodeType,
478    /// Whether listen() advertises this node's presence.
479    pub(in crate::processor) advertise_presence: bool,
480    /// Storage-only virtual positions derived per physical peer.
481    pub(in crate::processor) dht_virtual_nodes: u16,
482    /// Runtime-local final-destination quotas keyed by verified origin and logical lane.
483    pub(in crate::processor) origin_quota: OriginQuotaConfig,
484    /// Onion symbols this process registers (#834 D2).
485    pub(in crate::processor) onion_role: OnionRole<OnionExitOffer>,
486    /// Onion-exit registry heartbeat interval.
487    pub(in crate::processor) onion_exit_heartbeat_interval: Duration,
488    /// Onion-exit registry descriptor TTL.
489    pub(in crate::processor) onion_exit_ttl: Duration,
490    /// Optional HTTP(S) proxy for remote JSON-RPC endpoints on native targets.
491    pub(crate) remote_rpc_proxy: Option<RemoteRpcProxy>,
492    /// Epoch clock capability injected into this node's runtime subsystems.
493    pub(in crate::processor) clock: SharedClock,
494}
495
496#[wasm_export]
497impl ProcessorConfig {
498    /// Creates a new `ProcessorConfig` instance without an external endpoint hint.
499    pub fn new(
500        network_id: u32,
501        traversal_servers: String,
502        delegatee_key: DelegateeKey,
503        stabilize_interval: u64,
504    ) -> Self {
505        Self {
506            network_id,
507            network_parameters: Arc::new(TransportNetworkConfig::new(
508                traversal_servers,
509                None,
510                None,
511            )),
512            delegatee_key,
513            stabilize_interval: Duration::from_secs(stabilize_interval),
514            online_node_heartbeat_interval: Duration::from_secs(
515                default_online_node_heartbeat_interval_secs(),
516            ),
517            online_node_ttl: Duration::from_secs(default_online_node_ttl_secs()),
518            online_node_type: default_online_node_type(),
519            advertise_presence: default_advertise_presence(),
520            dht_virtual_nodes: DEFAULT_STORAGE_VIRTUAL_POSITIONS_PER_OWNER,
521            origin_quota: OriginQuotaConfig::default(),
522            onion_role: OnionRole::Client,
523            onion_exit_heartbeat_interval: Duration::from_secs(
524                default_onion_exit_heartbeat_interval_secs(),
525            ),
526            onion_exit_ttl: Duration::from_secs(default_onion_exit_ttl_secs()),
527            remote_rpc_proxy: None,
528            clock: Arc::new(SystemClock),
529        }
530    }
531
532    /// Return associated [DelegateeKey].
533    pub fn delegatee_key(&self) -> DelegateeKey {
534        self.delegatee_key.clone()
535    }
536
537    /// Return the overlay this node joins.
538    pub fn network_id(&self) -> u32 {
539        self.network_id
540    }
541
542    /// Sets storage-only virtual positions derived per physical peer.
543    ///
544    /// Serialized configs reject values above
545    /// [`MAX_STORAGE_VIRTUAL_POSITIONS_PER_OWNER`]. This setter is infallible
546    /// for direct programmatic use; the core swarm builder normalizes the value
547    /// once before storage ownership and protocol advertisement are created.
548    pub fn dht_virtual_nodes(mut self, positions_per_peer: u16) -> Self {
549        self.dht_virtual_nodes = positions_per_peer;
550        self
551    }
552
553    /// Enable or disable onion relay advertisement on this node.
554    ///
555    /// When enabling relay while currently `Client`, upgrades the role to `Relay`; when disabling
556    /// relay, resets the role to `Client`.
557    pub fn advertise_onion_relay(mut self, enabled: bool) -> Self {
558        self.onion_role = match (enabled, self.onion_role) {
559            (true, OnionRole::Client) => OnionRole::Relay,
560            (true, role) => role,
561            (false, _) => OnionRole::Client,
562        };
563        self
564    }
565}
566
567impl ProcessorConfig {
568    /// Override the runtime family advertised in the online-node registry.
569    pub fn online_node_type(mut self, node_type: OnlineNodeType) -> Self {
570        self.online_node_type = node_type;
571        self
572    }
573
574    /// Return the configured [`NodeNetworkParameters`].
575    pub fn network_parameters(&self) -> &Arc<dyn NodeNetworkParameters> {
576        &self.network_parameters
577    }
578
579    /// Inject custom [`NodeNetworkParameters`] to customize the transport layer (#1291).
580    pub fn with_network_parameters<P>(mut self, params: P) -> Self
581    where P: NodeNetworkParameters + 'static {
582        self.network_parameters = Arc::new(params);
583        self
584    }
585
586    /// Returns the validated local UDP port range when configured on a built-in UDP-capable
587    /// transport (`TransportNetworkConfig` or `WebrtcNetworkParameters`), or `None` when no port
588    /// range is set or when custom [`NodeNetworkParameters`] are injected (custom media manage
589    /// their own local socket or radio channel allocation internally).
590    pub fn udp_port_range(&self) -> Option<UdpPortRange> {
591        let any = self.network_parameters.as_ref() as &dyn Any;
592        if let Some(cfg) = any.downcast_ref::<TransportNetworkConfig>() {
593            return cfg.udp_port_range();
594        }
595        if let Some(webrtc) = any.downcast_ref::<WebrtcNetworkParameters>() {
596            return webrtc.transport_config().udp_port_range();
597        }
598        None
599    }
600
601    /// The longer heartbeat of the two registries this node publishes, online nodes and onion
602    /// exits: the pause after which each of its registrations is published again.
603    pub fn registry_heartbeat_interval(&self) -> Duration {
604        self.online_node_heartbeat_interval
605            .max(self.onion_exit_heartbeat_interval)
606    }
607
608    /// Sets the onion symbols this process registers (#834 D2).
609    pub fn onion_role(mut self, role: OnionRole<OnionExitOffer>) -> Self {
610        self.onion_role = role;
611        self
612    }
613
614    /// Validate this config's onion role ([`validate_onion_role_config`]) before any runtime
615    /// effect, as the builder does at build time.
616    #[cfg(all(feature = "browser", target_family = "wasm"))]
617    pub(crate) fn validate_onion_role(&self) -> Result<()> {
618        validate_onion_role_config(self.advertise_presence, &self.onion_role)
619    }
620
621    /// Sets runtime-local final-destination quotas keyed by verified origin and logical lane.
622    pub fn origin_quota(mut self, config: OriginQuotaConfig) -> Self {
623        self.origin_quota = config;
624        self
625    }
626
627    /// Route native remote JSON-RPC requests (`nodeDid`, `answerOffer`, `acceptAnswer`) through
628    /// `proxy` instead of connecting directly.
629    pub fn remote_rpc_proxy(mut self, proxy: RemoteRpcProxy) -> Self {
630        self.remote_rpc_proxy = Some(proxy);
631        self
632    }
633
634    /// Return the [`SharedClock`] capability configured for this node.
635    pub fn clock(&self) -> &SharedClock {
636        &self.clock
637    }
638
639    /// Inject a custom [`SharedClock`] capability for deterministic node time.
640    pub fn with_clock(mut self, clock: SharedClock) -> Self {
641        self.clock = clock;
642        self
643    }
644}
645
646impl FromStr for ProcessorConfig {
647    type Err = Error;
648    /// Reveal config from serialized string (with YAML error source snippets disabled so secret
649    /// `delegatee_key` lines are never echoed in formatted error messages).
650    fn from_str(ser: &str) -> Result<Self> {
651        let mut options = serde_saphyr::Options::default();
652        options.with_snippet = false;
653        Ok(serde_saphyr::from_str_with_options::<ProcessorConfig>(
654            ser, options,
655        )?)
656    }
657}
658
659/// `ProcessorConfigSerialized` is a serialized version of `ProcessorConfig`.
660/// Instead of storing the `DelegateeKey` instance, it stores the dumped string representation of
661/// the delegatee key.
662#[derive(Serialize, Deserialize, Clone)]
663#[wasm_export]
664pub struct ProcessorConfigSerialized {
665    /// The network_id is used to distinguish different networks.
666    /// Use 1 for main network.
667    pub(crate) network_id: u32,
668    /// Traversal/relay server specification string (serialized under the `ice_servers` key for
669    /// config file compatibility; defaults to empty when `network` selects a non-ICE transport).
670    #[serde(default)]
671    pub(crate) ice_servers: String,
672    /// Optional external endpoint locator advertised by this node.
673    #[serde(default)]
674    pub(crate) external_address: Option<String>,
675    /// Inclusive lower local UDP port bound.
676    #[serde(default, alias = "webrtc_udp_port_min")]
677    pub(crate) udp_port_min: Option<u16>,
678    /// Inclusive upper local UDP port bound.
679    #[serde(default, alias = "webrtc_udp_port_max")]
680    pub(crate) udp_port_max: Option<u16>,
681    /// Optional serde-extensible tagged transport descriptor (`{ kind, params }`).
682    /// When present, overrides the legacy `ice_servers` / `external_address` / `udp_port_*`
683    /// WebRTC fields and resolves through [`resolve_network_config_descriptor`].
684    #[serde(default, skip_serializing_if = "Option::is_none")]
685    pub(crate) network: Option<NetworkConfigDescriptor>,
686    /// A string representing the dumped `DelegateeKey`.
687    pub(crate) delegatee_key: String,
688    /// An unsigned integer representing the stabilization interval in seconds.
689    pub(crate) stabilize_interval: u64,
690    /// Online-node registry heartbeat interval in seconds.
691    #[serde(default = "default_online_node_heartbeat_interval_secs")]
692    pub(crate) online_node_heartbeat_interval_secs: u64,
693    /// Online-node registry descriptor TTL in seconds.
694    #[serde(default = "default_online_node_ttl_secs")]
695    pub(crate) online_node_ttl_secs: u64,
696    /// Runtime family advertised in the online-node registry.
697    #[serde(default = "default_online_node_type")]
698    pub(crate) online_node_type: OnlineNodeType,
699    /// Whether listen() advertises this node's presence.
700    #[serde(default = "default_advertise_presence")]
701    pub(crate) advertise_presence: bool,
702    /// Storage-only virtual positions derived per physical peer.
703    #[serde(default = "default_storage_virtual_positions_per_owner")]
704    pub(crate) dht_virtual_nodes: u16,
705    /// Runtime-local final-destination quotas keyed by verified origin and logical lane.
706    #[serde(default)]
707    pub(crate) origin_quota: OriginQuotaConfig,
708    /// Whether listen() advertises onion relay capability.
709    #[serde(default = "default_advertise_onion_relay")]
710    pub(crate) advertise_onion_relay: bool,
711    /// Whether listen() publishes an onion-exit descriptor.
712    #[serde(default = "default_advertise_onion_exit")]
713    pub(crate) advertise_onion_exit: bool,
714    /// Onion-exit registry heartbeat interval in seconds.
715    #[serde(default = "default_onion_exit_heartbeat_interval_secs")]
716    pub(crate) onion_exit_heartbeat_interval_secs: u64,
717    /// Onion-exit registry descriptor TTL in seconds.
718    #[serde(default = "default_onion_exit_ttl_secs")]
719    pub(crate) onion_exit_ttl_secs: u64,
720    /// Exit services advertised by this node.
721    #[serde(default = "default_onion_exit_services")]
722    pub(crate) onion_exit_services: Vec<OnionServiceName>,
723    /// Exit policy advertised by this node.
724    #[serde(default = "default_onion_exit_policy")]
725    pub(crate) onion_exit_policy: OnionExitPolicy,
726    /// Optional intermediate `invoke` offer advertised by this node.
727    #[serde(default, skip_serializing_if = "Option::is_none")]
728    pub(crate) onion_invoke_offer: Option<crate::onion::OnionInvokeOffer>,
729    /// Optional HTTP(S) proxy URL for remote JSON-RPC endpoints on native targets.
730    #[serde(default, skip_serializing_if = "Option::is_none")]
731    pub(crate) remote_rpc_proxy_url: Option<String>,
732}
733
734pub(crate) fn parse_udp_port_range(
735    min: Option<u16>,
736    max: Option<u16>,
737) -> Result<Option<UdpPortRange>> {
738    match (min, max) {
739        (None, None) => Ok(None),
740        (Some(min), Some(max)) => UdpPortRange::new(min, max).map(Some).map_err(Error::from),
741        (min, max) => Err(Error::IncompleteUdpPortRange { min, max }),
742    }
743}
744
745pub(in crate::processor) fn validate_dht_virtual_nodes(positions_per_peer: u16) -> Result<()> {
746    if VirtualNodeConfig::positions_per_owner_within_limit(positions_per_peer) {
747        return Ok(());
748    }
749
750    Err(Error::InvalidConfig(format!(
751        "dht_virtual_nodes {positions_per_peer} exceeds maximum {MAX_STORAGE_VIRTUAL_POSITIONS_PER_OWNER}"
752    )))
753}
754
755/// Validate that the onion role can be published and served.
756///
757/// - `relay ∈ Σ_n ⇒ advertise_presence`, because the relay registration lives in the online-node
758///   descriptor.
759/// - Every offered exit service is one this node's runtime interprets
760///   ([`OnionExitOffer::uninterpretable_service`]), so no descriptor names a service the node
761///   cannot evaluate.
762///
763/// `Σ_n ≠ ∅ ⇒ relay ∈ Σ_n` needs no check: [`OnionRole`] has no rung that registers a symbol
764/// without `relay`.
765pub(in crate::processor) fn validate_onion_role_config(
766    advertise_presence: bool,
767    onion_role: &OnionRole<OnionExitOffer>,
768) -> Result<()> {
769    if let Some(service) = onion_role
770        .exit()
771        .and_then(OnionExitOffer::uninterpretable_service)
772    {
773        return Err(Error::UninterpretableOnionService {
774            service: service.clone(),
775        });
776    }
777    #[cfg(rings_browser)]
778    if let Some(offer) = onion_role.exit() {
779        offer.policy().validate_browser_targets()?;
780    }
781    if onion_role.registers_relay() && !advertise_presence {
782        return Err(Error::InvalidConfig(
783            "advertise_onion_relay requires advertise_presence because relay capability is published in online-node descriptors"
784                .to_string(),
785        ));
786    }
787    Ok(())
788}
789
790impl TryFrom<ProcessorConfig> for ProcessorConfigSerialized {
791    type Error = Error;
792    fn try_from(ins: ProcessorConfig) -> Result<Self> {
793        let (ice_servers, external_address, udp_port_min, udp_port_max, network) = if let Some(
794            transport_config,
795        ) =
796            (ins.network_parameters.as_ref() as &dyn Any).downcast_ref::<TransportNetworkConfig>()
797        {
798            let udp_port_range = transport_config.udp_port_range();
799            (
800                transport_config.traversal_servers().to_owned(),
801                ins.network_parameters.endpoint_hint().map(str::to_owned),
802                udp_port_range.map(UdpPortRange::min),
803                udp_port_range.map(UdpPortRange::max),
804                None,
805            )
806        } else if let Some(descriptor) = ins.network_parameters.to_network_descriptor() {
807            (String::new(), None, None, None, Some(descriptor))
808        } else {
809            return Err(Error::InvalidConfig(
810                "cannot losslessly serialize custom NodeNetworkParameters into ProcessorConfigSerialized \
811                 (implement `to_network_descriptor` and register via `register_network_transport_factory`)"
812                    .to_string(),
813            ));
814        };
815        Ok(Self {
816            network_id: ins.network_id,
817            ice_servers,
818            external_address,
819            udp_port_min,
820            udp_port_max,
821            network,
822            delegatee_key: ins.delegatee_key.dump()?,
823            stabilize_interval: ins.stabilize_interval.as_secs(),
824            online_node_heartbeat_interval_secs: ins.online_node_heartbeat_interval.as_secs(),
825            online_node_ttl_secs: ins.online_node_ttl.as_secs(),
826            online_node_type: ins.online_node_type,
827            advertise_presence: ins.advertise_presence,
828            dht_virtual_nodes: ins.dht_virtual_nodes,
829            origin_quota: ins.origin_quota,
830            advertise_onion_relay: ins.onion_role.registers_relay(),
831            advertise_onion_exit: ins.onion_role.exit().is_some(),
832            onion_exit_heartbeat_interval_secs: ins.onion_exit_heartbeat_interval.as_secs(),
833            onion_exit_ttl_secs: ins.onion_exit_ttl.as_secs(),
834            onion_exit_services: ins
835                .onion_role
836                .exit()
837                .map_or_else(default_onion_exit_services, |offer| {
838                    offer.services().iter().cloned().collect()
839                }),
840            onion_exit_policy: ins
841                .onion_role
842                .exit()
843                .map_or_else(default_onion_exit_policy, |offer| offer.policy().clone()),
844            onion_invoke_offer: ins.onion_role.invoke().cloned(),
845            remote_rpc_proxy_url: ins
846                .remote_rpc_proxy
847                .as_ref()
848                .map(|proxy| proxy.as_str().to_owned()),
849        })
850    }
851}
852
853impl TryFrom<ProcessorConfigSerialized> for ProcessorConfig {
854    type Error = Error;
855    fn try_from(ins: ProcessorConfigSerialized) -> Result<Self> {
856        let network_parameters: Arc<dyn NodeNetworkParameters> = match ins.network.as_ref() {
857            Some(descriptor) => {
858                if !ins.ice_servers.trim().is_empty()
859                    || ins.external_address.is_some()
860                    || ins.udp_port_min.is_some()
861                    || ins.udp_port_max.is_some()
862                {
863                    return Err(Error::InvalidConfig(
864                        "cannot specify both `network` and legacy flat WebRTC fields (`ice_servers`, `external_address`, `udp_port_min`, `udp_port_max`)"
865                            .to_string(),
866                    ));
867                }
868                resolve_network_config_descriptor(descriptor)?
869            }
870            None => {
871                let udp_port_range = parse_udp_port_range(ins.udp_port_min, ins.udp_port_max)?;
872                Arc::new(TransportNetworkConfig::new(
873                    ins.ice_servers,
874                    ins.external_address,
875                    udp_port_range,
876                ))
877            }
878        };
879        let remote_rpc_proxy = ins
880            .remote_rpc_proxy_url
881            .as_deref()
882            .map(RemoteRpcProxy::parse)
883            .transpose()?;
884        let online_node_heartbeat_interval =
885            Duration::from_secs(ins.online_node_heartbeat_interval_secs);
886        let online_node_ttl = Duration::from_secs(ins.online_node_ttl_secs);
887        let onion_exit_heartbeat_interval =
888            Duration::from_secs(ins.onion_exit_heartbeat_interval_secs);
889        let onion_exit_ttl = Duration::from_secs(ins.onion_exit_ttl_secs);
890        Ok(Self {
891            network_id: ins.network_id,
892            network_parameters,
893            delegatee_key: DelegateeKey::from_str(&ins.delegatee_key)?,
894            stabilize_interval: Duration::from_secs(ins.stabilize_interval),
895            online_node_heartbeat_interval,
896            online_node_ttl,
897            online_node_type: ins.online_node_type,
898            advertise_presence: ins.advertise_presence,
899            dht_virtual_nodes: ins.dht_virtual_nodes,
900            origin_quota: ins.origin_quota,
901            onion_role: {
902                let role = OnionRole::from_flags(
903                    ins.advertise_onion_relay,
904                    ins.advertise_onion_exit,
905                    ins.onion_exit_services,
906                    ins.onion_exit_policy,
907                )?;
908                match ins.onion_invoke_offer {
909                    Some(invoke) => {
910                        if !ins.advertise_onion_relay {
911                            return Err(Error::InvalidConfig(
912                                "onion_invoke_offer requires advertise_onion_relay".to_string(),
913                            ));
914                        }
915                        role.with_invoke(invoke)
916                    }
917                    None => role,
918                }
919            },
920            onion_exit_heartbeat_interval,
921            onion_exit_ttl,
922            remote_rpc_proxy,
923            clock: Arc::new(SystemClock),
924        })
925    }
926}
927
928impl Serialize for ProcessorConfig {
929    fn serialize<S: serde::Serializer>(
930        &self,
931        serializer: S,
932    ) -> core::result::Result<S::Ok, S::Error> {
933        let ins: ProcessorConfigSerialized = self
934            .clone()
935            .try_into()
936            .map_err(|e: Error| serde::ser::Error::custom(e.to_string()))?;
937        ProcessorConfigSerialized::serialize(&ins, serializer)
938    }
939}
940
941impl<'de> serde::de::Deserialize<'de> for ProcessorConfig {
942    fn deserialize<D>(deserializer: D) -> core::result::Result<Self, D::Error>
943    where D: serde::Deserializer<'de> {
944        match ProcessorConfigSerialized::deserialize(deserializer) {
945            Ok(ins) => {
946                let cfg: ProcessorConfig = ins
947                    .try_into()
948                    .map_err(|e: Error| serde::de::Error::custom(e.to_string()))?;
949                Ok(cfg)
950            }
951            Err(e) => Err(e),
952        }
953    }
954}