rings-node 1.0.0-pre.8

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.
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
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
use std::env;
use std::fs;
use std::io;
use std::path::PathBuf;

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

use crate::dns_relay::DnsRelayConfig;
use crate::dns_relay::ServicesConfig;
use crate::error::Error;
use crate::error::Result;
use crate::onion::OnionExitPolicy;
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;
#[cfg(test)]
use crate::prelude::rings_core::ecc::SecretKey;
use crate::prelude::rings_core::message::OriginQuotaConfig;
#[cfg(test)]
use crate::prelude::DelegateeKey;
use crate::processor::ProcessorConfig;
use crate::processor::ProcessorConfigSerialized;
use crate::seed::SeedPeer;
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;
pub use crate::consts::DEFAULT_STORAGE_CAPACITY;
/// Default interval for refreshing gateway status.
pub const DEFAULT_GATEWAY_STATUS_REFRESH_SECS: u64 = 2;

/// Native foreground-gateway configuration: the `gateway:` section of the node config file.
///
/// `rings init` writes this section in full through [`NativeGatewayConfig::disabled_default`],
/// so the generated file is the one place an operator edits and `rings run --gateway` works on
/// it unchanged. Presence of the section is not consent to start a TUN device:
///
/// ```text
/// gateway starts ⟺ section present ∧ (enabled = true ∨ --gateway)
/// ```
///
/// A section that omits `enabled` is inert, and a config without the section loads
/// with `gateway = None`.
#[derive(Debug, Clone, Deserialize, Serialize)]
pub struct NativeGatewayConfig {
    /// Whether plain `rings run` starts the gateway. Absent means `false`; only an explicit
    /// `enabled: true` or `rings run --gateway` starts a TUN device.
    #[serde(default)]
    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)]
    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)]
    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,
}

impl NativeGatewayConfig {
    /// The section `rings init` writes: the gateway crate's interface-only plan under its default
    /// limits, the node's default paths, and `enabled: false`, with every field stated so the
    /// generated file documents the whole surface. Optional fields are written as `null`.
    pub fn disabled_default() -> Self {
        Self {
            enabled: false,
            runtime: GatewayConfig::with_default_limits(GatewayPlan::interface_only()),
            interface_name: None,
            route_ledger_path: default_gateway_route_ledger_path(),
            unix_helper_socket: default_gateway_unix_helper_socket(),
            wintun_dll_path: None,
            status_refresh_secs: default_gateway_status_refresh_secs(),
        }
    }

    /// Render this section as the top-level `gateway:` mapping of a config file, so a message
    /// telling an operator what to add quotes the shape `rings init` writes rather than a copy.
    pub fn to_yaml_section(&self) -> Result<String> {
        serde_saphyr::to_string(&GatewaySection { gateway: self }).map_err(|_| Error::EncodeError)
    }
}

/// A config document consisting of the `gateway:` section alone.
#[derive(Serialize)]
struct GatewaySection<'a> {
    gateway: &'a NativeGatewayConfig,
}

/// Keys of the `gateway:` section: those of [`NativeGatewayConfig`] and of the flattened
/// [`GatewayConfig`], in the order `rings init` writes them.
const GATEWAY_KEYS: [&str; 10] = [
    "enabled",
    "plan",
    "max_flows",
    "flow_idle_timeout",
    "tcp_buffer_bytes",
    "interface_name",
    "route_ledger_path",
    "unix_helper_socket",
    "wintun_dll_path",
    "status_refresh_secs",
];

/// Deserialize the `gateway:` section, rejecting every key outside [`GATEWAY_KEYS`].
///
/// The section flattens [`GatewayConfig`], so serde cannot deny unknown keys there; without this
/// a misspelt key (say `onion_services`) would silently fall back to its default. The section is
/// first read as a format-neutral JSON object, so its keys are checked before its fields are.
fn deserialize_gateway_section<'de, D>(
    deserializer: D,
) -> std::result::Result<Option<NativeGatewayConfig>, D::Error>
where D: serde::Deserializer<'de> {
    let Some(section) =
        Option::<serde_json::Map<String, serde_json::Value>>::deserialize(deserializer)?
    else {
        return Ok(None);
    };
    if let Some(key) = section
        .keys()
        .map(String::as_str)
        .find(|key| !GATEWAY_KEYS.contains(key))
    {
        return Err(serde::de::Error::custom(format!(
            "unknown gateway key {key:?}; expected one of {}",
            GATEWAY_KEYS.join(", ")
        )));
    }
    serde_json::from_value(serde_json::Value::Object(section))
        .map(Some)
        .map_err(serde::de::Error::custom)
}

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()
}

