rings-node 0.20.0

Rings is a structured peer-to-peer network implementation using WebRTC, Chord algorithm, and full WebAssembly (WASM) support.
Documentation
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
use std::env;
use std::fs;
use std::io;
use std::path::PathBuf;

use rings_gateway::GatewayConfig;
use serde::Deserialize;
use serde::Serialize;

use crate::error::Error;
use crate::error::Result;
use crate::onion::OnionExitPolicy;
use crate::onion::OnionExitService;
use crate::onion::OnionServiceName;
use crate::online::OnlineNodeType;
use crate::prelude::rings_core::dht::default_storage_virtual_positions_per_owner;
use crate::prelude::rings_core::dht::DEFAULT_STORAGE_VIRTUAL_POSITIONS_PER_OWNER;
use crate::prelude::rings_core::ecc::SecretKey;
use crate::prelude::SessionSk;
use crate::processor::ProcessorConfig;
use crate::processor::ProcessorConfigSerialized;
use crate::util::ensure_parent_dir;
use crate::util::expand_home;

lazy_static::lazy_static! {
  static ref DEFAULT_DATA_STORAGE_CONFIG: StorageConfig = StorageConfig {
    path: get_storage_location(".rings", "data"),
    capacity: DEFAULT_STORAGE_CAPACITY,
  };
  static ref DEFAULT_MEASURE_STORAGE_CONFIG: StorageConfig = StorageConfig {
    path: get_storage_location(".rings", "measure"),
    capacity: DEFAULT_STORAGE_CAPACITY,
  };
}

/// Default Rings network identifier for native nodes.
pub const DEFAULT_NETWORK_ID: u32 = 1;
/// Default internal JSON-RPC API port.
pub const DEFAULT_INTERNAL_API_PORT: u16 = 50000;
/// Default external JSON-RPC listener address.
pub const DEFAULT_EXTERNAL_API_ADDR: &str = "127.0.0.1:50001";
/// Default internal endpoint URL used by CLI clients.
pub const DEFAULT_ENDPOINT_URL: &str = "http://127.0.0.1:50000";
/// Default WebRTC ICE server list.
pub const DEFAULT_ICE_SERVERS: &str = "stun://stun.l.google.com:19302";
/// Default Chord stabilization interval in seconds.
pub const DEFAULT_STABILIZE_INTERVAL: u64 = 15;
/// Default storage capacity in bytes for native storage backends.
pub const DEFAULT_STORAGE_CAPACITY: u32 = 200000000;
/// Default interval for refreshing gateway status.
pub const DEFAULT_GATEWAY_STATUS_REFRESH_SECS: u64 = 2;

/// Native foreground-gateway configuration.
#[derive(Debug, Clone, Deserialize, Serialize)]
pub struct NativeGatewayConfig {
    /// Whether `rings run` starts the gateway when this section is present.
    #[serde(default = "default_true")]
    pub enabled: bool,
    /// Platform-neutral routing, TCP, and flow limits.
    #[serde(flatten)]
    pub runtime: GatewayConfig,
    /// Requested Wintun interface name; on Unix the helper's `--interface` is authoritative.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub interface_name: Option<String>,
    /// Durable journal used directly on Windows; on Unix the helper's `--ledger` is authoritative.
    #[serde(default = "default_gateway_route_ledger_path")]
    pub route_ledger_path: String,
    /// Foreground `gateway-config-unix` control socket on Linux and macOS.
    #[serde(default = "default_gateway_unix_helper_socket")]
    pub unix_helper_socket: String,
    /// Optional explicit Wintun DLL path on Windows; overrides `RINGS_GATEWAY_WINTUN_DLL`.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub wintun_dll_path: Option<String>,
    /// Interval for refreshing Onion exit availability in gateway status.
    #[serde(default = "default_gateway_status_refresh_secs")]
    pub status_refresh_secs: u64,
    /// Onion TCP exit service selected for captured flows.
    #[serde(default = "OnionServiceName::tcp")]
    pub onion_service: OnionServiceName,
    /// Requested onion route hop count; zero selects the node default.
    #[serde(default)]
    pub onion_hop_count: usize,
    /// Permit shorter onion paths when the requested hop count is unavailable.
    #[serde(default)]
    pub onion_allow_short_paths: bool,
}

