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
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
//! Signed online-node descriptors stored in the DHT.

use std::borrow::Borrow;

use rings_core::delegation::DelegateeKey;
use rings_core::dht::Did;
use rings_core::dht::RelayCustody;
use rings_core::domain_tag;
use rings_core::ecc::PublicKey;
use rings_core::ecc::VerificationPublicKey;
use rings_core::error::Error;
use rings_core::error::Result;
use rings_core::message::DhtProtocolMode;
use rings_core::message::DomainTag;
use rings_core::message::MessageSigner;
use rings_core::message::MessageVerification;
use serde::Deserialize;
use serde::Serialize;

use crate::descriptor::latest_valid_by_did;
use crate::descriptor::sign_descriptor_body;
use crate::descriptor::RegistryElement;
use crate::descriptor::SignedDescriptor;
use crate::descriptor::SignedDescriptorBody;
use crate::onion::OnionProcessEpoch;

/// DHT topic used for online-node registry descriptors.
pub const ONLINE_NODES_TOPIC: &str = "online_nodes";
/// Message family of the online-node descriptor signature.
const ONLINE_NODE_DESCRIPTOR_DOMAIN_TAG: DomainTag =
    domain_tag!("rings-node:online-node-descriptor");

/// Runtime family advertised by a node descriptor.
#[derive(Clone, Debug, Deserialize, Serialize, Eq, PartialEq)]
pub enum OnlineNodeType {
    /// Browser runtime.
    Browser,
    /// Native node runtime.
    Native,
    /// FFI runtime.
    Ffi,
}

/// Typed capabilities of one node process, published in its online-node descriptor.
///
/// `onion_relay = Some(e_n)` registers the identity symbol `relay` of the onion signature at the
/// process epoch `e_n` (#834 D2). The epoch is part of the capability, so a relay registration
/// without an epoch is unrepresentable.
///
/// `relay_custody` is the declaration the node also makes in every connection handshake: a node
/// without a retained relay store holds no relay mail, and relay custody moves past it to the
/// next node along the successor path that holds relay mail (`rings_core::dht::relay_holder`).
#[derive(Clone, Copy, Debug, Default, Deserialize, Serialize, Eq, PartialEq)]
pub struct OnlineNodeCapabilities {
    /// Process epoch at which this node registers the onion `relay` symbol, if it does.
    pub onion_relay: Option<OnionProcessEpoch>,
    /// Whether this node holds relay mail.
    pub relay_custody: RelayCustody,
}

impl OnlineNodeCapabilities {
    /// Register the onion `relay` symbol at process epoch `epoch`, holding relay mail.
    pub const fn onion_relay(epoch: OnionProcessEpoch) -> Self {
        Self {
            onion_relay: Some(epoch),
            relay_custody: RelayCustody::Holds,
        }
    }
}

/// Descriptor fields covered by the online-node signature.
#[derive(Clone, Debug, Deserialize, Serialize, Eq, PartialEq)]
pub struct OnlineNodeDescriptorBody {
    /// DID of the node/account.
    pub did: Did,
    /// Account public key corresponding to `did`.
    pub public_key: VerificationPublicKey,
    /// Delegation public key used for encrypted onion relay frames.
    pub delegatee_public_key: PublicKey<33>,
    /// Runtime family of this node.
    pub node_type: OnlineNodeType,
    /// Network identifier.
    pub network_id: u32,
    /// Storage redundancy required by this DHT protocol mode.
    pub storage_redundancy: u16,
    /// Storage virtual-node positions required by this DHT protocol mode.
    pub dht_virtual_nodes: u16,
    /// Typed capabilities of this node process.
    pub capabilities: OnlineNodeCapabilities,
    /// Optional endpoint hint, controlled by node policy/configuration.
    pub endpoint_hint: Option<String>,
    /// Process start timestamp in milliseconds since Unix epoch.
    pub started_at_ms: u128,
    /// Freshness window `T` in milliseconds: a reader holds the descriptor live only while it
    /// heard it within `T` (see the lease law of `descriptor`).
    pub fresh_for_ms: u64,
    /// Lease end `ℓ` in milliseconds since Unix epoch.
    pub expires_at_ms: u128,
    /// Node software version.
    pub version: String,
}

