rings-node 1.0.0-pre.6

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
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
//! The onion privacy layer: its directory, route selection and loop data plane.
//!
//! This module deliberately sits in `rings-node`, not `rings-core`: Chord
//! remains the storage and discovery substrate, while exit policy is an
//! application protocol decision.
//!
//! The data plane runs client-sealed loops of fixed-width Sphinx cells (`circuit`, `sphinx`). A
//! loop evaluates a pipeline over the static signature `Σ` of operation symbols (`signature`):
//! every hop's step interprets the identity symbol `relay`, and each node's Σ-algebra interprets
//! the world-facing symbols it registers, as sessions (`session`) over their worlds (`tcp`,
//! `https`). Route selection places a pipeline on a guard-closed loop (`loop_shape`) whose every
//! position is a node registering that position's symbol at its current process epoch.

use std::borrow::Borrow;
use std::sync::Arc;
use std::sync::RwLock;
use std::time::Duration;

use async_trait::async_trait;
use rings_core::delegation::DelegateeKey;
use rings_core::dht::Did;
use rings_core::domain_tag;
use rings_core::ecc::PublicKey;
use rings_core::ecc::VerificationPublicKey;
use rings_core::error::Error as CoreError;
use rings_core::error::Result as CoreResult;
use rings_core::message::DomainTag;
use rings_core::message::MessageSigner;
use rings_core::message::MessageVerification;
use rings_core::utils::SharedClock;
#[cfg(all(test, not(target_family = "wasm")))]
use rings_core::utils::SystemClock;
use serde::Deserialize;
use serde::Serialize;

use crate::descriptor::heard_elements;
use crate::descriptor::latest_valid_by_key;
use crate::descriptor::sign_descriptor_body;
use crate::descriptor::RegistryElement;
use crate::descriptor::SignedDescriptor;
use crate::descriptor::SignedDescriptorBody;
use crate::error::Error;
use crate::error::Result;
use crate::online::OnlineNodeType;
use crate::registration::DhtRegistrationPublisher;
use crate::registration::LeaseTerms;
use crate::registration::RegistrationContext;
use crate::registration::RegistrationTask;

pub mod circuit;
pub(crate) mod directory;
mod entry_guard;
pub(crate) mod exit_accounting;
mod failure;
#[cfg(rings_native)]
mod gateway;
#[cfg(any(rings_native, rings_browser))]
pub mod https;
pub(crate) mod invoke_accounting;
pub mod invoke_descriptor;
mod loop_shape;
#[cfg(rings_native)]
pub mod native;
pub mod pipeline;
pub mod proxy;
mod role;
pub mod route;
pub(crate) mod runtime;
pub(crate) mod session;
pub mod signature;
pub(crate) mod sphinx;
pub mod target;
#[cfg(rings_native)]
pub mod tcp;

pub use circuit::OnionInvokeBackend;
pub use circuit::OnionInvokeCall;
pub use circuit::OnionInvokeFn;
pub use entry_guard::OnionEntryGuardState;
pub use entry_guard::OnionEntryGuardStorage;
pub(crate) use entry_guard::OnionEntryGuards;
pub use failure::OnionExitFailure;
pub use failure::OnionRouteError;
#[cfg(rings_native)]
pub use gateway::NativeOnionGatewayConnector;
pub use invoke_descriptor::OnionInvokeDescriptor;
pub use invoke_descriptor::OnionInvokeDescriptorBody;
pub use invoke_descriptor::OnionInvokeDescriptorDecodeReport;
pub use invoke_descriptor::OnionInvokePolicy;
pub(crate) use invoke_descriptor::OnionInvokeRegistration;
pub use invoke_descriptor::ONION_INVOKES_TOPIC;
pub use loop_shape::OnionLoop;
pub(crate) use loop_shape::OnionLoopRelay;
pub use loop_shape::OnionLoopRole;
pub use loop_shape::OnionLoopShape;
pub(crate) use loop_shape::OnionPipelineSymbols;
pub use loop_shape::MAX_ONION_LOOP_HOPS;
pub use loop_shape::MAX_ONION_LOOP_SYMBOLS;
pub use loop_shape::ONION_SEGMENT_RELAYS;
pub use pipeline::OnionInvokeArguments;
pub use pipeline::OnionInvokePipeline;
pub use pipeline::OnionInvokeStage;
pub use pipeline::OnionPipeline;
pub use pipeline::OnionPipelineError;
pub use pipeline::OnionPipelineTerm;
pub use pipeline::OnionValueType;
pub use role::OnionExitOffer;
pub use role::OnionInvokeOffer;
pub use role::OnionRole;
pub(crate) use route::select_onion_route_from_candidates;
pub use route::OnionPipelineRoute;
pub use route::OnionPipelineRouteRequest;
pub use route::OnionRoute;
pub(crate) use route::OnionRouteCandidates;
pub use route::OnionRouteHop;
pub use route::OnionRouteRequest;
pub use runtime::OnionPipelineHandle;
pub use signature::OnionBackendName;
pub use signature::OnionInputType;
pub use signature::OnionInvokeShape;
pub use signature::OnionLatencyClass;
pub use signature::OnionServiceName;
pub use signature::OnionShape;
pub use signature::OnionWidthClass;
pub use signature::ONION_BACKEND_NAME_MAX_BYTES;
pub use sphinx::class::OnionLoopClass;
pub use target::OnionProxyTarget;
pub use target::OnionProxyTargetError;