const fn default_true() -> bool {
    true
}

const fn default_gateway_status_refresh_secs() -> u64 {
    DEFAULT_GATEWAY_STATUS_REFRESH_SECS
}

fn default_gateway_route_ledger_path() -> String {
    get_storage_location(".rings", "gateway-routes.json")
}

fn default_gateway_unix_helper_socket() -> String {
    get_storage_location(".rings", "gateway-helper.sock")
}

/// Builds the default storage path under the user home directory.
pub fn get_storage_location<P>(prefix: P, path: P) -> String
where P: AsRef<std::path::Path> {
    let home_dir = env::var_os("HOME").map(PathBuf::from);
    let storage_path = match home_dir {
        Some(dir) => dir.join(prefix).join(path),
        None => std::path::Path::new("data").join(prefix).join(path),
    };
    storage_path.to_string_lossy().to_string()
}

/// Serializable native-node configuration.
#[derive(Debug, Clone, Deserialize, Serialize)]
pub struct Config {
    /// Rings network identifier this node joins.
    pub network_id: u32,
    /// Deprecated ECDSA key field retained for backward-compatible config reads.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub ecdsa_key: Option<SecretKey>,
    /// Deprecated session manager field retained for backward-compatible config reads.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub session_manager: Option<String>,
    /// Session secret key file path or legacy raw session key string.
    pub session_sk: Option<String>,
    /// Internal JSON-RPC API port.
    pub internal_api_port: u16,
    /// External JSON-RPC listener address.
    pub external_api_addr: String,
    /// Internal endpoint URL used by local clients.
    pub endpoint_url: String,
    /// WebRTC ICE server list, independent from optional gateway ingress.
    pub ice_servers: String,
    /// Chord stabilization interval in seconds.
    pub stabilize_interval: u64,
    /// Presence descriptor heartbeat interval in seconds.
    #[serde(default = "crate::registration::default_online_node_heartbeat_interval_secs")]
    pub online_node_heartbeat_interval_secs: u64,
    /// Presence descriptor time-to-live in seconds.
    #[serde(default = "crate::registration::default_online_node_ttl_secs")]
    pub online_node_ttl_secs: u64,
    /// Node type advertised in online-node descriptors.
    #[serde(default = "crate::registration::default_online_node_type")]
    pub online_node_type: OnlineNodeType,
    /// Whether this node publishes online-node descriptors.
    #[serde(default = "crate::registration::default_advertise_presence")]
    pub advertise_presence: bool,
    /// Whether this node advertises onion relay capability.
    #[serde(default = "crate::onion::default_advertise_onion_relay")]
    pub advertise_onion_relay: bool,
    /// Whether this node advertises onion exit capability.
    #[serde(default = "crate::onion::default_advertise_onion_exit")]
    pub advertise_onion_exit: bool,
    /// Onion-exit descriptor heartbeat interval in seconds.
    #[serde(default = "crate::onion::default_onion_exit_heartbeat_interval_secs")]
    pub onion_exit_heartbeat_interval_secs: u64,
    /// Onion-exit descriptor time-to-live in seconds.
    #[serde(default = "crate::onion::default_onion_exit_ttl_secs")]
    pub onion_exit_ttl_secs: u64,
    /// Onion-exit services this node can publish.
    #[serde(default = "crate::onion::default_onion_exit_services")]
    pub onion_exit_services: Vec<OnionExitService>,
    /// Onion-exit target and resource policy.
    #[serde(default = "crate::onion::default_onion_exit_policy")]
    pub onion_exit_policy: OnionExitPolicy,
    /// Optional local HTTP CONNECT proxy listener address.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub onion_http_proxy_addr: Option<String>,
    /// Onion service name used by the HTTP CONNECT proxy.
    #[serde(default = "OnionServiceName::tcp")]
    pub onion_http_proxy_service: OnionServiceName,
    /// Requested hop count for HTTP CONNECT proxy routes.
    #[serde(default)]
    pub onion_http_proxy_hop_count: usize,
    /// Whether the HTTP CONNECT proxy may use shorter routes when needed.
    #[serde(default)]
    pub onion_http_proxy_allow_short_paths: bool,
    /// Timeout for reading HTTP CONNECT headers in seconds.
    #[serde(default = "crate::onion::proxy::http::default_connect_header_timeout_secs")]
    pub onion_http_proxy_header_timeout_secs: u64,
    /// Maximum simultaneous HTTP CONNECT proxy connections.
    #[serde(default = "crate::onion::proxy::http::default_max_connect_connections")]
    pub onion_http_proxy_max_connections: usize,
    /// Optional native TUN gateway started in the same foreground lifecycle.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub gateway: Option<NativeGatewayConfig>,
    /// Virtual DHT positions per storage owner.
    #[serde(default = "default_storage_virtual_positions_per_owner")]
    pub dht_virtual_nodes: u16,
    /// Optional externally reachable IP address hint.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub external_ip: Option<String>,
    /// Optional lower bound for WebRTC UDP port allocation.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub webrtc_udp_port_min: Option<u16>,
    /// Optional upper bound for WebRTC UDP port allocation.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub webrtc_udp_port_max: Option<u16>,
    /// Persistent DHT data storage configuration.
    pub data_storage: StorageConfig,
    /// Peer measurement storage configuration.
    pub measure_storage: StorageConfig,
}