impl OnlineNodeDescriptorBody {
    fn body_ref(&self) -> OnlineNodeDescriptorBodyRef<'_> {
        OnlineNodeDescriptorBodyRef {
            did: self.did,
            public_key: &self.public_key,
            delegatee_public_key: &self.delegatee_public_key,
            node_type: &self.node_type,
            network_id: self.network_id,
            storage_redundancy: self.storage_redundancy,
            dht_virtual_nodes: self.dht_virtual_nodes,
            capabilities: self.capabilities,
            endpoint_hint: &self.endpoint_hint,
            started_at_ms: self.started_at_ms,
            fresh_for_ms: self.fresh_for_ms,
            expires_at_ms: self.expires_at_ms,
            version: self.version.as_str(),
        }
    }

    fn signing_data(&self) -> Result<Vec<u8>> {
        self.body_ref().signing_data()
    }
}

impl SignedDescriptorBody for OnlineNodeDescriptorBody {
    type Descriptor = OnlineNodeDescriptor;

    const DOMAIN_TAG: DomainTag = ONLINE_NODE_DESCRIPTOR_DOMAIN_TAG;

    fn body_did(&self) -> Did {
        self.did
    }

    fn body_public_key(&self) -> &VerificationPublicKey {
        &self.public_key
    }

    fn body_network_id(&self) -> u32 {
        self.network_id
    }

    fn body_signing_data(&self) -> Result<Vec<u8>> {
        self.signing_data()
    }

    fn into_signed_descriptor(self, signature: MessageVerification) -> Self::Descriptor {
        OnlineNodeDescriptor {
            did: self.did,
            public_key: self.public_key,
            delegatee_public_key: self.delegatee_public_key,
            node_type: self.node_type,
            network_id: self.network_id,
            storage_redundancy: self.storage_redundancy,
            dht_virtual_nodes: self.dht_virtual_nodes,
            capabilities: self.capabilities,
            endpoint_hint: self.endpoint_hint,
            started_at_ms: self.started_at_ms,
            heartbeat_at_ms: 0,
            fresh_for_ms: self.fresh_for_ms,
            expires_at_ms: self.expires_at_ms,
            version: self.version,
            signature,
        }
    }
}

#[derive(Serialize)]
struct OnlineNodeDescriptorBodyRef<'a> {
    did: Did,
    public_key: &'a VerificationPublicKey,
    delegatee_public_key: &'a PublicKey<33>,
    node_type: &'a OnlineNodeType,
    network_id: u32,
    storage_redundancy: u16,
    dht_virtual_nodes: u16,
    capabilities: OnlineNodeCapabilities,
    endpoint_hint: &'a Option<String>,
    started_at_ms: u128,
    fresh_for_ms: u64,
    expires_at_ms: u128,
    version: &'a str,
}

impl OnlineNodeDescriptorBodyRef<'_> {
    fn signing_data(&self) -> Result<Vec<u8>> {
        rings_codec::serialize(self).map_err(Error::CodecSerialize)
    }
}

