rings-node 1.0.0-pre.5

Rings is a browser-native, structured peer-to-peer network: browser tabs and native daemons find each other by DID and talk over WebRTC, routed by a Chord DHT.
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
use rings_core::dht::default_storage_virtual_positions_per_owner;
use rings_core::dht::VirtualNodeConfig;
use rings_core::dht::DEFAULT_STORAGE_VIRTUAL_POSITIONS_PER_OWNER;
use rings_core::dht::MAX_STORAGE_VIRTUAL_POSITIONS_PER_OWNER;
use rings_core::utils::SharedClock;
use rings_core::utils::SystemClock;

use super::*;
use crate::remote_endpoint::RemoteRpcProxy;

/// ProcessorConfig is usually serialized as json or yaml.
/// There is a `from_config` method in [ProcessorBuilder] used to initialize the Builder with a serialized ProcessorConfig.
#[derive(Clone, Debug)]
#[wasm_export]
pub struct ProcessorConfig {
    /// The network_id is used to distinguish different networks.
    /// Use 1 for main network.
    pub(in crate::processor) network_id: u32,
    /// ICE servers for webrtc
    pub(in crate::processor) ice_servers: String,
    /// External address for webrtc
    pub(in crate::processor) external_address: Option<String>,
    /// Inclusive lower native WebRTC UDP port bound.
    pub(in crate::processor) webrtc_udp_port_min: Option<u16>,
    /// Inclusive upper native WebRTC UDP port bound.
    pub(in crate::processor) webrtc_udp_port_max: Option<u16>,
    /// [DelegateeKey].
    pub(in crate::processor) delegatee_key: DelegateeKey,
    /// Stabilization interval.
    pub(in crate::processor) stabilize_interval: Duration,
    /// Online-node registry heartbeat interval.
    pub(in crate::processor) online_node_heartbeat_interval: Duration,
    /// Online-node registry descriptor TTL.
    pub(in crate::processor) online_node_ttl: Duration,
    /// Runtime family advertised in the online-node registry.
    pub(in crate::processor) online_node_type: OnlineNodeType,
    /// Whether listen() advertises this node's presence.
    pub(in crate::processor) advertise_presence: bool,
    /// Storage-only virtual positions derived per physical peer.
    pub(in crate::processor) dht_virtual_nodes: u16,
    /// Runtime-local final-destination quotas keyed by verified origin and logical lane.
    pub(in crate::processor) origin_quota: OriginQuotaConfig,
    /// Onion symbols this process registers (#834 D2).
    pub(in crate::processor) onion_role: OnionRole<OnionExitOffer>,
    /// Onion-exit registry heartbeat interval.
    pub(in crate::processor) onion_exit_heartbeat_interval: Duration,
    /// Onion-exit registry descriptor TTL.
    pub(in crate::processor) onion_exit_ttl: Duration,
    /// Optional HTTP(S) proxy for remote JSON-RPC endpoints on native targets.
    pub(crate) remote_rpc_proxy: Option<RemoteRpcProxy>,
    /// Epoch clock capability injected into this node's runtime subsystems.
    pub(in crate::processor) clock: SharedClock,
}

#[wasm_export]
impl ProcessorConfig {
    /// Creates a new `ProcessorConfig` instance without an external address.
    pub fn new(
        network_id: u32,
        ice_servers: String,
        delegatee_key: DelegateeKey,
        stabilize_interval: u64,
    ) -> Self {
        Self {
            network_id,
            ice_servers,
            external_address: None,
            webrtc_udp_port_min: None,
            webrtc_udp_port_max: None,
            delegatee_key,
            stabilize_interval: Duration::from_secs(stabilize_interval),
            online_node_heartbeat_interval: Duration::from_secs(
                default_online_node_heartbeat_interval_secs(),
            ),
            online_node_ttl: Duration::from_secs(default_online_node_ttl_secs()),
            online_node_type: default_online_node_type(),
            advertise_presence: default_advertise_presence(),
            dht_virtual_nodes: DEFAULT_STORAGE_VIRTUAL_POSITIONS_PER_OWNER,
            origin_quota: OriginQuotaConfig::default(),
            onion_role: OnionRole::Client,
            onion_exit_heartbeat_interval: Duration::from_secs(
                default_onion_exit_heartbeat_interval_secs(),
            ),
            onion_exit_ttl: Duration::from_secs(default_onion_exit_ttl_secs()),
            remote_rpc_proxy: None,
            clock: Arc::new(SystemClock),
        }
    }

    /// Return associated [DelegateeKey].
    pub fn delegatee_key(&self) -> DelegateeKey {
        self.delegatee_key.clone()
    }

    /// Return the overlay this node joins.
    pub fn network_id(&self) -> u32 {
        self.network_id
    }