/// DHT topic used for application-layer onion exit descriptors.
pub const ONION_EXITS_TOPIC: &str = "onion_exits";

/// Process epoch `e_n` of one node process (#834 D2), drawn afresh at every process start.
///
/// Every symbol a process registers carries its `e_n`: `relay` in the online-node capabilities and
/// every other symbol in its signed descriptor, so a process registers exactly one epoch,
///
/// ```text
/// ∀ f ∈ Σ_n.  epoch(f) = e_n,
/// ```
///
/// and a layer sealed for an earlier process of the same node names an epoch no current
/// registration carries.
#[derive(Clone, Copy, Debug, Deserialize, Eq, Hash, Ord, PartialEq, PartialOrd, Serialize)]
pub struct OnionProcessEpoch([u8; 16]);

impl OnionProcessEpoch {
    /// Build a process epoch from explicit bytes.
    pub const fn new(bytes: [u8; 16]) -> Self {
        Self(bytes)
    }

    /// Return the epoch bytes, the `e` field of the uniform layer (#834 D6″).
    pub(crate) const fn to_bytes(self) -> [u8; 16] {
        self.0
    }

    /// Draw a fresh process epoch from an explicit cryptographic RNG.
    pub fn from_rng(rng: &mut impl rand::RngCore) -> Self {
        let mut bytes = [0_u8; 16];
        rng.fill_bytes(&mut bytes);
        Self(bytes)
    }

    /// Draw a fresh process epoch for one process lifetime.
    pub fn random() -> Self {
        Self::from_rng(&mut rings_core::utils::SystemEntropy)
    }
}

/// The current process epoch `e_n` of this node, shared by the onion admission state, which
/// renews it, and the registrations, which publish it at every heartbeat (#834 D2, L9).
///
/// Law: the epoch changes only by `renew`, to an epoch drawn independently and
/// uniformly, when admission detects a clock rollback beyond `X₀`; every registration published
/// after the renewal names the new epoch, and every layer sealed for the old one is rejected.
#[derive(Clone, Debug)]
pub struct OnionProcessEpochCell(Arc<RwLock<OnionProcessEpoch>>);

impl OnionProcessEpochCell {
    /// A cell holding `epoch`, the epoch drawn at process start.
    pub fn new(epoch: OnionProcessEpoch) -> Self {
        Self(Arc::new(RwLock::new(epoch)))
    }

    /// The current epoch.
    pub fn get(&self) -> OnionProcessEpoch {
        self.0
            .read()
            .map_or_else(|poisoned| *poisoned.into_inner(), |epoch| *epoch)
    }

    /// Replace the current epoch by `epoch`, after an admission reset.
    pub(crate) fn renew(&self, epoch: OnionProcessEpoch) {
        match self.0.write() {
            Ok(mut current) => *current = epoch,
            Err(poisoned) => *poisoned.into_inner() = epoch,
        }
    }
}