/// Signed descriptor published by online nodes.
#[derive(Clone, Debug, Deserialize, Serialize, Eq, PartialEq)]
pub struct OnlineNodeDescriptor {
    /// DID of the node/account.
    pub did: Did,
    /// Account public key corresponding to `did`.
    pub public_key: VerificationPublicKey,
    /// Delegation public key used for encrypted onion relay frames.
    pub delegatee_public_key: PublicKey<33>,
    /// Runtime family of this node.
    pub node_type: OnlineNodeType,
    /// Network identifier.
    pub network_id: u32,
    /// Storage redundancy required by this DHT protocol mode.
    pub storage_redundancy: u16,
    /// Storage virtual-node positions required by this DHT protocol mode.
    pub dht_virtual_nodes: u16,
    /// Typed capabilities of this node process.
    pub capabilities: OnlineNodeCapabilities,
    /// Optional endpoint hint, controlled by node policy/configuration.
    pub endpoint_hint: Option<String>,
    /// Process start timestamp in milliseconds since Unix epoch.
    pub started_at_ms: u128,
    /// When the reader last heard this descriptor, in milliseconds since Unix epoch: the dot of
    /// its element in the fetched registry carrier. Not signed and not encoded (see the lease
    /// law of `descriptor`); `0` until heard.
    #[serde(skip)]
    pub heartbeat_at_ms: u128,
    /// Freshness window `T` in milliseconds.
    pub fresh_for_ms: u64,
    /// Lease end `ℓ` in milliseconds since Unix epoch.
    pub expires_at_ms: u128,
    /// Node software version.
    pub version: String,
    /// Signature covering every descriptor field above except `heartbeat_at_ms`.
    pub signature: MessageVerification,
}

impl OnlineNodeDescriptor {
    /// Create and sign a descriptor.
    pub fn new_signed(
        body: OnlineNodeDescriptorBody,
        signer: MessageSigner<impl Borrow<DelegateeKey>>,
    ) -> Result<Self> {
        sign_descriptor_body(
            body,
            signer,
            "online node descriptor DID/public key/session mismatch",
        )
    }

    fn body_ref(&self) -> OnlineNodeDescriptorBodyRef<'_> {
        let Self {
            did,
            public_key,
            delegatee_public_key,
            node_type,
            network_id,
            storage_redundancy,
            dht_virtual_nodes,
            capabilities,
            endpoint_hint,
            started_at_ms,
            heartbeat_at_ms: _,
            fresh_for_ms,
            expires_at_ms,
            version,
            signature: _,
        } = self;

        OnlineNodeDescriptorBodyRef {
            did: *did,
            public_key,
            delegatee_public_key,
            node_type,
            network_id: *network_id,
            storage_redundancy: *storage_redundancy,
            dht_virtual_nodes: *dht_virtual_nodes,
            capabilities: *capabilities,
            endpoint_hint,
            started_at_ms: *started_at_ms,
            fresh_for_ms: *fresh_for_ms,
            expires_at_ms: *expires_at_ms,
            version: version.as_str(),
        }
    }

    fn signing_data(&self) -> Result<Vec<u8>> {
        self.body_ref().signing_data()
    }

    /// Return this descriptor's DHT protocol mode.
    pub const fn dht_protocol_mode(&self) -> DhtProtocolMode {
        DhtProtocolMode::new(
            self.network_id,
            self.storage_redundancy,
            self.dht_virtual_nodes,
        )
    }

    /// Return whether this descriptor belongs to the local DHT protocol mode.
    pub fn matches_dht_protocol(&self, expected: DhtProtocolMode) -> bool {
        self.dht_protocol_mode().matches(expected)
    }

    /// Verify the descriptor signature under the receiver's overlay `network_id` and the
    /// DID/public-key binding.
    ///
    /// This does not apply the embedded [`MessageVerification`] timestamp/TTL
    /// as a liveness rule. Online-node liveness is defined by the lease law of
    /// `descriptor`: the signed lease end and freshness window, and the time the
    /// descriptor was heard; use [`Self::is_live_at`] when it should be enforced.
    pub fn verify_signature(&self, network_id: u32) -> bool {
        self.descriptor_verify_signature(network_id)
    }

    /// Returns whether this descriptor is expired at `now_ms`: its lease ended, or it was not
    /// heard within its freshness window.
    pub fn is_expired_at(&self, now_ms: u128) -> bool {
        self.descriptor_is_expired_at(now_ms)
    }

    /// Returns whether a reader lists this descriptor: it verifies under the overlay
    /// `network_id`, its lease terms are admissible, and it is not expired (the lease law of
    /// `descriptor`).
    pub fn is_live_at(&self, now_ms: u128, network_id: u32) -> bool {
        self.descriptor_is_live_at(now_ms, network_id)
    }

    /// Select the newest descriptor per DID that verifies under the overlay `network_id`.
    pub fn latest_valid_by_did(
        descriptors: impl IntoIterator<Item = Self>,
        now_ms: u128,
        network_id: u32,
        include_expired: bool,
    ) -> Vec<Self> {
        latest_valid_by_did(descriptors, now_ms, network_id, include_expired)
    }
}