    /// Sets storage-only virtual positions derived per physical peer.
    ///
    /// Serialized configs reject values above
    /// [`MAX_STORAGE_VIRTUAL_POSITIONS_PER_OWNER`]. This setter is infallible
    /// for direct programmatic use; the core swarm builder normalizes the value
    /// once before storage ownership and protocol advertisement are created.
    pub fn dht_virtual_nodes(mut self, positions_per_peer: u16) -> Self {
        self.dht_virtual_nodes = positions_per_peer;
        self
    }

    /// Enable or disable onion relay advertisement on this node.
    ///
    /// When enabling relay while currently `Client`, upgrades the role to `Relay`; when disabling
    /// relay, resets the role to `Client`.
    pub fn advertise_onion_relay(mut self, enabled: bool) -> Self {
        self.onion_role = match (enabled, self.onion_role) {
            (true, OnionRole::Client) => OnionRole::Relay,
            (true, role) => role,
            (false, _) => OnionRole::Client,
        };
        self
    }
}

impl ProcessorConfig {
    /// Override the runtime family advertised in the online-node registry.
    pub fn online_node_type(mut self, node_type: OnlineNodeType) -> Self {
        self.online_node_type = node_type;
        self
    }
    /// Returns the validated native WebRTC UDP port range, when configured.
    pub fn webrtc_udp_port_range(&self) -> Result<Option<WebrtcUdpPortRange>> {
        parse_webrtc_udp_port_range(self.webrtc_udp_port_min, self.webrtc_udp_port_max)
    }

    /// The longer heartbeat of the two registries this node publishes, online nodes and onion
    /// exits: the pause after which each of its registrations is published again.
    pub fn registry_heartbeat_interval(&self) -> Duration {
        self.online_node_heartbeat_interval
            .max(self.onion_exit_heartbeat_interval)
    }

    /// Sets the onion symbols this process registers (#834 D2).
    pub fn onion_role(mut self, role: OnionRole<OnionExitOffer>) -> Self {
        self.onion_role = role;
        self
    }

    /// Validate this config's onion role ([`validate_onion_role_config`]) before any runtime
    /// effect, as the builder does at build time.
    #[cfg(all(feature = "browser", target_family = "wasm"))]
    pub(crate) fn validate_onion_role(&self) -> Result<()> {
        validate_onion_role_config(self.advertise_presence, &self.onion_role)
    }

    /// Sets runtime-local final-destination quotas keyed by verified origin and logical lane.
    pub fn origin_quota(mut self, config: OriginQuotaConfig) -> Self {
        self.origin_quota = config;
        self
    }

    /// Route native remote JSON-RPC requests (`nodeDid`, `answerOffer`, `acceptAnswer`) through
    /// `proxy` instead of connecting directly.
    pub fn remote_rpc_proxy(mut self, proxy: RemoteRpcProxy) -> Self {
        self.remote_rpc_proxy = Some(proxy);
        self
    }

    /// Return the [`SharedClock`] capability configured for this node.
    pub fn clock(&self) -> &SharedClock {
        &self.clock
    }

    /// Inject a custom [`SharedClock`] capability for deterministic node time.
    pub fn with_clock(mut self, clock: SharedClock) -> Self {
        self.clock = clock;
        self
    }
}

impl FromStr for ProcessorConfig {
    type Err = Error;
    /// Reveal config from serialized string.
    fn from_str(ser: &str) -> Result<Self> {
        Ok(serde_saphyr::from_str::<ProcessorConfig>(ser)?)
    }
}