impl TryFrom<Config> for ProcessorConfigSerialized {
    type Error = Error;
    fn try_from(config: Config) -> Result<Self> {
        // Support old version
        let session_sk: String = if let Some(sk) = config.ecdsa_key {
            tracing::warn!("Field `ecdsa_key` is deprecated, use `session_sk` instead.");
            SessionSk::new_with_seckey(&sk)
                .and_then(|session_sk| session_sk.dump())
                .map_err(|e| Error::VerifyError(e.to_string()))?
        } else if let Some(ssk) = config.session_manager {
            tracing::warn!("Field `session_manager` is deprecated, use `session_sk` instead.");
            ssk
        } else {
            let Some(ssk_file) = config.session_sk else {
                return Err(Error::InvalidData);
            };
            let ssk_file_expand_home = expand_home(&ssk_file)?;
            fs::read_to_string(ssk_file_expand_home).unwrap_or_else(|e| {
                tracing::warn!("Read session_sk file failed: {e:?}. Handling it as raw session_sk string. This mode is deprecated. please use a file path.");
                ssk_file
            })
        };

        let mut cs = Self::new(
            config.network_id,
            config.ice_servers,
            session_sk,
            config.stabilize_interval,
        )
        .online_node_heartbeat_interval_secs(config.online_node_heartbeat_interval_secs)
        .online_node_ttl_secs(config.online_node_ttl_secs)
        .online_node_type(config.online_node_type)
        .advertise_presence(config.advertise_presence)
        .advertise_onion_relay(config.advertise_onion_relay)
        .advertise_onion_exit(config.advertise_onion_exit)
        .onion_exit_heartbeat_interval_secs(config.onion_exit_heartbeat_interval_secs)
        .onion_exit_ttl_secs(config.onion_exit_ttl_secs)
        .onion_exit_services(config.onion_exit_services)
        .onion_exit_policy(config.onion_exit_policy)
        .dht_virtual_nodes(config.dht_virtual_nodes);

        cs = if let Some(ext_ip) = config.external_ip {
            cs.external_address(ext_ip)
        } else {
            cs
        };
        let udp_range = crate::processor::parse_webrtc_udp_port_range(
            config.webrtc_udp_port_min,
            config.webrtc_udp_port_max,
        )?;
        cs = if let Some(range) = udp_range {
            cs.webrtc_udp_port_range(range)
        } else {
            cs
        };

        Ok(cs)
    }
}

impl TryFrom<Config> for ProcessorConfig {
    type Error = Error;
    fn try_from(config: Config) -> Result<Self> {
        ProcessorConfigSerialized::try_from(config).and_then(Self::try_from)
    }
}

