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
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
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
//! The command line of the native node: the top-level parser, its subcommands, and the
//! arguments each takes.

use anyhow::Context;
use clap::ArgAction;
use clap::Args;
use clap::Parser;
use clap::Subcommand;
use clap::ValueEnum;
use rings_node::logging::LogLevel;
use rings_node::native::api_auth::load_api_token;
use rings_node::native::cli::Client;
use rings_node::native::config;
use rings_node::native::horizon::write_delegatee_key_atomically;
use rings_node::onion::OnionServiceName;
use rings_node::prelude::rings_core::chunk::ReassemblyLimits;
use rings_node::prelude::rings_core::delegation::DelegateeKey;
use rings_node::prelude::rings_core::ecc::SecretKey;
use rings_node::prelude::rings_core::utils::get_epoch_ms;

#[derive(Parser, Debug)]
#[command(about, version, author)]
pub(crate) struct Cli {
    #[command(subcommand)]
    pub(crate) command: Command,

    #[arg(long, default_value_t = LogLevel::default(), value_enum, env)]
    pub(crate) log_level: LogLevel,

    #[arg(
        long,
        value_enum,
        default_value = "multi-thread",
        env,
        help = "Tokio runtime scheduler for this process"
    )]
    pub(crate) runtime: RuntimeFlavor,
}

#[derive(Clone, Copy, Debug, Eq, PartialEq, ValueEnum)]
pub(crate) enum RuntimeFlavor {
    MultiThread,
    CurrentThread,
}

impl RuntimeFlavor {
    pub(crate) fn build(self) -> std::io::Result<tokio::runtime::Runtime> {
        match self {
            Self::MultiThread => tokio::runtime::Builder::new_multi_thread()
                .enable_all()
                .build(),
            Self::CurrentThread => tokio::runtime::Builder::new_current_thread()
                .enable_all()
                .build(),
        }
    }
}

#[derive(Clone, Copy, Debug, Eq, PartialEq, ValueEnum)]
pub(crate) enum ReassemblyProfile {
    Production,
    Constrained,
}

impl ReassemblyProfile {
    pub(crate) fn limits(self) -> ReassemblyLimits {
        match self {
            Self::Production => ReassemblyLimits::production(),
            Self::Constrained => ReassemblyLimits::constrained(),
        }
    }
}

/// Parse a singular onion-exit service name from the run command.
fn parse_onion_exit_service(raw: &str) -> Result<OnionServiceName, String> {
    OnionServiceName::parse(raw).map_err(|error| error.to_string())
}

/// Resolves a handshake payload argument that may be `-`, meaning "read it from stdin".
///
/// The base58-check offer/answer strings are long and awkward to pass inline, so the
/// manual-handshake subcommands accept `-` and consume stdin (trimmed) instead.
pub(crate) fn payload_arg_or_stdin(value: &str) -> anyhow::Result<String> {
    if value != "-" {
        return Ok(value.to_string());
    }

    let mut buf = String::new();
    std::io::Read::read_to_string(&mut std::io::stdin(), &mut buf)
        .context("failed to read handshake payload from stdin")?;
    Ok(buf.trim().to_string())
}

#[derive(Subcommand, Debug)]
#[command(rename_all = "kebab-case")]
pub(crate) enum Command {
    #[command(about = "Initializes a node with the given configuration.")]
    Init(InitCommand),
    #[command(about = "Creates a new delegatee signing key.")]
    NewDelegation(NewDelegationCommand),
    #[command(about = "Runs a foreground, composable Rings node.")]
    Run(Box<RunCommand>),
    #[command(about = "Provides chat room-like functionality on the Rings Network.")]
    Pubsub(PubsubCommand),
    #[command(about = "Connects to a remote peer.", subcommand)]
    Connect(ConnectCommand),
    #[command(about = "Manages peers on the network.", subcommand)]
    Peer(PeerCommand),
    #[command(about = "Sends a message to another peer.", subcommand)]
    Send(SendCommand),
    #[command(about = "Registers or looks up a service on the network.", subcommand)]
    Service(ServiceCommand),
    #[command(
        about = "Show information of swarm. Include transport table, successors, predecessor, and finger table."
    )]
    Inspect(InspectCommand),
}

