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
use bytes::Bytes;
use rings_core::message::MessageSigner;

use super::common::*;
use super::*;
use crate::descriptor::registry_lease;
use crate::descriptor::RegistryElement;
use crate::registration::DhtRegistrationPublisher;
use crate::registration::LeaseTerms;
use crate::tests::exit_descriptor::ExitDescriptorFixture;

struct StoppedRegistration;

struct CountingRegistration(std::sync::Arc<std::sync::atomic::AtomicUsize>);

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

    fn interval(&self) -> Duration {
        Duration::from_millis(20)
    }

    async fn register_once(&self, _context: &RegistrationContext<'_>) -> Result<()> {
        Err(Error::RegistrationStopped)
    }
}

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

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

    async fn register_once(&self, _context: &RegistrationContext<'_>) -> Result<()> {
        self.0.fetch_add(1, std::sync::atomic::Ordering::AcqRel);
        Ok(())
    }
}

#[tokio::test]
async fn test_registration_daemon_treats_expected_stop_as_terminal() {
    let processor = prepare_processor().await;
    let task = StoppedRegistration;

    tokio::time::timeout(
        Duration::from_millis(100),
        // A task outside the processor's registrations: an index with no readiness latch.
        processor.registration_task_daemon_with(
            &task,
            usize::MAX,
            StopToken::never(),
            StopToken::never(),
        ),
    )
    .await
    .expect("RegistrationStopped should terminate the registration daemon");
}

#[tokio::test]
async fn test_registration_daemon_stops_after_sibling_maintenance_exits() {
    let processor = prepare_processor().await;
    let calls = std::sync::Arc::new(std::sync::atomic::AtomicUsize::new(0));
    let task = CountingRegistration(std::sync::Arc::clone(&calls));
    let sibling_stop_source = StopSource::new();
    let daemon = processor.registration_task_daemon_with(
        &task,
        usize::MAX,
        StopToken::never(),
        sibling_stop_source.token(),
    );
    tokio::pin!(daemon);
    while calls.load(std::sync::atomic::Ordering::Acquire) == 0 {
        tokio::select! {
            () = tokio::task::yield_now() => {},
            () = &mut daemon => panic!("registration daemon exited before sibling stop"),
        }
    }

    sibling_stop_source.request_stop();
    tokio::time::timeout(Duration::from_millis(200), &mut daemon)
        .await
        .expect("sibling exit should cooperatively stop registration daemon");
    assert_eq!(calls.load(std::sync::atomic::Ordering::Acquire), 1);
}

#[tokio::test]
async fn test_online_node_descriptor_publishes_and_lists_signed_self() -> Result<()> {
    let processor = prepare_processor().await;
    let published = processor.publish_online_node_descriptor().await?;
    let nodes = processor.lookup_online_nodes(false).await?;

    assert_eq!(nodes.len(), 1);
    assert_eq!(nodes[0].did, processor.did());
    assert_eq!(nodes[0].did, published.did);
    assert_eq!(nodes[0].network_id, processor.swarm.network_id());
    assert_eq!(
        nodes[0].storage_redundancy,
        processor.swarm.storage_redundancy()
    );
    assert_eq!(
        nodes[0].dht_virtual_nodes,
        processor.swarm.dht_virtual_nodes()
    );
    assert!(nodes[0].verify_signature(processor.swarm.network_id()));
    assert!(!nodes[0].is_expired_at(get_epoch_ms()));
    Ok(())
}

/// The signed bytes of `descriptors`, which a reader's heard time does not change.
fn elements<D: RegistryElement>(descriptors: &[D]) -> Result<Vec<Bytes>> {
    descriptors
        .iter()
        .map(|descriptor| descriptor.to_element().map_err(Error::CoreError))
        .collect()
}