impl Config {
    /// Creates a default native-node configuration using the supplied session key path.
    pub fn new<P>(session_sk: P) -> Self
    where P: AsRef<std::path::Path> {
        let session_sk = session_sk.as_ref().to_string_lossy().to_string();
        Self {
            network_id: DEFAULT_NETWORK_ID,
            ecdsa_key: None,
            session_manager: None,
            session_sk: Some(session_sk),
            internal_api_port: DEFAULT_INTERNAL_API_PORT,
            external_api_addr: DEFAULT_EXTERNAL_API_ADDR.to_string(),
            endpoint_url: DEFAULT_ENDPOINT_URL.to_string(),
            ice_servers: DEFAULT_ICE_SERVERS.to_string(),
            stabilize_interval: DEFAULT_STABILIZE_INTERVAL,
            online_node_heartbeat_interval_secs:
                crate::registration::default_online_node_heartbeat_interval_secs(),
            online_node_ttl_secs: crate::registration::default_online_node_ttl_secs(),
            online_node_type: crate::registration::default_online_node_type(),
            advertise_presence: crate::registration::default_advertise_presence(),
            advertise_onion_relay: crate::onion::default_advertise_onion_relay(),
            advertise_onion_exit: crate::onion::default_advertise_onion_exit(),
            onion_exit_heartbeat_interval_secs:
                crate::onion::default_onion_exit_heartbeat_interval_secs(),
            onion_exit_ttl_secs: crate::onion::default_onion_exit_ttl_secs(),
            onion_exit_services: crate::onion::default_onion_exit_services(),
            onion_exit_policy: crate::onion::default_onion_exit_policy(),
            onion_http_proxy_addr: None,
            onion_http_proxy_service: OnionServiceName::tcp(),
            onion_http_proxy_hop_count: 0,
            onion_http_proxy_allow_short_paths: false,
            onion_http_proxy_header_timeout_secs:
                crate::onion::proxy::http::default_connect_header_timeout_secs(),
            onion_http_proxy_max_connections:
                crate::onion::proxy::http::default_max_connect_connections(),
            gateway: None,
            dht_virtual_nodes: DEFAULT_STORAGE_VIRTUAL_POSITIONS_PER_OWNER,
            external_ip: None,
            webrtc_udp_port_min: None,
            webrtc_udp_port_max: None,
            data_storage: DEFAULT_DATA_STORAGE_CONFIG.clone(),
            measure_storage: DEFAULT_MEASURE_STORAGE_CONFIG.clone(),
        }
    }

    /// Writes this configuration to a YAML file and returns the written path.
    pub fn write_fs<P>(&self, path: P) -> Result<String>
    where P: AsRef<std::path::Path> {
        let path = expand_home(path)?;
        ensure_parent_dir(&path)?;
        let f =
            fs::File::create(path.as_path()).map_err(|e| Error::CreateFileError(e.to_string()))?;
        let f_writer = io::BufWriter::new(f);
        serde_yaml::to_writer(f_writer, self).map_err(|_| Error::EncodeError)?;
        path.to_str()
            .map(str::to_owned)
            .ok_or_else(|| Error::PathUtf8Error(path.display().to_string()))
    }

    /// Reads a native-node configuration from a YAML file.
    pub fn read_fs<P>(path: P) -> Result<Config>
    where P: AsRef<std::path::Path> {
        let path = expand_home(path)?;
        tracing::debug!("Read config from: {:?}", path);
        let f = fs::File::open(path).map_err(|e| Error::OpenFileError(e.to_string()))?;
        let f_rdr = io::BufReader::new(f);
        serde_yaml::from_reader(f_rdr).map_err(|_| Error::EncodeError)
    }
}

/// Configuration for a node storage backend.
#[derive(Debug, Clone, Deserialize, Serialize)]
pub struct StorageConfig {
    /// Storage directory path.
    pub path: String,
    /// Storage capacity in bytes.
    pub capacity: u32,
}

