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
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
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
use super::*;

// Native WebRTC tests share process-global ICE/UDP resources and timing-sensitive
// connection callbacks; run them serially so one test's candidates or callbacks
// cannot add pressure to another test's handshake.
static NETWORK_TEST_LOCK: OnceLock<AsyncTestMutex<()>> = OnceLock::new();

pub(super) fn onion_policy(
    allowed_targets: &[&str],
    denied_targets: &[&str],
) -> Result<OnionExitPolicy> {
    OnionExitPolicy::from_target_strings(
        allowed_targets
            .iter()
            .map(|target| (*target).to_string())
            .collect(),
        denied_targets
            .iter()
            .map(|target| (*target).to_string())
            .collect(),
    )
}
pub(super) struct SwarmCallbackInstance {
    inbound: Mutex<Vec<Message>>,
    inbound_notify: Notify,
    connected_notify: Notify,
}

pub(super) struct StaticRegistration {
    publisher: crate::registration::DhtRegistrationPublisher,
    value: Encoded,
}

impl StaticRegistration {
    pub(super) fn new(topic: &str, value: Encoded) -> Self {
        Self {
            publisher: crate::registration::DhtRegistrationPublisher::new(topic),
            value,
        }
    }
}

#[async_trait]
impl RegistrationTask for StaticRegistration {
    fn name(&self) -> &'static str {
        "static-test"
    }

    fn interval(&self) -> Duration {
        Duration::from_secs(60)
    }

    async fn register_once(&self, context: &RegistrationContext<'_>) -> Result<()> {
        self.publisher.publish(context, self.value.clone()).await
    }
}

#[async_trait]
impl SwarmCallback for SwarmCallbackInstance {
    async fn on_inbound(
        &self,
        payload: &MessagePayload,
    ) -> std::result::Result<(), rings_core::error::CallbackError> {
        let msg: Message = payload.transaction.data().map_err(Box::new)?;
        {
            let mut inbound = self.inbound.lock().unwrap();
            inbound.push(msg);
        }
        self.inbound_notify.notify_one();

        Ok(())
    }

    async fn on_event(
        &self,
        event: &SwarmEvent,
    ) -> std::result::Result<(), rings_core::error::CallbackError> {
        if let SwarmEvent::ConnectionStateChange {
            state: WebrtcConnectionState::Connected,
            ..
        } = event
        {
            self.connected_notify.notify_one();
        }

        Ok(())
    }
}

pub(super) fn test_callback() -> Arc<SwarmCallbackInstance> {
    Arc::new(SwarmCallbackInstance {
        inbound: Mutex::new(Vec::new()),
        inbound_notify: Notify::new(),
        connected_notify: Notify::new(),
    })
}

pub(super) async fn network_test_guard() -> tokio::sync::MutexGuard<'static, ()> {
    NETWORK_TEST_LOCK
        .get_or_init(|| AsyncTestMutex::new(()))
        .lock()
        .await
}

pub(super) async fn prepare_processor_with_identity_key(identity_key: SecretKey) -> Processor {
    prepare_processor_with_identity_key_and_network(identity_key, 0).await
}

pub(super) async fn prepare_processor_with_identity_key_and_network(
    identity_key: SecretKey,
    network_id: u32,
) -> Processor {
    prepare_processor_with_identity_key_network_and_virtual_nodes(identity_key, network_id, {
        rings_core::dht::DEFAULT_STORAGE_VIRTUAL_POSITIONS_PER_OWNER
    })
    .await
}

pub(super) async fn prepare_processor_with_identity_key_network_and_virtual_nodes(
    identity_key: SecretKey,
    network_id: u32,
    dht_virtual_nodes: u16,
) -> Processor {
    let session_sk = SessionSk::new_with_seckey(&identity_key).unwrap();
    let config = ProcessorConfig::new(
        network_id,
        "stun://stun.l.google.com:19302".to_string(),
        session_sk,
        3,
    )
    .dht_virtual_nodes(dht_virtual_nodes);
    let storage = Box::new(MemStorage::new());

    ProcessorBuilder::from_config(&config)
        .unwrap()
        .storage(storage)
        .dht_finger_table_size(8)
        .build()
        .unwrap()
}