/// Heartbeat law (#918): a second heartbeat re-appends the lease's bytes, so the registry holds
/// one element, written without a remove, whose dot the heartbeat raised.
#[tokio::test]
async fn test_online_node_heartbeat_reappends_its_lease_without_a_remove() -> Result<()> {
    let processor = prepare_processor().await;
    let first = processor.publish_online_node_descriptor().await?;
    let second = processor.publish_online_node_descriptor().await?;
    let entry_key = entry::Entry::gen_did(ONLINE_NODES_TOPIC)?;
    processor.storage_fetch(entry_key).await?;
    let entry = processor
        .storage_check_cache(entry_key)
        .await
        .expect("online node registry entry should be cached after publish");
    let stored = OnlineNodeRegistration::descriptors_from_entry(&entry);
    let nodes = processor.lookup_online_nodes(false).await?;

    assert_eq!(
        elements(std::slice::from_ref(&first))?,
        elements(std::slice::from_ref(&second))?
    );
    assert_eq!(elements(&stored)?, elements(std::slice::from_ref(&second))?);
    assert!(entry.crdt.tombstones.is_empty());
    assert_eq!(nodes.len(), 1);
    assert!(nodes[0].heartbeat_at_ms >= second.heartbeat_at_ms);
    Ok(())
}

/// Two concurrent heartbeats serialize on the held lease and append the same bytes.
#[tokio::test]
async fn test_online_node_concurrent_publish_keeps_one_self_record() -> Result<()> {
    let processor = prepare_processor().await;
    let processor_clone = processor.clone();

    let (first, second) = futures::try_join!(
        processor.publish_online_node_descriptor(),
        processor_clone.publish_online_node_descriptor(),
    )?;
    let entry_key = entry::Entry::gen_did(ONLINE_NODES_TOPIC)?;
    processor.storage_fetch(entry_key).await?;
    let entry = processor
        .storage_check_cache(entry_key)
        .await
        .expect("online node registry entry should be cached after publish");
    let stored = OnlineNodeRegistration::descriptors_from_entry(&entry);
    let nodes = processor.lookup_online_nodes(false).await?;

    assert_eq!(
        elements(std::slice::from_ref(&first))?,
        elements(std::slice::from_ref(&second))?
    );
    assert_eq!(stored.len(), 1);
    assert!(entry.crdt.tombstones.is_empty());
    assert_eq!(nodes.len(), 1);
    assert!(nodes[0].heartbeat_at_ms >= first.heartbeat_at_ms.max(second.heartbeat_at_ms));
    Ok(())
}

/// A heartbeat removes nothing it observes: an older lease of its own and the descriptors of
/// other registrants stay, and the reader lists the newest lease per DID.
///
/// Even when the fixture `Overwrite` (`storage_store`) and the heartbeat `Extend`
/// (`publish_online_node_descriptor`) execute in the same millisecond (#1067, #1075), the HLC
/// counter stamps the `Extend` strictly above the `Overwrite`'s reset floor, so the appended
/// lease is never dropped below the floor.
#[tokio::test]
async fn test_online_node_heartbeat_removes_nothing_and_the_newest_lease_wins() -> Result<()> {
    let processor = prepare_processor().await;
    let other = prepare_processor().await;
    let now_ms = get_epoch_ms();
    let self_older = OnlineNodeRegistration::new(
        Duration::from_secs(default_online_node_heartbeat_interval_secs()),
        Duration::from_secs(default_online_node_ttl_secs()),
        default_online_node_type(),
        Some("https://old.example".to_string()),
        None,
    )
    .descriptor_at(&processor.registration_context(), LeaseTerms {
        fresh_for_ms: 90_000,
        expires_at_ms: now_ms.saturating_sub(15_000) + 90_000,
    })?;
    assert!(self_older.verify_signature(processor.swarm.network_id()));
    let other_descriptor = other.online_node_descriptor_at(now_ms)?;
    assert!(other_descriptor.verify_signature(processor.swarm.network_id()));
    let expired_other = other.online_node_descriptor_at(now_ms.saturating_sub(120_000))?;
    assert!(expired_other.verify_signature(processor.swarm.network_id()));
    assert!(expired_other.is_expired_at(now_ms));

    processor
        .storage_store(Processor::registry_entry(ONLINE_NODES_TOPIC, vec![
            self_older.clone(),
            other_descriptor.clone(),
            expired_other,
        ])?)
        .await?;
    let entry_key = entry::Entry::gen_did(ONLINE_NODES_TOPIC)?;
    processor.storage_fetch(entry_key).await?;
    let fixture_register = processor
        .storage_check_cache(entry_key)
        .await
        .expect("online node registry fixture should be cached after store")
        .crdt
        .register;
    let reset_floor = fixture_register.expect("overwrite sets a reset floor");

    let published = processor.publish_online_node_descriptor().await?;
    assert!(published.verify_signature(processor.swarm.network_id()));
    processor.storage_fetch(entry_key).await?;
    let entry = processor
        .storage_check_cache(entry_key)
        .await
        .expect("online node registry entry should be cached after publish");
    let stored = OnlineNodeRegistration::descriptors_from_entry(&entry);
    let mut nodes = processor.lookup_online_nodes(false).await?;
    nodes.sort_by_key(|descriptor| descriptor.did == processor.did());

    assert_eq!(stored.len(), 4);
    assert_eq!(entry.crdt.register, fixture_register);
    assert!(entry.crdt.tombstones.is_empty());
    let published_element = published.to_element().map_err(Error::CoreError)?;
    let published_dot = entry
        .data
        .iter()
        .zip(entry.crdt.dots.iter())
        .find_map(|(element, dot)| (element == &published_element).then_some(dot.version))
        .expect("published lease is stored with a dot");
    assert!(
        published_dot > reset_floor,
        "heartbeat Extend dot {published_dot:?} must strictly follow Overwrite floor {reset_floor:?}"
    );
    assert_eq!(elements(&nodes)?, elements(&[other_descriptor, published])?);
    assert_eq!(nodes[1].endpoint_hint, None);
    Ok(())
}