#[derive(Args, Debug)]
pub(crate) struct ConfigArgs {
    #[arg(
        long,
        short = 'c',
        env,
        default_value = "~/.rings/config.yaml",
        help = "Config file location"
    )]
    pub config: String,
}

#[derive(Args, Debug)]
pub(crate) struct InitCommand {
    #[command(flatten)]
    pub(crate) delegation_args: DelegationArgs,

    #[arg(
        long,
        default_value = "~/.rings/config.yaml",
        help = "The location of config file"
    )]
    pub location: String,
}

#[derive(Args, Debug)]
pub(crate) struct NewDelegationCommand {
    #[command(flatten)]
    pub(crate) delegation_args: DelegationArgs,
}

#[derive(Args, Debug)]
pub(crate) struct RunCommand {
    #[arg(
        long,
        action = ArgAction::SetTrue,
        help = "Start the native TUN gateway from the config's gateway section for this run; the section alone never starts it (rings init writes it with enabled: false)",
        env
    )]
    pub gateway: bool,

    #[arg(
        long,
        help = "Rings node external api listen address. If not provided, use external_api_addr in config file or 127.0.0.1:50001",
        env
    )]
    pub external_api_addr: Option<String>,

    #[arg(
        long,
        help = "Rings node internal api listen port. If not provided, use internal_api_port in config file or 50000"
    )]
    pub internal_api_port: Option<u16>,

    #[arg(
        long,
        help = "API Bearer token file guarding the internal API and the external status and registry reads; the external handshake (nodeDid, answerOffer) is public. Relative paths are resolved next to the node config file",
        env
    )]
    pub api_token_path: Option<String>,

    #[arg(
        long = "api-allowed-origin",
        action = ArgAction::Append,
        help = "Exact browser origin permitted to call the authenticated API; repeat as needed",
        env,
        value_delimiter = ','
    )]
    pub api_allowed_origins: Vec<String>,

    #[arg(
        long,
        action = ArgAction::SetTrue,
        help = "Explicitly permit external_api_addr to bind a non-loopback address",
        env
    )]
    pub allow_remote_external_api: bool,

    #[arg(
        long,
        help = "ICE server list. If not provided, use ice_servers in config file or stun://stun.l.google.com:19302",
        env
    )]
    pub ice_servers: Option<String>,

    #[arg(
        long,
        help = "Stabilization interval in seconds. If not provided, use stabilize_interval in config file or 15",
        env
    )]
    pub stabilize_interval: Option<u64>,

    #[arg(
        long,
        help = "Seed document URL (file:// or http(s)://) whose peers join the managed bootstrap targets of the config's bootstrap section; the run redials each target through its HTTP endpoint whenever it stops being reachable through the overlay",
        env
    )]
    pub bootstrap_seed: Option<String>,

    #[arg(
        long,
        help = "HTTP(S) proxy URL for remote JSON-RPC endpoints (seed and HTTP handshakes); local loopback RPC always bypasses proxies",
        env
    )]
    pub remote_rpc_proxy_url: Option<String>,

    #[arg(long, help = "external ip address", env)]
    pub external_ip: Option<String>,

    #[arg(
        long,
        help = "Minimum UDP port used by native WebRTC ICE gathering. Must be paired with --webrtc-udp-port-max.",
        env
    )]
    pub webrtc_udp_port_min: Option<u16>,

    #[arg(
        long,
        help = "Maximum UDP port used by native WebRTC ICE gathering. Must be paired with --webrtc-udp-port-min.",
        env
    )]
    pub webrtc_udp_port_max: Option<u16>,

    #[arg(
        long,
        help = "Storage files location. If not provided, use data_storage.path in config file or ~/.rings/data",
        env
    )]
    pub storage_path: Option<String>,

    #[arg(
        long,
        default_value = "200000000",
        help = "Storage capacity. If not provided, use data_storage.capacity in config file or 200000000",
        env
    )]
    pub storage_capacity: Option<u32>,

    #[arg(
        long,
        value_enum,
        default_value = "production",
        env,
        help = "Inbound chunk reassembly memory profile"
    )]
    pub reassembly_profile: ReassemblyProfile,

    #[arg(
        long,
        action = ArgAction::SetTrue,
        help = "Advertise this node as an onion relay in the online-node registry",
        env
    )]
    pub advertise_onion_relay: bool,

    #[arg(
        long,
        action = ArgAction::SetTrue,
        help = concat!(
            "Publish this node as an onion exit in the application-layer exit registry; ",
            "requires --advertise-onion-relay",
        ),
        env
    )]
    pub advertise_onion_exit: bool,

    #[arg(
        long,
        value_parser = parse_onion_exit_service,
        help = "Onion exit service to serve: tcp or https. May be repeated.",
        env
    )]
    pub onion_exit_service: Vec<OnionServiceName>,

    #[arg(
        long,
        help = "Allow-list target for onion exit policy. May be repeated.",
        env
    )]
    pub onion_exit_allow_target: Vec<String>,

    #[arg(
        long,
        help = "Deny-list target for onion exit policy. May be repeated.",
        env
    )]
    pub onion_exit_deny_target: Vec<String>,

    #[arg(long, help = "Maximum onion sessions this exit will serve", env)]
    pub onion_exit_max_sessions: Option<u32>,

    #[arg(long, help = "Maximum bytes per minute this exit will serve", env)]
    pub onion_exit_max_bytes_per_minute: Option<u64>,

    #[arg(long, help = "Onion-exit registry heartbeat interval in seconds", env)]
    pub onion_exit_heartbeat_interval_secs: Option<u64>,

    #[arg(long, help = "Onion-exit registry descriptor TTL in seconds", env)]
    pub onion_exit_ttl_secs: Option<u64>,

    #[arg(
        long,
        help = "Bind a local HTTP CONNECT proxy that routes client TCP streams through onion exits, e.g. 127.0.0.1:18080",
        env
    )]
    pub onion_http_proxy_addr: Option<String>,

    #[arg(
        long,
        help = "Maximum seconds to wait for one HTTP CONNECT header",
        env
    )]
    pub onion_http_proxy_header_timeout_secs: Option<u64>,

    #[arg(
        long,
        help = "Maximum concurrent local HTTP CONNECT proxy connections",
        env
    )]
    pub onion_http_proxy_max_connections: Option<usize>,

    #[command(flatten)]
    pub(crate) config_args: ConfigArgs,
}