impl SignedDescriptor for OnlineNodeDescriptor {
    type Body = OnlineNodeDescriptorBody;

    fn descriptor_did(&self) -> Did {
        self.did
    }

    fn descriptor_public_key(&self) -> &VerificationPublicKey {
        &self.public_key
    }

    fn descriptor_network_id(&self) -> u32 {
        self.network_id
    }

    fn descriptor_signature(&self) -> &MessageVerification {
        &self.signature
    }

    fn descriptor_heartbeat_at_ms(&self) -> u128 {
        self.heartbeat_at_ms
    }

    fn descriptor_expires_at_ms(&self) -> u128 {
        self.expires_at_ms
    }

    fn descriptor_fresh_for_ms(&self) -> u64 {
        self.fresh_for_ms
    }

    fn descriptor_signing_data(&self) -> Result<Vec<u8>> {
        self.signing_data()
    }

    fn heard_at(self, heartbeat_at_ms: u128) -> Self {
        Self {
            heartbeat_at_ms,
            ..self
        }
    }
}

impl RegistryElement for OnlineNodeDescriptor {}

#[cfg(test)]
mod tests {
    use rings_core::consts::TS_OFFSET_TOLERANCE_MS;
    use rings_core::delegation::DelegateeKey;
    use rings_core::ecc::SecretKey;

    use super::*;
    use crate::tests::TEST_NETWORK_ID;

    /// Mint a test delegatee key valid across both synthetic `[0, ...)` timestamps and wall-clock
    /// signature checks.
    fn test_delegatee_key(secret: &SecretKey) -> Result<DelegateeKey> {
        DelegateeKey::new_with_seckey_at(secret, u64::MAX, 0)
    }

    /// A descriptor of a fresh account, fresh for `fresh_for_ms` until the lease end
    /// `expires_at_ms`, heard at `heartbeat_at_ms`.
    fn descriptor_at(
        heartbeat_at_ms: u128,
        fresh_for_ms: u64,
        expires_at_ms: u128,
    ) -> Result<OnlineNodeDescriptor> {
        let key = SecretKey::random();
        let delegatee_key = test_delegatee_key(&key)?;
        Ok(
            descriptor_of(&delegatee_key, "test", fresh_for_ms, expires_at_ms)?
                .heard_at(heartbeat_at_ms),
        )
    }

    /// A descriptor of `delegatee_key`'s node at `version`, fresh for `fresh_for_ms` until the
    /// lease end `expires_at_ms`, not yet heard.
    fn descriptor_of(
        delegatee_key: &DelegateeKey,
        version: &str,
        fresh_for_ms: u64,
        expires_at_ms: u128,
    ) -> Result<OnlineNodeDescriptor> {
        let did = delegatee_key.delegator_did();
        OnlineNodeDescriptor::new_signed(
            OnlineNodeDescriptorBody {
                did,
                public_key: delegatee_key.delegation().delegator_verification_pubkey()?,
                delegatee_public_key: delegatee_key.delegatee_public_key(),
                node_type: OnlineNodeType::Native,
                network_id: 1,
                storage_redundancy: 6,
                dht_virtual_nodes: 0,
                capabilities: OnlineNodeCapabilities::default(),
                endpoint_hint: None,
                started_at_ms: 10,
                fresh_for_ms,
                expires_at_ms,
                version: version.to_string(),
            },
            MessageSigner::new(delegatee_key, TEST_NETWORK_ID),
        )
    }