impl StorageConfig {
    /// Creates a storage configuration from a path and capacity.
    pub fn new(path: &str, capacity: u32) -> Self {
        Self {
            path: path.to_string(),
            capacity,
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    fn dumped_session_sk() -> String {
        let key = SecretKey::random();
        let session = match SessionSk::new_with_seckey(&key) {
            Ok(session) => session,
            Err(error) => panic!("session key construction failed: {error}"),
        };
        match session.dump() {
            Ok(dump) => dump,
            Err(error) => panic!("session key dump failed: {error}"),
        }
    }

    #[test]
    fn test_deserialization_defaults_online_registration_fields() {
        let yaml = r#"
network_id: 1
session_sk: session_sk
internal_api_port: 50000
external_api_addr: 127.0.0.1:50001
endpoint_url: http://127.0.0.1:50000
ice_servers: stun://stun.l.google.com:19302
stabilize_interval: 15
external_ip: null
webrtc_udp_port_min: null
webrtc_udp_port_max: null
data_storage:
  path: /Users/foo/.rings/data
  capacity: 200000000
measure_storage:
  path: /Users/foo/.rings/measure
  capacity: 200000000
"#;
        let cfg: Config = serde_yaml::from_str(yaml).unwrap();
        assert_eq!(cfg.network_id, 1);
        assert_eq!(
            cfg.dht_virtual_nodes,
            DEFAULT_STORAGE_VIRTUAL_POSITIONS_PER_OWNER
        );
        assert!(cfg.advertise_presence);
        assert!(!cfg.advertise_onion_relay);
        assert!(!cfg.advertise_onion_exit);
        assert_eq!(cfg.onion_http_proxy_addr, None);
        assert_eq!(cfg.onion_http_proxy_service, OnionServiceName::tcp());
        assert_eq!(cfg.onion_http_proxy_hop_count, 0);
        assert!(!cfg.onion_http_proxy_allow_short_paths);
        assert_eq!(
            cfg.onion_http_proxy_header_timeout_secs,
            crate::onion::proxy::http::default_connect_header_timeout_secs()
        );
        assert_eq!(
            cfg.onion_http_proxy_max_connections,
            crate::onion::proxy::http::default_max_connect_connections()
        );
        assert_eq!(
            cfg.onion_exit_services,
            crate::onion::default_onion_exit_services()
        );
        assert!(cfg.gateway.is_none());
    }

    #[test]
    fn test_deserialization_preserves_explicit_disabled_dht_virtual_nodes() {
        let yaml = r#"
network_id: 1
session_sk: session_sk
internal_api_port: 50000
external_api_addr: 127.0.0.1:50001
endpoint_url: http://127.0.0.1:50000
ice_servers: stun://stun.l.google.com:19302
stabilize_interval: 15
dht_virtual_nodes: 0
external_ip: null
webrtc_udp_port_min: null
webrtc_udp_port_max: null
data_storage:
  path: /Users/foo/.rings/data
  capacity: 200000000
measure_storage:
  path: /Users/foo/.rings/measure
  capacity: 200000000
"#;

        let cfg: Config = serde_yaml::from_str(yaml).unwrap();

        assert_eq!(cfg.dht_virtual_nodes, 0);
    }

    #[test]
    fn test_config_with_valid_webrtc_udp_range_builds_processor_config() {
        let mut config = Config::new(dumped_session_sk());
        config.webrtc_udp_port_min = Some(49160);
        config.webrtc_udp_port_max = Some(49200);

        let processor_config = ProcessorConfig::try_from(config);

        assert!(matches!(
            processor_config.and_then(|config| config.webrtc_udp_port_range()),
            Ok(Some(range)) if range.min() == 49160 && range.max() == 49200
        ));
    }

    #[test]
    fn test_config_with_partial_webrtc_udp_range_is_rejected() {
        let mut config = Config::new(dumped_session_sk());
        config.webrtc_udp_port_min = Some(49160);

        let processor_config = ProcessorConfig::try_from(config);

        assert!(matches!(
            processor_config,
            Err(Error::IncompleteWebrtcUdpPortRange {
                min: Some(49160),
                max: None
            })
        ));
    }
}