#[derive(Args, Debug)]
pub(crate) struct ClientArgs {
    #[arg(
        long,
        short = 'u',
        help = "rings-node endpoint url. If not provided, use endpoint_url in config file or http://127.0.0.1:50000",
        env
    )]
    endpoint_url: Option<String>,

    #[arg(
        long,
        help = "API Bearer token file of the local node's internal API. Relative paths are resolved next to the node config file",
        env
    )]
    pub(crate) api_token_path: Option<String>,

    #[command(flatten)]
    pub(crate) config_args: ConfigArgs,
}

impl ClientArgs {
    pub(crate) async fn new_client(&self) -> anyhow::Result<Client> {
        let c = config::Config::read_fs(&self.config_args.config)?;
        let endpoint_url = self.endpoint_url.as_ref().unwrap_or(&c.endpoint_url);
        let configured_path = self
            .api_token_path
            .as_deref()
            .or(c.api_token_path.as_deref());
        let token = load_api_token(&self.config_args.config, configured_path)?;
        Client::with_api_token(endpoint_url, token.into_secret())
    }
}

#[derive(Args, Debug)]
pub(crate) struct DelegationArgs {
    #[arg(
        long,
        short = 's',
        default_value = "~/.rings/delegatee_key",
        help = "The location of delegatee_key file"
    )]
    pub delegatee_key: String,

    #[arg(
        long,
        short = 'k',
        help = "Your ecdsa_key. If not provided, a random key will be used"
    )]
    pub ecdsa_key: Option<SecretKey>,

    #[arg(
        long = "key-file",
        value_name = "FILE",
        conflicts_with = "ecdsa_key",
        help = "Read your ECDSA key from a file instead of passing it on the command line"
    )]
    pub ecdsa_key_file: Option<String>,

    #[arg(
        long,
        default_value = "2592000",
        help = "The ttl of delegation file in seconds; a node using it exits 25 s before it \
                ends, when it can send nothing more"
    )]
    pub ttl: u64,
}