    /// Totality (#864): of two distinct descriptors of one DID at an equal lease and heartbeat,
    /// the same one is selected whatever order they are read in: two delegatee keys of one
    /// account (two processes publishing in the same millisecond).
    #[test]
    fn test_latest_valid_by_did_breaks_an_equal_lease_by_content() -> Result<()> {
        let account = SecretKey::random();
        let delegatee_key = test_delegatee_key(&account)?;
        let other_delegatee_key = test_delegatee_key(&account)?;
        let one = descriptor_of(&delegatee_key, "test", 100, 200)?.heard_at(20);
        let other_process = descriptor_of(&other_delegatee_key, "test", 100, 200)?.heard_at(20);
        assert_eq!(other_process.did, one.did);
        assert_ne!(other_process, one);

        let forward = OnlineNodeDescriptor::latest_valid_by_did(
            [one.clone(), other_process.clone()],
            50,
            TEST_NETWORK_ID,
            false,
        );
        let reverse = OnlineNodeDescriptor::latest_valid_by_did(
            [other_process, one],
            50,
            TEST_NETWORK_ID,
            false,
        );
        assert_eq!(forward, reverse);
        assert_eq!(forward.len(), 1);
        Ok(())
    }

    #[test]
    fn test_descriptor_signature_covers_mutable_fields() -> Result<()> {
        let mut descriptor = descriptor_at(20, 10, 30)?;
        assert!(descriptor.verify_signature(TEST_NETWORK_ID));

        descriptor.node_type = OnlineNodeType::Browser;
        assert!(!descriptor.verify_signature(TEST_NETWORK_ID));
        descriptor = descriptor_at(20, 10, 30)?;
        descriptor.storage_redundancy = 7;
        assert!(!descriptor.verify_signature(TEST_NETWORK_ID));
        descriptor = descriptor_at(20, 10, 30)?;
        descriptor.expires_at_ms = 31;
        assert!(!descriptor.verify_signature(TEST_NETWORK_ID));
        descriptor = descriptor_at(20, 10, 30)?;
        descriptor.fresh_for_ms = 11;
        assert!(!descriptor.verify_signature(TEST_NETWORK_ID));
        Ok(())
    }

    /// The heard time is neither signed nor encoded: a descriptor heard at any time verifies,
    /// and its element is the same bytes, which decode unheard.
    #[test]
    fn test_heard_time_is_neither_signed_nor_encoded() -> Result<()> {
        let unheard = descriptor_at(0, 10, 30)?;
        let heard = unheard.clone().heard_at(25);
        assert!(heard.verify_signature(TEST_NETWORK_ID));
        let element = heard.to_element()?;
        assert_eq!(element, unheard.to_element()?);
        assert_eq!(OnlineNodeDescriptor::from_element(&element)?, unheard);
        Ok(())
    }

    /// Lease law (#918): live iff `t ≤ ℓ` and `t ≤ τ* + T + σ`; a descriptor re-appended after
    /// its registrant stopped is listed at most until its signed lease end.
    #[test]
    fn test_a_descriptor_is_live_within_its_lease_and_freshness() -> Result<()> {
        let skew = TS_OFFSET_TOLERANCE_MS;
        let fresh = descriptor_at(1_000, 90, 10_000)?;
        assert!(fresh.is_live_at(1_000 + 90 + skew, TEST_NETWORK_ID));
        assert!(!fresh.is_live_at(1_000 + 90 + skew + 1, TEST_NETWORK_ID));

        let replayed = descriptor_at(10_000, 90, 10_000)?;
        assert!(replayed.is_live_at(10_000, TEST_NETWORK_ID));
        let replayed_late = descriptor_at(10_001, 90, 10_000)?;
        assert!(
            !replayed_late.is_live_at(10_001, TEST_NETWORK_ID),
            "a fresh dot never extends a lease past its signed end"
        );
        Ok(())
    }