/// The `bootstrap` section: targets `rings run` keeps reachable for the life of the process.
/// `rings init` writes it empty; see [`crate::native::bootstrap`].
#[derive(Clone, Debug, Default, Deserialize, Serialize, PartialEq, Eq)]
pub struct BootstrapConfig {
    /// Managed targets, in the same shape as the entries of a seed document.
    #[serde(default)]
    pub peers: Vec<SeedPeer>,
}

/// Serializable native-node configuration.
#[derive(Debug, Clone, Deserialize, Serialize)]
#[serde(deny_unknown_fields)]
pub struct Config {
    /// Rings network identifier this node joins.
    pub network_id: u32,
    /// Delegation secret key file path.
    pub delegatee_key: String,
    /// Optional delegator secret key file path for in-process delegation renewal before the
    /// signing horizon (#1153); relative paths are resolved next to this config file.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub delegator_key: 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,
    /// Optional HTTP(S) proxy URL used for remote JSON-RPC endpoints (seed and HTTP handshakes).
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub remote_rpc_proxy_url: Option<String>,
    /// Optional API token file path; relative paths are resolved next to this config file.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub api_token_path: Option<String>,
    /// Exact browser origins permitted to call the authenticated API.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub api_allowed_origins: Vec<String>,
    /// Explicitly allow the external API listener to bind a non-loopback address.
    #[serde(default)]
    pub allow_remote_external_api: bool,
    /// WebRTC ICE server list, independent from optional gateway ingress.
    /// Defaults to empty when `network: { kind, params }` selects the transport explicitly.
    #[serde(default)]
    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<OnionServiceName>,
    /// 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>,
    /// 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,
    /// Native TUN gateway section; `rings init` writes it disabled, and it starts a gateway in
    /// the same foreground lifecycle only under `enabled: true` or `--gateway`. Older configs
    /// without the section load as `None`.
    #[serde(
        default,
        deserialize_with = "deserialize_gateway_section",
        skip_serializing_if = "Option::is_none"
    )]
    pub gateway: Option<NativeGatewayConfig>,
    /// Managed bootstrap targets `rings run` keeps reachable for the life of the process.
    #[serde(default)]
    pub bootstrap: BootstrapConfig,
    /// The services this node serves at `<did>.<zone>` through DNS relays (#1049); absent, it
    /// announces nothing.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub services: Option<ServicesConfig>,
    /// The DNS relay this node runs for its zones (#1049), if any.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub dns_relay: Option<DnsRelayConfig>,
    /// Virtual DHT positions per storage owner.
    #[serde(default = "default_storage_virtual_positions_per_owner")]
    pub dht_virtual_nodes: u16,
    /// Runtime-local final-destination quotas keyed by verified origin and logical lane.
    #[serde(default)]
    pub origin_quota: OriginQuotaConfig,
    /// Optional externally reachable IP address hint.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub external_ip: Option<String>,
    /// Optional lower bound for local UDP port allocation.
    #[serde(
        default,
        alias = "webrtc_udp_port_min",
        skip_serializing_if = "Option::is_none"
    )]
    pub udp_port_min: Option<u16>,
    /// Optional upper bound for local UDP port allocation.
    #[serde(
        default,
        alias = "webrtc_udp_port_max",
        skip_serializing_if = "Option::is_none"
    )]
    pub udp_port_max: Option<u16>,
    /// Optional serde-extensible tagged transport configuration (`{ kind, params }`).
    /// When present, overrides the default `"webrtc"` transport constructed from `ice_servers`,
    /// `external_ip`, and `udp_port_min` / `udp_port_max`.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub network: Option<crate::processor::NetworkConfigDescriptor>,
    /// 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> {
        let delegatee_key_path = expand_home(&config.delegatee_key)?;
        let delegatee_key = fs::read_to_string(&delegatee_key_path).map_err(|error| {
            Error::OpenFileError(format!("{}: {error}", delegatee_key_path.display()))
        })?;

        let udp_range =
            crate::processor::parse_udp_port_range(config.udp_port_min, config.udp_port_max)?;
        if config.network.is_some()
            && (!config.ice_servers.trim().is_empty()
                || config.external_ip.is_some()
                || udp_range.is_some())
        {
            return Err(Error::InvalidConfig(
                "cannot specify both `network` and legacy flat WebRTC fields (`ice_servers`, `external_ip`, `udp_port_min`, `udp_port_max`)"
                    .to_string(),
            ));
        }

        Ok(Self {
            network_id: config.network_id,
            ice_servers: config.ice_servers,
            external_address: config.external_ip,
            udp_port_min: udp_range.map(|range| range.min()),
            udp_port_max: udp_range.map(|range| range.max()),
            network: config.network,
            delegatee_key,
            stabilize_interval: 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,
            dht_virtual_nodes: config.dht_virtual_nodes,
            origin_quota: config.origin_quota,
            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,
            onion_invoke_offer: None,
            remote_rpc_proxy_url: config.remote_rpc_proxy_url,
        })
    }
}

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 delegatee key path.
    pub fn new<P>(delegatee_key: P) -> Self
    where P: AsRef<std::path::Path> {
        let delegatee_key = delegatee_key.as_ref().to_string_lossy().to_string();
        Self {
            network_id: DEFAULT_NETWORK_ID,
            delegatee_key,
            delegator_key: None,
            internal_api_port: DEFAULT_INTERNAL_API_PORT,
            external_api_addr: DEFAULT_EXTERNAL_API_ADDR.to_string(),
            endpoint_url: DEFAULT_ENDPOINT_URL.to_string(),
            remote_rpc_proxy_url: None,
            api_token_path: None,
            api_allowed_origins: Vec::new(),
            allow_remote_external_api: false,
            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_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: Some(NativeGatewayConfig::disabled_default()),
            bootstrap: BootstrapConfig::default(),
            services: None,
            dns_relay: None,
            dht_virtual_nodes: DEFAULT_STORAGE_VIRTUAL_POSITIONS_PER_OWNER,
            origin_quota: OriginQuotaConfig::default(),
            external_ip: None,
            udp_port_min: None,
            udp_port_max: None,
            network: None,
            data_storage: DEFAULT_DATA_STORAGE_CONFIG.clone(),
            measure_storage: DEFAULT_MEASURE_STORAGE_CONFIG.clone(),
        }
    }

    /// The gateway section `rings run` starts a runner from, if any.
    ///
    /// Law: `enabled_gateway() = Some(g) ⟺ gateway = Some(g) ∧ g.enabled`. `--gateway` sets
    /// `enabled` before this is consulted, so the flag and the field select the same runner.
    pub fn enabled_gateway(&self) -> Option<&NativeGatewayConfig> {
        self.gateway.as_ref().filter(|gateway| gateway.enabled)
    }

    /// 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 mut f_writer = io::BufWriter::new(f);
        serde_saphyr::to_io_writer(&mut f_writer, self).map_err(|source| {
            Error::ConfigSerialize {
                path: path.clone(),
                source,
            }
        })?;
        io::Write::flush(&mut f_writer).map_err(|e| Error::CreateFileError(e.to_string()))?;
        let f = f_writer
            .into_inner()
            .map_err(|e| Error::CreateFileError(e.into_error().to_string()))?;
        f.sync_all()
            .map_err(|e| Error::CreateFileError(e.to_string()))?;
        path.to_str()
            .map(str::to_owned)
            .ok_or_else(|| Error::PathUtf8Error(path.display().to_string()))
    }

    /// Normalize relative file paths in this configuration (such as `delegator_key`) against the
    /// parent directory of `config_path`.
    pub fn resolve_paths_relative_to<P>(&mut self, config_path: P) -> Result<()>
    where P: AsRef<std::path::Path> {
        let path = expand_home(config_path)?;
        if let Some(delegator_key) = self.delegator_key.as_deref() {
            let expanded = expand_home(delegator_key)?;
            let resolved = if expanded.is_relative() {
                match path.parent() {
                    Some(parent) if !parent.as_os_str().is_empty() => parent.join(expanded),
                    _ => expanded,
                }
            } else {
                expanded
            };
            self.delegator_key = Some(resolved.to_string_lossy().into_owned());
        }
        Ok(())
    }

    /// 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.as_path()).map_err(|e| Error::OpenFileError(e.to_string()))?;
        let f_rdr = io::BufReader::new(f);
        let mut config: Config =
            serde_saphyr::from_reader(f_rdr).map_err(|source| Error::ConfigParse {
                path: path.clone(),
                source: Box::new(source),
            })?;
        config.resolve_paths_relative_to(&path)?;
        Ok(config)
    }
}

/// 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;