impl DelegationArgs {
    pub(crate) fn new_delegation_then_write_to_fs(&self) -> anyhow::Result<&std::path::Path> {
        let key = self.load_or_create_key()?;
        let ssk =
            DelegateeKey::new_with_seckey_at(&key, self.ttl.saturating_mul(1000), get_epoch_ms())?;
        let ssk_path = std::path::Path::new(&self.delegatee_key);
        write_delegatee_key_atomically(ssk_path, &ssk)?;
        println!(
            "Your delegatee_key file has saved to: {}",
            ssk_path.display()
        );

        Ok(ssk_path)
    }

    fn load_or_create_key(&self) -> anyhow::Result<SecretKey> {
        if let Some(key) = &self.ecdsa_key {
            return Ok(key.clone());
        }

        if let Some(key_file) = &self.ecdsa_key_file {
            return read_secret_key_file(key_file);
        }

        let rand_key = SecretKey::random();
        println!("Your random ecdsa key is: {}", rand_key.to_string());
        Ok(rand_key)
    }
}

fn read_secret_key_file(path: &str) -> anyhow::Result<SecretKey> {
    rings_node::native::horizon::read_delegator_secret_key(path).map_err(Into::into)
}

#[derive(Subcommand, Debug)]
#[command(rename_all = "kebab-case")]
pub(crate) enum ConnectCommand {
    #[command(about = "Connects to a node using its URL.")]
    Node(ConnectUrlCommand),
    #[command(about = "Connects to a node using its DID via DHT.")]
    Did(ConnectWithDidCommand),
    #[command(about = "Connects to a node using its seed from a URL or file.")]
    Seed(ConnectWithSeedCommand),
    #[command(
        about = "Creates a manual-handshake offer targeting a peer DID; prints the encoded offer.",
        long_about = "Creates a manual-handshake offer targeting a peer DID and prints the encoded offer.\n\n\
                      Manual handshakes take three steps: `connect offer <peer-did>` -> peer runs \
                      `connect answer <offer>` -> offerer finishes with `connect accept <answer>`."
    )]
    Offer(ConnectOfferCommand),
    #[command(
        about = "Answers a peer's offer; prints the encoded answer (or counter-offer on a simultaneous-offer tie-break).",
        long_about = "Answers a peer's offer in the three-step manual handshake (`connect offer` -> \
                      `connect answer` -> `connect accept`) and prints the encoded reply payload to stdout \
                      with a status notice on stderr.\n\n\
                      Normally the reply is an answer (`ConnectNodeReport`), which the offerer completes \
                      with `rings connect accept <answer>`.\n\n\
                      When both sides offer simultaneously and this node's pending offer prevails on the \
                      DID tie-break (glare), the printed payload is a counter-offer (`ConnectNodeSend`) \
                      instead of an answer: pass it to the peer so the peer runs \
                      `rings connect answer <counter-offer>`, then finish on this node with \
                      `rings connect accept <answer>`."
    )]
    Answer(ConnectAnswerCommand),
    #[command(
        about = "Accepts a peer's answer, completing the manual handshake (if given a counter-offer, run `connect answer` instead).",
        long_about = "Accepts a peer's answer (`ConnectNodeReport`), completing the three-step manual \
                      handshake (`connect offer` -> `connect answer` -> `connect accept`).\n\n\
                      If `connect answer` on the peer returned a counter-offer (`ConnectNodeSend`) \
                      because both nodes offered simultaneously and the peer won the DID tie-break, \
                      do not pass it to `connect accept`: run `rings connect answer <counter-offer>` \
                      on this node and return that answer to the peer's `rings connect accept`."
    )]
    Accept(ConnectAcceptCommand),
}