    /// The reader bounds the signed terms (Law 9): a lease ending more than `Λ + σ` from now, or
    /// a freshness window longer than `Λ`, is never live, so a one-shot write cannot list its
    /// signer for longer than a lease; at the bounds it is live.
    #[test]
    fn test_a_descriptor_with_terms_past_the_lease_is_never_live() -> Result<()> {
        let lease = crate::descriptor::registry_lease().as_millis();
        let lease_u64 = u64::try_from(lease).unwrap_or(u64::MAX);
        let skew = TS_OFFSET_TOLERANCE_MS;
        let now = 1_000_000;

        let at_bound = descriptor_at(now, lease_u64, now + lease + skew)?;
        assert!(at_bound.is_live_at(now, TEST_NETWORK_ID));
        let long_lease = descriptor_at(now, 90_000, now + lease + skew + 1)?;
        assert!(!long_lease.is_live_at(now, TEST_NETWORK_ID));
        let long_window = descriptor_at(now, lease_u64 + 1, now + 90_000)?;
        assert!(!long_window.is_live_at(now, TEST_NETWORK_ID));
        assert!(
            long_lease.is_live_at(now + skew + 1, TEST_NETWORK_ID),
            "a lease within reach of the reader's clock is live again"
        );
        Ok(())
    }

    #[test]
    fn test_descriptor_round_trips_through_dht_encoding() -> Result<()> {
        let descriptor = descriptor_at(0, 10, 30)?;
        let element = descriptor.to_element()?;
        let decoded = OnlineNodeDescriptor::from_element(&element)?;

        assert_eq!(decoded, descriptor);
        assert!(decoded.verify_signature(TEST_NETWORK_ID));
        Ok(())
    }

    /// Delegation validity law: `is_live_at` judges the signing delegation at `now_ms`, so a
    /// descriptor whose delegation is not yet valid beyond `TS_OFFSET_TOLERANCE_MS` or has
    /// already expired at `now_ms` is rejected even while its own lease terms are live.
    #[test]
    fn test_a_descriptor_requires_its_delegation_to_be_live_at_now() -> Result<()> {
        let skew = TS_OFFSET_TOLERANCE_MS;
        let issued_at = 10_000;
        let delegation_ttl = 1_000;
        let key = SecretKey::random();
        let delegatee_key = DelegateeKey::new_with_seckey_at(&key, delegation_ttl, issued_at)?;
        let descriptor = descriptor_of(&delegatee_key, "test", 20_000, 25_000)?.heard_at(5_000);

        assert!(!descriptor.is_live_at(issued_at - skew - 1, TEST_NETWORK_ID));
        assert!(descriptor.is_live_at(issued_at - skew, TEST_NETWORK_ID));
        assert!(descriptor.is_live_at(issued_at + u128::from(delegation_ttl), TEST_NETWORK_ID));
        assert!(!descriptor.is_live_at(issued_at + u128::from(delegation_ttl) + 1, TEST_NETWORK_ID));
        Ok(())
    }

    /// The newest lease of a DID wins even when an older lease was heard later, as a replayed
    /// older lease is; expired descriptors are kept only on request.
    #[test]
    fn test_latest_valid_by_did_filters_expired_and_keeps_the_newest_lease() -> Result<()> {
        let key = SecretKey::random();
        let delegatee_key = test_delegatee_key(&key)?;
        let older = descriptor_of(&delegatee_key, "old", 100, 90)?.heard_at(45);
        let newer = descriptor_of(&delegatee_key, "new", 100, 100)?.heard_at(40);
        let other_live = descriptor_at(25, 100, 100)?;
        let expired = descriptor_at(30, 100, 40)?;

        let descriptors = OnlineNodeDescriptor::latest_valid_by_did(
            vec![
                older.clone(),
                newer.clone(),
                other_live.clone(),
                expired.clone(),
            ],
            50,
            TEST_NETWORK_ID,
            false,
        );

        assert_eq!(descriptors.len(), 2);
        assert!(descriptors.iter().any(|descriptor| descriptor == &newer));
        assert!(descriptors
            .iter()
            .any(|descriptor| descriptor == &other_live));

        let with_expired = OnlineNodeDescriptor::latest_valid_by_did(
            vec![older, newer, other_live, expired],
            50,
            TEST_NETWORK_ID,
            true,
        );
        assert_eq!(with_expired.len(), 3);
        Ok(())
    }
}