const DEFAULT_ONION_EXIT_HEARTBEAT_INTERVAL_SECS: u64 = 30;
const DEFAULT_ONION_EXIT_TTL_SECS: u64 = 90;
/// Message family of the onion-exit descriptor signature.
const ONION_EXIT_DESCRIPTOR_DOMAIN_TAG: DomainTag = domain_tag!("rings-node:onion-exit-descriptor");

/// Default onion-exit registry heartbeat interval in seconds.
pub(crate) const fn default_onion_exit_heartbeat_interval_secs() -> u64 {
    DEFAULT_ONION_EXIT_HEARTBEAT_INTERVAL_SECS
}

/// Default onion-exit registry descriptor TTL in seconds.
pub(crate) const fn default_onion_exit_ttl_secs() -> u64 {
    DEFAULT_ONION_EXIT_TTL_SECS
}

/// Default onion relay advertisement enablement.
pub(crate) const fn default_advertise_onion_relay() -> bool {
    false
}

/// Default onion exit advertisement enablement.
pub(crate) const fn default_advertise_onion_exit() -> bool {
    false
}

/// Default native exit services: the world-facing symbols of the onion signature, in table order.
/// It is only published when onion-exit advertisement is enabled.
pub fn default_onion_exit_services() -> Vec<OnionServiceName> {
    OnionServiceName::world_facing().collect()
}

/// Standard HTTPS onion-exit service set: the single `https` symbol of the onion signature.
pub fn https_onion_exit_services() -> Vec<OnionServiceName> {
    vec![OnionServiceName::https()]
}

/// Default exit policy. It is intentionally closed until the operator configures targets.
pub fn default_onion_exit_policy() -> OnionExitPolicy {
    OnionExitPolicy::default()
}

/// Signed policy fields for an onion exit.
///
/// Unknown fields are refused, so a removed limit (`max_circuits`, `max_streams_per_circuit`)
/// in an old config fails to load rather than leaving the operator's limit unspecified.
#[derive(Clone, Debug, Default, Deserialize, Serialize, Eq, PartialEq)]
#[serde(deny_unknown_fields)]
pub struct OnionExitPolicy {
    /// Target allow-list entries understood by the exit implementation. Empty means closed.
    pub allowed_targets: Vec<OnionExitTarget>,
    /// Target deny-list entries understood by the exit implementation. Deny entries override allows.
    pub denied_targets: Vec<OnionExitTarget>,
    /// Maximum concurrent sessions this exit wants to serve. `0` means unspecified.
    pub max_sessions: u32,
    /// Maximum bytes per minute. `0` means unspecified.
    pub max_bytes_per_minute: u64,
}

/// One entry of an onion exit policy: a pattern over target authorities.
///
/// ```text
/// OnionExitTarget = Any | AnyHost(port) | Authority(host, port)
/// encode:  *:*      *:port          host:port | [ipv6]:port        (canonical, lowercase)
/// matches(Any, t) = ⊤    matches(AnyHost(p), t) = (port(t) = p)
/// matches(Authority(a), t) = (a = t)
/// ```
///
/// Laws: `parse ∘ encode = Ok` on every pattern, `encode ∘ parse` is canonicalisation, and
/// `matches` is monotone in the pattern order `Authority(h, p) ≤ AnyHost(p) ≤ Any`. The port
/// wildcard is how an operator expresses HTTPS-only egress: `https` is a fetch only, so a TLS
/// tunnel is `tcp` restricted to `*:443` (#834 D1′).
#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
#[serde(try_from = "String", into = "String")]
pub struct OnionExitTarget(OnionExitTargetPattern);

/// The pattern of an [`OnionExitTarget`]; see its encoding table.
#[derive(Clone, Debug, Eq, PartialEq)]
enum OnionExitTargetPattern {
    /// `*:*`: every target.
    Any,
    /// `*:port`: every host on one port.
    AnyHost(u16),
    /// `host:port`: exactly one canonical authority.
    Authority(OnionProxyTarget),
}

impl OnionExitTarget {
    /// The wildcard host `*` of a pattern.
    const WILDCARD: &'static str = "*";