pub(super) async fn prepare_online_node_registry_pair(
    network_id: u32,
) -> Result<(Processor, Processor)> {
    let registry_key = entry::Entry::gen_did(ONLINE_NODES_TOPIC)?;
    let placement_keys = registry_key.rotate_affine(DATA_REDUNDANT)?;
    // Keep the fetch path deterministic: storage_fetch returns the first
    // placement hit, so the publisher must not own a stale replica on any
    // registry placement before it asks the owner for the merged entry.
    for _ in 0..512 {
        let first_key = SecretKey::random();
        let second_key = SecretKey::random();
        let first_did = first_key.address().into();
        let second_did = second_key.address().into();
        let first_owns_all = owns_all_placements(first_did, second_did, placement_keys.as_slice());
        let second_owns_all = owns_all_placements(second_did, first_did, placement_keys.as_slice());
        let Some((publisher_key, owner_key)) = (match (first_owns_all, second_owns_all) {
            (true, false) => Some((second_key, first_key)),
            (false, true) => Some((first_key, second_key)),
            _ => None,
        }) else {
            continue;
        };
        let publisher = prepare_processor_with_identity_key_network_and_virtual_nodes(
            publisher_key,
            network_id,
            0,
        )
        .await;
        let owner =
            prepare_processor_with_identity_key_network_and_virtual_nodes(owner_key, network_id, 0)
                .await;
        return Ok((publisher, owner));
    }
    Err(Error::InvalidConfig(
        "could not generate an online-node registry owner covering every placement".to_string(),
    ))
}

pub(super) fn owns_all_placements(local: Did, successor: Did, placements: &[Did]) -> bool {
    placements
        .iter()
        .all(|placement| *placement - local <= successor - local)
}

pub(super) async fn prepare_processor_with_network(network_id: u32) -> Processor {
    prepare_processor_with_network_and_virtual_nodes(network_id, 0).await
}

pub(super) async fn prepare_processor_with_network_and_virtual_nodes(
    network_id: u32,
    dht_virtual_nodes: u16,
) -> Processor {
    let key = SecretKey::random();
    let session_sk = SessionSk::new_with_seckey(&key).unwrap();
    let serialized = ProcessorConfigSerialized::new(
        network_id,
        "stun://stun.l.google.com:19302".to_string(),
        session_sk.dump().unwrap(),
        3,
    )
    .dht_virtual_nodes(dht_virtual_nodes);
    let config = ProcessorConfig::try_from(serialized).unwrap();
    let storage = Box::new(MemStorage::new());

    ProcessorBuilder::from_config(&config)
        .unwrap()
        .storage(storage)
        .dht_finger_table_size(8)
        .build()
        .unwrap()
}

pub(super) fn owns_entry_placement(processor: &Processor, placement_key: Did) -> Result<bool> {
    match processor.swarm.dht().find_successor(placement_key)? {
        PeerRingAction::Some(_) => Ok(true),
        PeerRingAction::RemoteAction(_, PeerRingRemoteAction::FindSuccessor(_)) => Ok(false),
        action => Err(Error::InvalidConfig(format!(
            "unexpected registry owner lookup action: {action:?}"
        ))),
    }
}

pub(super) async fn prepare_processor_with_online_node_type(
    node_type: OnlineNodeType,
) -> Processor {
    let key = SecretKey::random();
    let session_sk = SessionSk::new_with_seckey(&key).unwrap();
    let config = ProcessorConfig::new(
        0,
        "stun://stun.l.google.com:19302".to_string(),
        session_sk,
        3,
    );
    let storage = Box::new(MemStorage::new());

    ProcessorBuilder::from_config(&config)
        .unwrap()
        .storage(storage)
        .online_node_type(node_type)
        .dht_finger_table_size(8)
        .build()
        .unwrap()
}