/// Deterministic same-millisecond boundary for #1067 / #1075: when `storage_store` (`Overwrite`)
/// and `publish_online_node_descriptor` (`Extend`) execute within the same millisecond `t0`, the
/// HLC counter stamps the `Extend` strictly after the `Overwrite`'s reset floor, all 3 carrier
/// elements (`self_older`, `peer_descriptor`, and the new `self` lease) remain stored
/// (`stored.len() == 3`), and `lookup_online_nodes(false)` returns the 2 live descriptors with
/// the newer `self` lease winning over `self_older`.
#[tokio::test]
async fn test_online_node_same_millisecond_overwrite_and_heartbeat_keeps_all_elements() -> Result<()>
{
    let processor = prepare_processor().await;
    let peer = prepare_processor().await;
    let entry_key = entry::Entry::gen_did(ONLINE_NODES_TOPIC)?;
    let now_ms = get_epoch_ms();
    let self_older = OnlineNodeRegistration::new(
        Duration::from_secs(default_online_node_heartbeat_interval_secs()),
        Duration::from_secs(default_online_node_ttl_secs()),
        default_online_node_type(),
        Some("https://old.example".to_string()),
        None,
    )
    .descriptor_at(&processor.registration_context(), LeaseTerms {
        fresh_for_ms: 90_000,
        expires_at_ms: now_ms.saturating_sub(15_000) + 90_000,
    })?;
    assert!(self_older.verify_signature(processor.swarm.network_id()));
    let peer_descriptor = peer.online_node_descriptor_at(now_ms)?;
    assert!(peer_descriptor.verify_signature(processor.swarm.network_id()));

    // Pre-stamp the Overwrite at `t0 = now_ms + 50` (within clock skew tolerance `σ = 3000 ms`)
    // so `PeerRing::stamp_operation` raises the node's HLC floor to `(t0, 0)`. When
    // `publish_online_node_descriptor()` then runs at wall-clock `≤ t0`, `stamp_operation` sees
    // the floor at `t0` and deterministically stamps the Extend at `(t0, 1)`, reproducing the
    // exact same-millisecond Overwrite-then-Extend ordering boundary of #1067 / #1075 without
    // depending on wall-clock speed.
    let t0 = now_ms + 50;
    let stamped_overwrite =
        rings_core::dht::entry::EntryOperation::Overwrite(Processor::registry_entry(
            ONLINE_NODES_TOPIC,
            vec![self_older.clone(), peer_descriptor.clone()],
        )?)
        .stamped(t0, processor.did())
        .map_err(Error::EntryError)?;
    let reset_floor = stamped_overwrite
        .entry()
        .crdt
        .register
        .expect("stamped overwrite carries a reset floor");
    assert_eq!((reset_floor.logical_time_ms, reset_floor.counter), (t0, 0));

    processor
        .storage_store(stamped_overwrite.entry().clone())
        .await?;
    let published = processor.publish_online_node_descriptor().await?;
    assert!(published.verify_signature(processor.swarm.network_id()));
    processor.storage_fetch(entry_key).await?;
    let entry = processor
        .storage_check_cache(entry_key)
        .await
        .expect("online node registry entry should be cached after same-ms publish");
    let published_element = published.to_element().map_err(Error::CoreError)?;
    let published_dot = entry
        .data
        .iter()
        .zip(entry.crdt.dots.iter())
        .find_map(|(element, dot)| (element == &published_element).then_some(dot.version))
        .expect("published lease is stored with a dot");
    assert_eq!(published_dot.logical_time_ms, reset_floor.logical_time_ms);
    assert_eq!(published_dot.counter, reset_floor.counter + 1);
    assert!(published_dot > reset_floor);

    let stored = OnlineNodeRegistration::descriptors_from_entry(&entry);
    assert_eq!(stored.len(), 3);
    assert!(elements(&stored)?.contains(&self_older.to_element().map_err(Error::CoreError)?));
    assert_eq!(entry.crdt.register, Some(reset_floor));
    assert!(entry.crdt.tombstones.is_empty());

    let mut nodes = processor.lookup_online_nodes(false).await?;
    nodes.sort_by_key(|descriptor| descriptor.did == processor.did());
    assert_eq!(nodes.len(), 2);
    assert_eq!(elements(&nodes)?, elements(&[peer_descriptor, published])?);
    assert_eq!(nodes[1].endpoint_hint, None);
    Ok(())
}