    /// Parse and canonicalize an exit target pattern: `*`, `*:*`, `*:port` or `host:port`.
    pub fn parse(target: impl AsRef<str>) -> Result<Self> {
        let raw = target.as_ref().trim();
        let invalid = |error: &dyn std::fmt::Display| {
            Error::InvalidConfig(format!(
                "invalid onion exit target {:?}; expected host:port, *:port or *:*: {error}",
                target.as_ref()
            ))
        };
        let pattern = match raw.split_once(':') {
            _ if raw == Self::WILDCARD => OnionExitTargetPattern::Any,
            Some((Self::WILDCARD, Self::WILDCARD)) => OnionExitTargetPattern::Any,
            Some((Self::WILDCARD, port)) => match port.parse::<u16>() {
                Ok(0) => return Err(invalid(&OnionProxyTargetError::ZeroPort)),
                Ok(port) => OnionExitTargetPattern::AnyHost(port),
                Err(_) => return Err(invalid(&OnionProxyTargetError::InvalidPort)),
            },
            _ => OnionExitTargetPattern::Authority(
                OnionProxyTarget::parse_authority(raw).map_err(|error| invalid(&error))?,
            ),
        };
        Ok(Self(pattern))
    }

    /// Return whether `target` falls under this pattern.
    pub fn matches(&self, target: &OnionProxyTarget) -> bool {
        match &self.0 {
            OnionExitTargetPattern::Any => true,
            OnionExitTargetPattern::AnyHost(port) => target.port() == *port,
            OnionExitTargetPattern::Authority(authority) => authority == target,
        }
    }

    /// Return whether this target pattern is a single canonical public IP-literal authority.
    pub fn is_public_ip_literal_authority(&self) -> bool {
        matches!(
            &self.0,
            OnionExitTargetPattern::Authority(target)
                if target::validate_public_ip_literal(target).is_ok()
        )
    }
}

impl std::fmt::Display for OnionExitTarget {
    /// The canonical encoding of the pattern.
    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match &self.0 {
            OnionExitTargetPattern::Any => write!(formatter, "*:*"),
            OnionExitTargetPattern::AnyHost(port) => write!(formatter, "*:{port}"),
            OnionExitTargetPattern::Authority(authority) => {
                formatter.write_str(authority.authority().as_str())
            }
        }
    }
}

impl TryFrom<String> for OnionExitTarget {
    type Error = String;

    fn try_from(value: String) -> std::result::Result<Self, Self::Error> {
        Self::parse(&value).map_err(|error| error.to_string())
    }
}

impl From<OnionExitTarget> for String {
    fn from(target: OnionExitTarget) -> Self {
        target.to_string()
    }
}

impl OnionExitPolicy {
    /// Build a policy from raw target strings at configuration or API boundaries.
    pub fn from_target_strings(
        allowed_targets: Vec<String>,
        denied_targets: Vec<String>,
    ) -> Result<Self> {
        Ok(Self {
            allowed_targets: parse_exit_targets(allowed_targets)?,
            denied_targets: parse_exit_targets(denied_targets)?,
            ..Self::default()
        })
    }

    /// Return whether this policy denies every exit target.
    pub fn is_closed(&self) -> bool {
        self.allowed_targets.is_empty()
    }

    /// Validate target lists for an advertised onion exit.
    pub fn validate_targets(&self) -> Result<()> {
        if self.is_closed() {
            return Err(Error::InvalidConfig(
                "advertise_onion_exit requires at least one valid onion_exit_policy allowed target"
                    .to_string(),
            ));
        }
        Ok(())
    }

    /// Validate target lists for a browser onion exit, which can only enforce address-level
    /// public-IP admission on explicit public IP-literal targets.
    pub fn validate_browser_targets(&self) -> Result<()> {
        self.validate_targets()?;
        if let Some(target) = self
            .allowed_targets
            .iter()
            .find(|target| !target.is_public_ip_literal_authority())
        {
            return Err(Error::InvalidConfig(format!(
                "browser HTTPS onion exit policy only supports public IP-literal allowed_targets, got {target}"
            )));
        }
        Ok(())
    }

    /// Return whether `target` is admitted by this policy: some allow entry matches it and no
    /// deny entry does.
    pub fn allows_target(&self, target: &OnionProxyTarget) -> bool {
        !self.is_closed() && !self.denies(target) && self.allows(target)
    }