/// `ProcessorConfigSerialized` is a serialized version of `ProcessorConfig`.
/// Instead of storing the `DelegateeKey` instance, it stores the dumped string representation of
/// the delegatee key.
#[derive(Serialize, Deserialize, Clone)]
#[wasm_export]
pub struct ProcessorConfigSerialized {
    /// The network_id is used to distinguish different networks.
    /// Use 1 for main network.
    pub(crate) network_id: u32,
    /// A string representing ICE servers for WebRTC
    pub(crate) ice_servers: String,
    /// An optional string representing the external address for WebRTC
    pub(crate) external_address: Option<String>,
    /// Inclusive lower native WebRTC UDP port bound.
    pub(crate) webrtc_udp_port_min: Option<u16>,
    /// Inclusive upper native WebRTC UDP port bound.
    pub(crate) webrtc_udp_port_max: Option<u16>,
    /// A string representing the dumped `DelegateeKey`.
    pub(crate) delegatee_key: String,
    /// An unsigned integer representing the stabilization interval in seconds.
    pub(crate) stabilize_interval: u64,
    /// Online-node registry heartbeat interval in seconds.
    #[serde(default = "default_online_node_heartbeat_interval_secs")]
    pub(crate) online_node_heartbeat_interval_secs: u64,
    /// Online-node registry descriptor TTL in seconds.
    #[serde(default = "default_online_node_ttl_secs")]
    pub(crate) online_node_ttl_secs: u64,
    /// Runtime family advertised in the online-node registry.
    #[serde(default = "default_online_node_type")]
    pub(crate) online_node_type: OnlineNodeType,
    /// Whether listen() advertises this node's presence.
    #[serde(default = "default_advertise_presence")]
    pub(crate) advertise_presence: bool,
    /// Storage-only virtual positions derived per physical peer.
    #[serde(default = "default_storage_virtual_positions_per_owner")]
    pub(crate) dht_virtual_nodes: u16,
    /// Runtime-local final-destination quotas keyed by verified origin and logical lane.
    #[serde(default)]
    pub(crate) origin_quota: OriginQuotaConfig,
    /// Whether listen() advertises onion relay capability.
    #[serde(default = "default_advertise_onion_relay")]
    pub(crate) advertise_onion_relay: bool,
    /// Whether listen() publishes an onion-exit descriptor.
    #[serde(default = "default_advertise_onion_exit")]
    pub(crate) advertise_onion_exit: bool,
    /// Onion-exit registry heartbeat interval in seconds.
    #[serde(default = "default_onion_exit_heartbeat_interval_secs")]
    pub(crate) onion_exit_heartbeat_interval_secs: u64,
    /// Onion-exit registry descriptor TTL in seconds.
    #[serde(default = "default_onion_exit_ttl_secs")]
    pub(crate) onion_exit_ttl_secs: u64,
    /// Exit services advertised by this node.
    #[serde(default = "default_onion_exit_services")]
    pub(crate) onion_exit_services: Vec<OnionServiceName>,
    /// Exit policy advertised by this node.
    #[serde(default = "default_onion_exit_policy")]
    pub(crate) onion_exit_policy: OnionExitPolicy,
    /// Optional intermediate `invoke` offer advertised by this node.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub(crate) onion_invoke_offer: Option<crate::onion::OnionInvokeOffer>,
    /// Optional HTTP(S) proxy URL for remote JSON-RPC endpoints on native targets.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub(crate) remote_rpc_proxy_url: Option<String>,
}

pub(crate) fn parse_webrtc_udp_port_range(
    min: Option<u16>,
    max: Option<u16>,
) -> Result<Option<WebrtcUdpPortRange>> {
    match (min, max) {
        (None, None) => Ok(None),
        (Some(min), Some(max)) => WebrtcUdpPortRange::new(min, max)
            .map(Some)
            .map_err(Error::from),
        (min, max) => Err(Error::IncompleteWebrtcUdpPortRange { min, max }),
    }
}

pub(in crate::processor) fn validate_dht_virtual_nodes(positions_per_peer: u16) -> Result<()> {
    if VirtualNodeConfig::positions_per_owner_within_limit(positions_per_peer) {
        return Ok(());
    }

    Err(Error::InvalidConfig(format!(
        "dht_virtual_nodes {positions_per_peer} exceeds maximum {MAX_STORAGE_VIRTUAL_POSITIONS_PER_OWNER}"
    )))
}

/// Validate that the onion role can be published and served.
///
/// - `relay ∈ Σ_n ⇒ advertise_presence`, because the relay registration lives in the online-node
///   descriptor.
/// - Every offered exit service is one this node's runtime interprets
///   ([`OnionExitOffer::uninterpretable_service`]), so no descriptor names a service the node
///   cannot evaluate.
///
/// `Σ_n ≠ ∅ ⇒ relay ∈ Σ_n` needs no check: [`OnionRole`] has no rung that registers a symbol
/// without `relay`.
pub(in crate::processor) fn validate_onion_role_config(
    advertise_presence: bool,
    onion_role: &OnionRole<OnionExitOffer>,
) -> Result<()> {
    if let Some(service) = onion_role
        .exit()
        .and_then(OnionExitOffer::uninterpretable_service)
    {
        return Err(Error::UninterpretableOnionService {
            service: service.clone(),
        });
    }
    #[cfg(rings_browser)]
    if let Some(offer) = onion_role.exit() {
        offer.policy().validate_browser_targets()?;
    }
    if onion_role.registers_relay() && !advertise_presence {
        return Err(Error::InvalidConfig(
            "advertise_onion_relay requires advertise_presence because relay capability is published in online-node descriptors"
                .to_string(),
        ));
    }
    Ok(())
}