/// The exit registry follows the same law: the published lease outranks this exit's older one
/// for the service it offers, and nothing is removed.
#[tokio::test]
async fn test_onion_exit_newest_lease_outranks_stale_self_records() -> Result<()> {
    let processor = prepare_processor().await;
    let other = prepare_processor().await;
    let now_ms = get_epoch_ms();
    let policy = bounded_policy(&["example.com:443"], &[])?;
    let stale_https = ExitDescriptorFixture::live(
        &processor,
        OnionServiceName::https(),
        policy.clone(),
        now_ms.saturating_sub(20_000),
    )
    .sign()?;
    let other_https =
        ExitDescriptorFixture::live(&other, OnionServiceName::https(), policy.clone(), now_ms)
            .sign()?;

    processor
        .storage_store(Processor::registry_entry(ONION_EXITS_TOPIC, vec![
            stale_https,
            other_https.clone(),
        ])?)
        .await?;

    let registration = OnionExitRegistration::new(
        Duration::from_secs(30),
        Duration::from_secs(90),
        default_online_node_type(),
        OnionExitOffer::new(vec![OnionServiceName::https()], policy)?,
        processor.onion_process_epoch(),
    );
    let published = registration
        .publish_descriptors(&processor.registration_context())
        .await?;
    assert!(published
        .iter()
        .all(|descriptor| descriptor.process_epoch == processor.onion_process_epoch.get()));
    let entry_key = entry::Entry::gen_did(ONION_EXITS_TOPIC)?;
    processor.storage_fetch(entry_key).await?;
    let entry = processor
        .storage_check_cache(entry_key)
        .await
        .expect("onion exit registry entry should be cached after publish");
    let mut exits = processor.lookup_onion_exits("https", false).await?;
    exits.sort_by_key(|descriptor| descriptor.did == processor.did());

    assert_eq!(
        OnionExitRegistration::descriptors_from_entry(&entry).len(),
        3
    );
    assert!(entry.crdt.tombstones.is_empty());
    let mut expected = vec![other_https];
    expected.extend(published);
    assert_eq!(elements(&exits)?, elements(&expected)?);
    Ok(())
}