    /// Whether an allow entry matches `target`.
    fn allows(&self, target: &OnionProxyTarget) -> bool {
        self.allowed_targets
            .iter()
            .any(|allowed| allowed.matches(target))
    }

    /// Whether a deny entry matches `target`.
    fn denies(&self, target: &OnionProxyTarget) -> bool {
        self.denied_targets
            .iter()
            .any(|denied| denied.matches(target))
    }
}

fn parse_exit_targets(targets: Vec<String>) -> Result<Vec<OnionExitTarget>> {
    targets
        .into_iter()
        .map(OnionExitTarget::parse)
        .collect::<Result<Vec<_>>>()
}

/// Descriptor fields covered by the onion-exit signature.
#[derive(Clone, Debug, Deserialize, Serialize, Eq, PartialEq)]
pub struct OnionExitDescriptorBody {
    /// DID of the exit node/account.
    pub did: Did,
    /// Account public key corresponding to `did`.
    pub public_key: VerificationPublicKey,
    /// Delegation public key: the Sphinx key `pk_i` a loop's header blinds the exit's layer to.
    pub delegatee_public_key: PublicKey<33>,
    /// Process epoch `e_n` of the registering process, equal to its `relay` registration's.
    pub process_epoch: OnionProcessEpoch,
    /// Runtime family of this exit node.
    pub node_type: OnlineNodeType,
    /// Network identifier.
    pub network_id: u32,
    /// Service this descriptor is willing to expose.
    pub service: OnionServiceName,
    /// Signed exit policy.
    pub policy: OnionExitPolicy,
    /// 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 OnionExitDescriptorBody {
    fn body_ref(&self) -> OnionExitDescriptorBodyRef<'_> {
        OnionExitDescriptorBodyRef {
            did: self.did,
            public_key: &self.public_key,
            delegatee_public_key: &self.delegatee_public_key,
            process_epoch: self.process_epoch,
            node_type: &self.node_type,
            network_id: self.network_id,
            service: &self.service,
            policy: &self.policy,
            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) -> CoreResult<Vec<u8>> {
        self.body_ref().signing_data()
    }
}

impl SignedDescriptorBody for OnionExitDescriptorBody {
    type Descriptor = OnionExitDescriptor;

    const DOMAIN_TAG: DomainTag = ONION_EXIT_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) -> CoreResult<Vec<u8>> {
        self.signing_data()
    }

    fn into_signed_descriptor(self, signature: MessageVerification) -> Self::Descriptor {
        OnionExitDescriptor {
            did: self.did,
            public_key: self.public_key,
            delegatee_public_key: self.delegatee_public_key,
            process_epoch: self.process_epoch,
            node_type: self.node_type,
            network_id: self.network_id,
            service: self.service,
            policy: self.policy,
            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 OnionExitDescriptorBodyRef<'a> {
    did: Did,
    public_key: &'a VerificationPublicKey,
    delegatee_public_key: &'a PublicKey<33>,
    process_epoch: OnionProcessEpoch,
    node_type: &'a OnlineNodeType,
    network_id: u32,
    service: &'a OnionServiceName,
    policy: &'a OnionExitPolicy,
    started_at_ms: u128,
    fresh_for_ms: u64,
    expires_at_ms: u128,
    version: &'a str,
}

impl OnionExitDescriptorBodyRef<'_> {
    fn signing_data(&self) -> CoreResult<Vec<u8>> {
        rings_codec::serialize(self).map_err(CoreError::CodecSerialize)
    }
}

/// Signed descriptor published by onion exits.
#[derive(Clone, Debug, Deserialize, Serialize, Eq, PartialEq)]
pub struct OnionExitDescriptor {
    /// DID of the exit node/account.
    pub did: Did,
    /// Account public key corresponding to `did`.
    pub public_key: VerificationPublicKey,
    /// Delegation public key: the Sphinx key `pk_i` a loop's header blinds the exit's layer to.
    pub delegatee_public_key: PublicKey<33>,
    /// Process epoch `e_n` of the registering process, equal to its `relay` registration's.
    pub process_epoch: OnionProcessEpoch,
    /// Runtime family of this exit node.
    pub node_type: OnlineNodeType,
    /// Network identifier.
    pub network_id: u32,
    /// Service this descriptor is willing to expose.
    pub service: OnionServiceName,
    /// Signed exit policy.
    pub policy: OnionExitPolicy,
    /// 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 OnionExitDescriptor {
    /// Create and sign an onion-exit descriptor.
    pub fn new_signed(
        body: OnionExitDescriptorBody,
        signer: MessageSigner<impl Borrow<DelegateeKey>>,
    ) -> CoreResult<Self> {
        sign_descriptor_body(
            body,
            signer,
            "onion exit descriptor DID/public key/session mismatch",
        )
    }