impl TryFrom<ProcessorConfig> for ProcessorConfigSerialized {
    type Error = Error;
    fn try_from(ins: ProcessorConfig) -> Result<Self> {
        Ok(Self {
            network_id: ins.network_id,
            ice_servers: ins.ice_servers.clone(),
            external_address: ins.external_address.clone(),
            webrtc_udp_port_min: ins.webrtc_udp_port_min,
            webrtc_udp_port_max: ins.webrtc_udp_port_max,
            delegatee_key: ins.delegatee_key.dump()?,
            stabilize_interval: ins.stabilize_interval.as_secs(),
            online_node_heartbeat_interval_secs: ins.online_node_heartbeat_interval.as_secs(),
            online_node_ttl_secs: ins.online_node_ttl.as_secs(),
            online_node_type: ins.online_node_type,
            advertise_presence: ins.advertise_presence,
            dht_virtual_nodes: ins.dht_virtual_nodes,
            origin_quota: ins.origin_quota,
            advertise_onion_relay: ins.onion_role.registers_relay(),
            advertise_onion_exit: ins.onion_role.exit().is_some(),
            onion_exit_heartbeat_interval_secs: ins.onion_exit_heartbeat_interval.as_secs(),
            onion_exit_ttl_secs: ins.onion_exit_ttl.as_secs(),
            onion_exit_services: ins
                .onion_role
                .exit()
                .map_or_else(default_onion_exit_services, |offer| {
                    offer.services().iter().cloned().collect()
                }),
            onion_exit_policy: ins
                .onion_role
                .exit()
                .map_or_else(default_onion_exit_policy, |offer| offer.policy().clone()),
            onion_invoke_offer: ins.onion_role.invoke().cloned(),
            remote_rpc_proxy_url: ins
                .remote_rpc_proxy
                .as_ref()
                .map(|proxy| proxy.as_str().to_owned()),
        })
    }
}

impl TryFrom<ProcessorConfigSerialized> for ProcessorConfig {
    type Error = Error;
    fn try_from(ins: ProcessorConfigSerialized) -> Result<Self> {
        let webrtc_udp_port_range =
            parse_webrtc_udp_port_range(ins.webrtc_udp_port_min, ins.webrtc_udp_port_max)?;
        let remote_rpc_proxy = ins
            .remote_rpc_proxy_url
            .as_deref()
            .map(RemoteRpcProxy::parse)
            .transpose()?;
        let online_node_heartbeat_interval =
            Duration::from_secs(ins.online_node_heartbeat_interval_secs);
        let online_node_ttl = Duration::from_secs(ins.online_node_ttl_secs);
        let onion_exit_heartbeat_interval =
            Duration::from_secs(ins.onion_exit_heartbeat_interval_secs);
        let onion_exit_ttl = Duration::from_secs(ins.onion_exit_ttl_secs);
        Ok(Self {
            network_id: ins.network_id,
            ice_servers: ins.ice_servers.clone(),
            external_address: ins.external_address.clone(),
            webrtc_udp_port_min: webrtc_udp_port_range.map(WebrtcUdpPortRange::min),
            webrtc_udp_port_max: webrtc_udp_port_range.map(WebrtcUdpPortRange::max),
            delegatee_key: DelegateeKey::from_str(&ins.delegatee_key)?,
            stabilize_interval: Duration::from_secs(ins.stabilize_interval),
            online_node_heartbeat_interval,
            online_node_ttl,
            online_node_type: ins.online_node_type,
            advertise_presence: ins.advertise_presence,
            dht_virtual_nodes: ins.dht_virtual_nodes,
            origin_quota: ins.origin_quota,
            onion_role: {
                let role = OnionRole::from_flags(
                    ins.advertise_onion_relay,
                    ins.advertise_onion_exit,
                    ins.onion_exit_services,
                    ins.onion_exit_policy,
                )?;
                match ins.onion_invoke_offer {
                    Some(invoke) => {
                        if !ins.advertise_onion_relay {
                            return Err(Error::InvalidConfig(
                                "onion_invoke_offer requires advertise_onion_relay".to_string(),
                            ));
                        }
                        role.with_invoke(invoke)
                    }
                    None => role,
                }
            },
            onion_exit_heartbeat_interval,
            onion_exit_ttl,
            remote_rpc_proxy,
            clock: Arc::new(SystemClock),
        })
    }
}

impl Serialize for ProcessorConfig {
    fn serialize<S: serde::Serializer>(
        &self,
        serializer: S,
    ) -> core::result::Result<S::Ok, S::Error> {
        let ins: ProcessorConfigSerialized = self
            .clone()
            .try_into()
            .map_err(|e: Error| serde::ser::Error::custom(e.to_string()))?;
        ProcessorConfigSerialized::serialize(&ins, serializer)
    }
}

impl<'de> serde::de::Deserialize<'de> for ProcessorConfig {
    fn deserialize<D>(deserializer: D) -> core::result::Result<Self, D::Error>
    where D: serde::Deserializer<'de> {
        match ProcessorConfigSerialized::deserialize(deserializer) {
            Ok(ins) => {
                let cfg: ProcessorConfig = ins
                    .try_into()
                    .map_err(|e: Error| serde::de::Error::custom(e.to_string()))?;
                Ok(cfg)
            }
            Err(e) => Err(e),
        }
    }
}