/// A lease is renewed only once fewer than two heartbeats remain in it, or when a signed field
/// changes; until then every heartbeat appends the same bytes.
#[tokio::test]
async fn test_registry_lease_renews_near_its_end_or_on_a_change() -> Result<()> {
    let processor = prepare_processor().await;
    let context = processor.registration_context();
    let interval = Duration::from_secs(30);
    let publisher = DhtRegistrationPublisher::<[OnlineNodeDescriptor; 1]>::new(
        ONLINE_NODES_TOPIC,
        interval,
        Duration::from_secs(90),
    );
    let onion_relay = OnionProcessEpochCell::new(processor.onion_process_epoch.get());
    let registration = OnlineNodeRegistration::new(
        interval,
        Duration::from_secs(90),
        default_online_node_type(),
        None,
        Some(onion_relay.clone()),
    );
    let sign = |terms: LeaseTerms| {
        registration
            .descriptor_at(&context, terms)
            .map(|descriptor| [descriptor])
    };
    let t0 = get_epoch_ms();
    let lease = registry_lease().as_millis();
    let margin = 2 * interval.as_millis();

    let [first] = publisher.publish_lease(&context, t0, sign).await?;
    assert!(first.verify_signature(processor.swarm.network_id()));
    assert_eq!(first.expires_at_ms, t0 + lease);
    let [kept] = publisher
        .publish_lease(&context, t0 + lease - margin - 1, sign)
        .await?;
    assert!(kept.verify_signature(processor.swarm.network_id()));
    assert_eq!(elements(&[kept])?, elements(std::slice::from_ref(&first))?);
    let [renewed] = publisher
        .publish_lease(&context, t0 + lease - margin, sign)
        .await?;
    assert!(renewed.verify_signature(processor.swarm.network_id()));
    assert_eq!(renewed.expires_at_ms, t0 + 2 * lease - margin);

    let next_epoch = OnionProcessEpoch::random();
    onion_relay.renew(next_epoch);
    let [changed] = publisher.publish_lease(&context, t0 + lease, sign).await?;
    assert!(changed.verify_signature(processor.swarm.network_id()));
    assert_eq!(changed.capabilities.onion_relay, Some(next_epoch));
    assert_eq!(changed.expires_at_ms, t0 + 2 * lease);
    Ok(())
}

#[tokio::test]
async fn test_online_node_lookup_filters_expired_descriptors_by_default() -> Result<()> {
    let processor = prepare_processor().await;
    let expired_processor = prepare_processor().await;
    let now_ms = get_epoch_ms();
    let live = processor.online_node_descriptor_at(now_ms)?;
    let expired_key = expired_processor.delegatee_key();
    let expired = OnlineNodeDescriptor::new_signed(
        OnlineNodeDescriptorBody {
            did: expired_processor.did(),
            public_key: expired_processor
                .swarm
                .delegator_verification_pubkey()
                .map_err(Error::CoreError)?,
            delegatee_public_key: expired_key.delegatee_public_key(),
            node_type: default_online_node_type(),
            network_id: expired_processor.swarm.network_id(),
            storage_redundancy: expired_processor.swarm.storage_redundancy(),
            dht_virtual_nodes: expired_processor.swarm.dht_virtual_nodes(),
            capabilities: OnlineNodeCapabilities::default(),
            endpoint_hint: None,
            started_at_ms: now_ms.saturating_sub(120_000),
            fresh_for_ms: 60_000,
            expires_at_ms: now_ms.saturating_sub(30_000),
            version: crate::util::build_version(),
        },
        MessageSigner::new(&expired_key, expired_processor.swarm.network_id()),
    )
    .map_err(Error::CoreError)?;

    processor
        .storage_store(Processor::registry_entry(ONLINE_NODES_TOPIC, vec![
            live.clone(),
            expired.clone(),
        ])?)
        .await?;

    let live_nodes = processor.lookup_online_nodes(false).await?;
    assert_eq!(elements(&live_nodes)?, elements(&[live])?);

    let all_nodes = processor.lookup_online_nodes(true).await?;
    assert_eq!(all_nodes.len(), 2);
    assert!(all_nodes
        .iter()
        .any(|descriptor| descriptor.did == processor.did()));
    assert!(all_nodes
        .iter()
        .any(|descriptor| descriptor.did == expired_processor.did()));
    assert!(elements(&all_nodes)?.contains(&expired.to_element().map_err(Error::CoreError)?));
    Ok(())
}