#[derive(Args, Debug)]
pub(crate) struct ConnectUrlCommand {
    #[command(flatten)]
    pub(crate) client_args: ClientArgs,

    pub(crate) node_url: String,

    #[arg(
        long,
        help = "Bearer token file for a remote peer that gates its handshake behind its token; not needed by default, since the external handshake (nodeDid, answerOffer) is public",
        env = "RINGS_REMOTE_API_TOKEN_FILE"
    )]
    pub(crate) remote_api_token_file: Option<String>,
}

#[derive(Args, Debug)]
pub(crate) struct ConnectWithDidCommand {
    #[command(flatten)]
    pub(crate) client_args: ClientArgs,

    pub(crate) did: String,
}

#[derive(Args, Debug)]
pub(crate) struct ConnectWithSeedCommand {
    #[command(flatten)]
    pub(crate) client_args: ClientArgs,

    pub(crate) source: String,
}

#[derive(Args, Debug)]
pub(crate) struct ConnectOfferCommand {
    #[command(flatten)]
    pub(crate) client_args: ClientArgs,

    /// DID of the peer this offer targets.
    pub(crate) did: String,
}

#[derive(Args, Debug)]
pub(crate) struct ConnectAnswerCommand {
    #[command(flatten)]
    pub(crate) client_args: ClientArgs,

    /// Encoded offer produced by the peer's `connect offer`, or `-` to read it from stdin.
    pub(crate) offer: String,
}

#[derive(Args, Debug)]
pub(crate) struct ConnectAcceptCommand {
    #[command(flatten)]
    pub(crate) client_args: ClientArgs,

    /// Encoded answer produced by the peer's `connect answer`, or `-` to read it from stdin.
    pub(crate) answer: String,
}

#[derive(Subcommand, Debug)]
#[command(rename_all = "kebab-case")]
pub(crate) enum PeerCommand {
    #[command(about = "List peers")]
    List(PeerListCommand),
    #[command(about = "Disconnect peer")]
    Disconnect(PeerDisconnectCommand),
}

#[derive(Args, Debug)]
pub(crate) struct PeerListCommand {
    #[command(flatten)]
    pub(crate) client_args: ClientArgs,
}

#[derive(Args, Debug)]
pub(crate) struct PeerDisconnectCommand {
    #[command(flatten)]
    pub(crate) client_args: ClientArgs,

    pub(crate) address: String,
}

#[derive(Subcommand, Debug)]
#[command(rename_all = "kebab-case")]
pub(crate) enum SendCommand {
    #[command(about = "Sends a namespaced message to a peer.")]
    Message(SendMessageCommand),
}

#[derive(Args, Debug)]
pub(crate) struct PubsubCommand {
    #[command(flatten)]
    pub(crate) client_args: ClientArgs,
    pub(crate) topic: String,
}

#[derive(Args, Debug)]
pub(crate) struct SendMessageCommand {
    #[command(flatten)]
    pub(crate) client_args: ClientArgs,
    pub(crate) to_did: String,
    pub(crate) namespace: String,
    pub(crate) data: String,
}

#[derive(Subcommand, Debug)]
#[command(rename_all = "kebab-case")]
pub(crate) enum ServiceCommand {
    Register(ServiceRegisterCommand),
    Lookup(ServiceLookupCommand),
}

#[derive(Args, Debug)]
pub(crate) struct ServiceRegisterCommand {
    #[command(flatten)]
    pub(crate) client_args: ClientArgs,

    pub(crate) name: String,
}

#[derive(Args, Debug)]
pub(crate) struct ServiceLookupCommand {
    #[command(flatten)]
    pub(crate) client_args: ClientArgs,

    pub(crate) name: String,
}

#[derive(Args, Debug)]
pub(crate) struct InspectCommand {
    #[command(flatten)]
    pub(crate) client_args: ClientArgs,
}