    fn body_ref(&self) -> OnionExitDescriptorBodyRef<'_> {
        let Self {
            did,
            public_key,
            delegatee_public_key,
            process_epoch,
            node_type,
            network_id,
            service,
            policy,
            started_at_ms,
            heartbeat_at_ms: _,
            fresh_for_ms,
            expires_at_ms,
            version,
            signature: _,
        } = self;

        OnionExitDescriptorBodyRef {
            did: *did,
            public_key,
            delegatee_public_key,
            process_epoch: *process_epoch,
            node_type,
            network_id: *network_id,
            service,
            policy,
            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) -> CoreResult<Vec<u8>> {
        self.body_ref().signing_data()
    }

    /// Return whether this descriptor offers the service named `service`, after service-name
    /// canonicalization: the predicate of the RPC boundary, where the name is still a string.
    /// Typed callers compare [`Self::service`] directly.
    pub fn offers_service(&self, service: &str) -> bool {
        self.service.matches(service)
    }

    /// Verify the descriptor signature and DID/public-key binding.
    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 has a valid signature, admissible
    /// lease terms, and 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 valid onion-exit descriptor per `(DID, service)`.
    ///
    /// Invariant: an exit may publish independent TCP and HTTPS registrations under the same DID.
    /// Preservation: heartbeat ordering is compared only inside each `(DID, service name)` key.
    pub fn latest_valid_by_service_did(
        descriptors: impl IntoIterator<Item = Self>,
        now_ms: u128,
        network_id: u32,
        include_expired: bool,
    ) -> Vec<Self> {
        latest_valid_by_key(
            descriptors,
            Self::registration_key,
            now_ms,
            network_id,
            include_expired,
        )
        .into_values()
        .collect()
    }

    /// Return the key `(DID, service)` of this registration: an exit registers each service it
    /// offers independently.
    pub(crate) fn registration_key(&self) -> (Did, OnionServiceName) {
        (self.did, self.service.clone())
    }
}

impl SignedDescriptor for OnionExitDescriptor {
    type Body = OnionExitDescriptorBody;

    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) -> CoreResult<Vec<u8>> {
        self.signing_data()
    }

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

impl RegistryElement for OnionExitDescriptor {}

/// Result of decoding one onion-exit registry entry.
#[derive(Clone, Debug, Default, Eq, PartialEq)]
pub struct OnionExitDescriptorDecodeReport {
    /// Descriptors that decoded successfully under the total-cutover wire shape.
    pub descriptors: Vec<OnionExitDescriptor>,
    /// Number of registry values explicitly rejected at the decode boundary.
    pub rejected_values: usize,
}

impl OnionExitDescriptorDecodeReport {
    /// Return whether the entry contained values this node could not decode.
    pub const fn has_rejections(&self) -> bool {
        self.rejected_values > 0
    }
}

/// Periodic node-layer registration for onion exit policy.
#[derive(Clone, Debug)]
pub(crate) struct OnionExitRegistration {
    heartbeat_interval: Duration,
    node_type: OnlineNodeType,
    process_epoch: OnionProcessEpochCell,
    clock: SharedClock,
    started_at_ms: u128,
    offer: OnionExitOffer,
    publisher: DhtRegistrationPublisher<Vec<OnionExitDescriptor>>,
}

impl OnionExitRegistration {
    #[cfg(all(test, not(target_family = "wasm")))]
    pub(crate) fn new(
        heartbeat_interval: Duration,
        ttl: Duration,
        node_type: OnlineNodeType,
        offer: OnionExitOffer,
        process_epoch: OnionProcessEpochCell,
    ) -> Self {
        Self::new_with_clock(
            heartbeat_interval,
            ttl,
            node_type,
            offer,
            process_epoch,
            Arc::new(SystemClock),
        )
    }