#[tokio::test]
async fn test_online_node_lookup_filters_other_network_descriptors() -> Result<()> {
    let processor = prepare_processor_with_network(0).await;
    let foreign = prepare_processor_with_network(1).await;
    let now_ms = get_epoch_ms();
    let local_descriptor = processor.online_node_descriptor_at(now_ms)?;
    let foreign_descriptor = foreign.online_node_descriptor_at(now_ms)?;

    processor
        .storage_store(Processor::registry_entry(ONLINE_NODES_TOPIC, vec![
            local_descriptor.clone(),
            foreign_descriptor,
        ])?)
        .await?;

    let nodes = processor.lookup_online_nodes(true).await?;
    assert_eq!(elements(&nodes)?, elements(&[local_descriptor])?);
    Ok(())
}

#[tokio::test]
async fn test_online_node_lookup_filters_other_dht_virtual_node_modes() -> Result<()> {
    let processor = prepare_processor_with_network_and_virtual_nodes(0, 2).await;
    let foreign = prepare_processor_with_network_and_virtual_nodes(0, 3).await;
    let now_ms = get_epoch_ms();
    let local_descriptor = processor.online_node_descriptor_at(now_ms)?;
    let foreign_descriptor = foreign.online_node_descriptor_at(now_ms)?;

    processor
        .storage_store(Processor::registry_entry(ONLINE_NODES_TOPIC, vec![
            local_descriptor.clone(),
            foreign_descriptor,
        ])?)
        .await?;

    let nodes = processor.lookup_online_nodes(true).await?;
    assert_eq!(elements(&nodes)?, elements(&[local_descriptor])?);
    Ok(())
}

#[tokio::test]
async fn test_online_node_lookup_filters_other_storage_redundancy_modes() -> Result<()> {
    let processor = prepare_processor_with_network(0).await;
    let foreign = prepare_processor_with_network(0).await;
    let now_ms = get_epoch_ms();
    let local_descriptor = processor.online_node_descriptor_at(now_ms)?;
    let foreign_key = foreign.delegatee_key();
    let foreign_descriptor = OnlineNodeDescriptor::new_signed(
        OnlineNodeDescriptorBody {
            did: foreign.did(),
            public_key: foreign
                .swarm
                .delegator_verification_pubkey()
                .map_err(Error::CoreError)?,
            delegatee_public_key: foreign_key.delegatee_public_key(),
            node_type: default_online_node_type(),
            network_id: foreign.swarm.network_id(),
            storage_redundancy: mismatched_storage_redundancy(foreign.swarm.storage_redundancy()),
            dht_virtual_nodes: foreign.swarm.dht_virtual_nodes(),
            capabilities: OnlineNodeCapabilities::default(),
            endpoint_hint: None,
            started_at_ms: now_ms,
            fresh_for_ms: 60_000,
            expires_at_ms: now_ms.saturating_add(60_000),
            version: crate::util::build_version(),
        },
        MessageSigner::new(&foreign_key, foreign.swarm.network_id()),
    )
    .map_err(Error::CoreError)?;

    processor
        .storage_store(Processor::registry_entry(ONLINE_NODES_TOPIC, vec![
            local_descriptor.clone(),
            foreign_descriptor,
        ])?)
        .await?;

    let nodes = processor.lookup_online_nodes(true).await?;
    assert_eq!(elements(&nodes)?, elements(&[local_descriptor])?);
    Ok(())
}

#[tokio::test]
async fn test_online_node_registry_lists_multiple_nodes() -> Result<()> {
    let processor = prepare_processor().await;
    let other = prepare_processor().await;
    let other_descriptor = other.online_node_descriptor_at(get_epoch_ms())?;

    processor
        .storage_append_data(
            ONLINE_NODES_TOPIC,
            other_descriptor.to_element().map_err(Error::CoreError)?,
        )
        .await?;
    let published = processor.publish_online_node_descriptor().await?;
    let mut nodes = processor.lookup_online_nodes(false).await?;
    nodes.sort_by_key(|descriptor| descriptor.did);

    assert_eq!(nodes.len(), 2);
    assert!(nodes
        .iter()
        .any(|descriptor| descriptor.did == published.did));
    assert!(nodes.iter().any(|descriptor| descriptor.did == other.did()));
    assert!(nodes
        .iter()
        .all(|descriptor| descriptor.verify_signature(processor.swarm.network_id())));
    Ok(())
}