pub(super) fn onion_exit_descriptor_for_processor(
    processor: &Processor,
    service: &str,
    now_ms: u128,
) -> Result<OnionExitDescriptor> {
    onion_exit_descriptor_for_processor_with_policy(processor, service, now_ms, {
        let mut policy = onion_policy(&["127.0.0.1:8080", "example.com:443"], &[])?;
        policy.max_circuits = 8;
        policy.max_streams_per_circuit = 2;
        policy.max_bytes_per_minute = 4096;
        policy
    })
}

pub(super) fn onion_exit_descriptor_for_processor_with_policy(
    processor: &Processor,
    service: &str,
    now_ms: u128,
    policy: OnionExitPolicy,
) -> Result<OnionExitDescriptor> {
    onion_exit_descriptor_for_processor_with_service(
        processor,
        OnionExitService::new(
            service,
            OnionExitService::reserved_transport(service).unwrap_or(OnionExitTransport::Tcp),
        )?,
        now_ms,
        policy,
    )
}

pub(super) fn onion_exit_descriptor_for_processor_with_service(
    processor: &Processor,
    service: OnionExitService,
    now_ms: u128,
    policy: OnionExitPolicy,
) -> Result<OnionExitDescriptor> {
    onion_exit_descriptor_for_processor_with_node_type_service(
        processor,
        default_online_node_type(),
        service,
        now_ms,
        policy,
    )
}

pub(super) fn onion_exit_descriptor_for_processor_with_node_type_service(
    processor: &Processor,
    node_type: OnlineNodeType,
    service: OnionExitService,
    now_ms: u128,
    policy: OnionExitPolicy,
) -> Result<OnionExitDescriptor> {
    OnionExitDescriptor::new_signed(
        OnionExitDescriptorBody {
            did: processor.did(),
            public_key: processor
                .swarm
                .account_verification_pubkey()
                .map_err(Error::CoreError)?,
            session_public_key: processor.session_sk.session_public_key(),
            node_type,
            network_id: processor.swarm.network_id(),
            service,
            policy,
            started_at_ms: now_ms,
            heartbeat_at_ms: now_ms,
            expires_at_ms: now_ms + 90_000,
            version: crate::util::build_version(),
        },
        &processor.session_sk,
    )
    .map_err(Error::CoreError)
}

pub(super) fn online_relay_descriptor_for_processor(
    processor: &Processor,
    now_ms: u128,
) -> Result<OnlineNodeDescriptor> {
    let mut capabilities = OnlineNodeRegistration::default_capabilities();
    capabilities.push(ONION_RELAY_CAPABILITY.to_string());
    OnlineNodeDescriptor::new_signed(
        OnlineNodeDescriptorBody {
            did: processor.did(),
            public_key: processor
                .swarm
                .account_verification_pubkey()
                .map_err(Error::CoreError)?,
            session_public_key: processor.session_sk.session_public_key(),
            node_type: default_online_node_type(),
            network_id: processor.swarm.network_id(),
            storage_redundancy: processor.swarm.storage_redundancy(),
            dht_virtual_nodes: processor.swarm.dht_virtual_nodes(),
            capabilities,
            endpoint_hint: None,
            started_at_ms: now_ms,
            heartbeat_at_ms: now_ms,
            expires_at_ms: now_ms + 90_000,
            version: crate::util::build_version(),
        },
        &processor.session_sk,
    )
    .map_err(Error::CoreError)
}

pub(super) fn mismatched_storage_redundancy(value: u16) -> u16 {
    if value == u16::MAX {
        value.saturating_sub(1)
    } else {
        value.saturating_add(1)
    }
}

pub(super) async fn prepare_measured_processor() -> Processor {
    let key = SecretKey::random();
    let session_sk = SessionSk::new_with_seckey(&key).unwrap();
    let config = ProcessorConfig::new(
        0,
        "stun://stun.l.google.com:19302".to_string(),
        session_sk,
        3,
    );
    let storage = Box::new(MemStorage::new());
    let measure = PeriodicMeasure::new(Box::new(MemStorage::new()))
        .await
        .unwrap();

    ProcessorBuilder::from_config(&config)
        .unwrap()
        .storage(storage)
        .measure(measure)
        .dht_finger_table_size(8)
        .build()
        .unwrap()
}