    pub(crate) fn new_with_clock(
        heartbeat_interval: Duration,
        ttl: Duration,
        node_type: OnlineNodeType,
        offer: OnionExitOffer,
        process_epoch: OnionProcessEpochCell,
        clock: SharedClock,
    ) -> Self {
        let started_at_ms = clock.now_ms();
        Self {
            heartbeat_interval,
            node_type,
            process_epoch,
            clock,
            started_at_ms,
            offer,
            publisher: DhtRegistrationPublisher::new(ONION_EXITS_TOPIC, heartbeat_interval, ttl),
        }
    }

    /// Build this node's signed onion-exit descriptors under the lease `terms`.
    pub fn descriptors_at(
        &self,
        context: &RegistrationContext<'_>,
        terms: LeaseTerms,
    ) -> Result<Vec<OnionExitDescriptor>> {
        self.offer
            .services()
            .iter()
            .cloned()
            .map(|service| self.descriptor_for_service(context, terms, service))
            .collect()
    }

    fn descriptor_for_service(
        &self,
        context: &RegistrationContext<'_>,
        terms: LeaseTerms,
        service: OnionServiceName,
    ) -> Result<OnionExitDescriptor> {
        OnionExitDescriptor::new_signed(
            OnionExitDescriptorBody {
                did: context.did(),
                public_key: context.delegator_verification_pubkey()?,
                delegatee_public_key: context.delegatee_key().delegatee_public_key(),
                process_epoch: self.process_epoch.get(),
                node_type: self.node_type.clone(),
                network_id: context.network_id(),
                service,
                policy: self.offer.policy().clone(),
                started_at_ms: self.started_at_ms,
                fresh_for_ms: terms.fresh_for_ms,
                expires_at_ms: terms.expires_at_ms,
                version: crate::util::build_version(),
            },
            context.message_signer(),
        )
        .map_err(Error::CoreError)
    }

    /// Publish one heartbeat of this node's signed onion-exit descriptors, returning them as
    /// heard now.
    pub async fn publish_descriptors(
        &self,
        context: &RegistrationContext<'_>,
    ) -> Result<Vec<OnionExitDescriptor>> {
        self.publisher
            .publish_lease(context, self.clock.now_ms(), |terms| {
                self.descriptors_at(context, terms)
            })
            .await
    }

    /// Decode onion-exit descriptors from a DHT entry, each heard at its element's dot.
    pub fn decode_descriptors_from_entry(
        entry: &rings_core::dht::entry::Entry,
    ) -> OnionExitDescriptorDecodeReport {
        let mut report = OnionExitDescriptorDecodeReport::default();
        for (value, heard_at_ms) in heard_elements(entry) {
            match OnionExitDescriptor::from_element(value) {
                Ok(descriptor) => report.descriptors.push(descriptor.heard_at(heard_at_ms)),
                Err(error) => {
                    report.rejected_values = report.rejected_values.saturating_add(1);
                    tracing::debug!(
                        "rejected onion-exit descriptor registry value at schema boundary: {error}"
                    );
                }
            }
        }
        report
    }

    /// Decode onion-exit descriptors from a DHT entry, dropping values rejected at the schema boundary.
    pub fn descriptors_from_entry(
        entry: &rings_core::dht::entry::Entry,
    ) -> Vec<OnionExitDescriptor> {
        let report = Self::decode_descriptors_from_entry(entry);
        if report.has_rejections() {
            tracing::warn!(
                rejected_values = report.rejected_values,
                "ignored unsupported onion-exit descriptor registry values"
            );
        }
        report.descriptors
    }
}

#[cfg_attr(rings_browser, async_trait(?Send))]
#[cfg_attr(rings_native, async_trait)]
impl RegistrationTask for OnionExitRegistration {
    fn name(&self) -> &'static str {
        "onion-exit"
    }

    fn interval(&self) -> Duration {
        self.heartbeat_interval
    }

    async fn register_once(&self, context: &RegistrationContext<'_>) -> Result<()> {
        self.publish_descriptors(context).await.map(|_| ())
    }
}

#[cfg(test)]
pub(crate) mod tests;