pub(super) async fn connect_processors(
    p1: &Processor,
    p2: &Processor,
    callback1: &SwarmCallbackInstance,
    callback2: &SwarmCallbackInstance,
) {
    let offer = p1.swarm.create_offer(p2.did()).await.unwrap();
    let answer = p2.swarm.answer_offer(offer).await.unwrap();
    p1.swarm.accept_answer(answer).await.unwrap();
    wait_processors_connected(p1, p2, callback1, callback2).await;
}

pub(super) async fn wait_processors_connected(
    p1: &Processor,
    p2: &Processor,
    callback1: &SwarmCallbackInstance,
    callback2: &SwarmCallbackInstance,
) {
    let deadline = Instant::now() + Duration::from_secs(5);
    loop {
        if processor_has_connected_peer(p1, p2.did()) && processor_has_connected_peer(p2, p1.did())
        {
            return;
        }

        let remaining = deadline
            .checked_duration_since(Instant::now())
            .expect("processors did not connect");
        tokio::time::timeout(remaining, async {
            tokio::select! {
                _ = callback1.connected_notify.notified() => {}
                _ = callback2.connected_notify.notified() => {}
            }
        })
        .await
        .expect("processors did not connect");
    }
}

pub(super) fn processor_has_connected_peer(processor: &Processor, peer: Did) -> bool {
    let peer = peer.to_string();
    processor
        .swarm
        .peers()
        .into_iter()
        .any(|conn| conn.did == peer && conn.state == "Connected")
}

pub(super) async fn wait_for_mutual_dht_topology(
    processor: &Processor,
    other: &Processor,
) -> Result<()> {
    let deadline = Instant::now() + Duration::from_secs(10);
    loop {
        let inspect = processor.swarm.inspect().await;
        let other_inspect = other.swarm.inspect().await;
        let did = processor.did().to_string();
        let other_did = other.did().to_string();
        let processor_sees_other = inspect
            .dht
            .successors
            .iter()
            .any(|successor| successor == &other_did)
            && inspect.dht.predecessor.as_ref() == Some(&other_did);
        let other_sees_processor = other_inspect
            .dht
            .successors
            .iter()
            .any(|successor| successor == &did)
            && other_inspect.dht.predecessor.as_ref() == Some(&did);
        if processor_sees_other && other_sees_processor {
            return Ok(());
        }

        let stabilizer = processor.swarm.stabilizer();
        let other_stabilizer = other.swarm.stabilizer();
        futures::try_join!(stabilizer.stabilize(), other_stabilizer.stabilize(),)
            .map_err(Error::CoreError)?;
        let remaining = deadline
            .checked_duration_since(Instant::now())
            .unwrap_or_else(|| {
                panic!(
                    "mutual DHT topology did not converge: processor={:?}, other={:?}",
                    inspect.dht, other_inspect.dht
                )
            });
        tokio::time::timeout(remaining, tokio::time::sleep(Duration::from_millis(20)))
            .await
            .unwrap_or_else(|_| {
                panic!(
                    "mutual DHT topology did not converge: processor={:?}, other={:?}",
                    inspect.dht, other_inspect.dht
                )
            });
    }
}

pub(super) async fn wait_for_online_node_dids(
    processor: &Processor,
    expected: &BTreeSet<Did>,
    context: &str,
) -> Result<Vec<OnlineNodeDescriptor>> {
    let deadline = Instant::now() + Duration::from_secs(60);
    loop {
        let nodes = processor.lookup_online_nodes(false).await?;
        let observed = nodes
            .iter()
            .map(|descriptor| descriptor.did)
            .collect::<BTreeSet<_>>();
        if expected.is_subset(&observed) {
            return Ok(nodes);
        }

        let remaining = deadline
                .checked_duration_since(Instant::now())
                .unwrap_or_else(|| {
                    panic!(
                        "online node registry did not converge during {context}: expected {expected:?}, observed {observed:?}",
                    )
                });
        tokio::time::timeout(remaining, tokio::time::sleep(Duration::from_millis(20)))
                .await
                .unwrap_or_else(|_| {
                    panic!(
                        "online node registry did not converge during {context}: expected {expected:?}, observed {observed:?}",
                    )
                });
    }
}

pub(super) async fn wait_for_online_node_dids_in_storage(
    processor: &Processor,
    placement_keys: &[Did],
    expected: &BTreeSet<Did>,
    context: &str,
) -> Result<()> {
    let deadline = Instant::now() + Duration::from_secs(60);
    loop {
        let mut observed_by_placement = BTreeMap::new();
        for placement_key in placement_keys {
            let observed = match processor
                .swarm
                .dht()
                .storage
                .get(&placement_key.to_string())
                .await
                .map_err(Error::Storage)?
            {
                Some(entry) => Processor::online_node_descriptors_from_entry(&entry)
                    .into_iter()
                    .map(|descriptor| descriptor.did)
                    .collect::<BTreeSet<_>>(),
                None => BTreeSet::new(),
            };
            observed_by_placement.insert(*placement_key, observed);
        }

        if observed_by_placement
            .values()
            .all(|observed| expected.is_subset(observed))
        {
            return Ok(());
        }

        let remaining = deadline
                .checked_duration_since(Instant::now())
                .unwrap_or_else(|| {
                    panic!(
                        "online node registry storage did not converge during {context}: expected {expected:?}, observed {observed_by_placement:?}",
                    )
                });
        tokio::time::timeout(remaining, tokio::time::sleep(Duration::from_millis(20)))
                .await
                .unwrap_or_else(|_| {
                    panic!(
                        "online node registry storage did not converge during {context}: expected {expected:?}, observed {observed_by_placement:?}",
                    )
                });
    }
}

pub(super) async fn wait_for_peer_measurement(
    processor: &Processor,
    did: Did,
    predicate: impl Fn(&PeerMeasurement) -> bool,
) -> PeerMeasurement {
    let deadline = Instant::now() + Duration::from_secs(5);
    loop {
        if let Some(measurement) = processor.peer_measurement(did).await {
            if predicate(&measurement) {
                return measurement;
            }
        }

        let remaining = deadline
            .checked_duration_since(Instant::now())
            .expect("measurement was not updated");
        tokio::time::timeout(remaining, tokio::time::sleep(Duration::from_millis(20)))
            .await
            .expect("measurement was not updated");
    }
}

pub(super) async fn wait_for_inbound_message(
    callback: &SwarmCallbackInstance,
    predicate: impl Fn(&Message) -> bool,
) -> Message {
    let deadline = Instant::now() + Duration::from_secs(5);
    loop {
        {
            let inbound = callback.inbound.lock().unwrap();
            if let Some(msg) = inbound.iter().find(|msg| predicate(msg)).cloned() {
                return msg;
            }
        }

        let remaining = deadline
            .checked_duration_since(Instant::now())
            .expect("inbound message was not delivered");
        tokio::time::timeout(remaining, callback.inbound_notify.notified())
            .await
            .expect("inbound message was not delivered");
    }
}

pub(super) async fn wait_for_e2e_stream_frames(
    callback: &SwarmCallbackInstance,
    stream_id: e2e::E2eStreamId,
) -> Vec<E2eStreamFrame> {
    let deadline = Instant::now() + Duration::from_secs(5);
    loop {
        {
            let inbound = callback.inbound.lock().unwrap();
            let frames = inbound
                .iter()
                .filter_map(|msg| match msg {
                    Message::E2eStreamFrame(frame) if frame.stream_id == stream_id => {
                        Some(frame.clone())
                    }
                    _ => None,
                })
                .collect::<Vec<_>>();
            if frames.iter().any(|frame| frame.is_final) {
                return frames;
            }
        }

        let remaining = deadline
            .checked_duration_since(Instant::now())
            .expect("E2E stream final frame was not delivered");
        tokio::time::timeout(remaining, callback.inbound_notify.notified())
            .await
            .expect("E2E stream final frame was not delivered");
    }
}