1use std::borrow::Borrow;
15use std::sync::Arc;
16use std::sync::RwLock;
17use std::time::Duration;
18
19use async_trait::async_trait;
20use rings_core::delegation::DelegateeKey;
21use rings_core::dht::Did;
22use rings_core::domain_tag;
23use rings_core::ecc::PublicKey;
24use rings_core::ecc::VerificationPublicKey;
25use rings_core::error::Error as CoreError;
26use rings_core::error::Result as CoreResult;
27use rings_core::message::DomainTag;
28use rings_core::message::MessageSigner;
29use rings_core::message::MessageVerification;
30use rings_core::utils::SharedClock;
31#[cfg(all(test, not(target_family = "wasm")))]
32use rings_core::utils::SystemClock;
33use serde::Deserialize;
34use serde::Serialize;
35
36use crate::descriptor::heard_elements;
37use crate::descriptor::latest_valid_by_key;
38use crate::descriptor::sign_descriptor_body;
39use crate::descriptor::RegistryElement;
40use crate::descriptor::SignedDescriptor;
41use crate::descriptor::SignedDescriptorBody;
42use crate::error::Error;
43use crate::error::Result;
44use crate::online::OnlineNodeType;
45use crate::registration::DhtRegistrationPublisher;
46use crate::registration::LeaseTerms;
47use crate::registration::RegistrationContext;
48use crate::registration::RegistrationTask;
49
50pub mod circuit;
51pub(crate) mod directory;
52mod entry_guard;
53pub(crate) mod exit_accounting;
54mod failure;
55#[cfg(rings_native)]
56mod gateway;
57#[cfg(any(rings_native, rings_browser))]
58pub mod https;
59pub(crate) mod invoke_accounting;
60pub mod invoke_descriptor;
61mod loop_shape;
62#[cfg(rings_native)]
63pub mod native;
64pub mod pipeline;
65pub mod proxy;
66mod role;
67pub mod route;
68pub(crate) mod runtime;
69pub(crate) mod session;
70pub mod signature;
71pub(crate) mod sphinx;
72pub mod target;
73#[cfg(rings_native)]
74pub mod tcp;
75pub mod udp;
76
77pub use circuit::OnionInvokeBackend;
78pub use circuit::OnionInvokeCall;
79pub use circuit::OnionInvokeFn;
80pub use entry_guard::OnionEntryGuardState;
81pub use entry_guard::OnionEntryGuardStorage;
82pub(crate) use entry_guard::OnionEntryGuards;
83pub use failure::OnionExitFailure;
84pub use failure::OnionRouteError;
85#[cfg(rings_native)]
86pub use gateway::NativeOnionGatewayConnector;
87pub use invoke_descriptor::OnionInvokeDescriptor;
88pub use invoke_descriptor::OnionInvokeDescriptorBody;
89pub use invoke_descriptor::OnionInvokeDescriptorDecodeReport;
90pub use invoke_descriptor::OnionInvokePolicy;
91pub(crate) use invoke_descriptor::OnionInvokeRegistration;
92pub use invoke_descriptor::ONION_INVOKES_TOPIC;
93pub use loop_shape::OnionLoop;
94pub(crate) use loop_shape::OnionLoopRelay;
95pub use loop_shape::OnionLoopRole;
96pub use loop_shape::OnionLoopShape;
97pub(crate) use loop_shape::OnionPipelineSymbols;
98pub use loop_shape::MAX_ONION_LOOP_HOPS;
99pub use loop_shape::MAX_ONION_LOOP_SYMBOLS;
100pub use loop_shape::ONION_SEGMENT_RELAYS;
101pub use pipeline::OnionInvokeArguments;
102pub use pipeline::OnionInvokePipeline;
103pub use pipeline::OnionInvokeStage;
104pub use pipeline::OnionPipeline;
105pub use pipeline::OnionPipelineError;
106pub use pipeline::OnionPipelineTerm;
107pub use pipeline::OnionValueType;
108pub use role::OnionExitOffer;
109pub use role::OnionInvokeOffer;
110pub use role::OnionRole;
111pub(crate) use route::select_onion_route_from_candidates;
112pub use route::OnionPipelineRoute;
113pub use route::OnionPipelineRouteRequest;
114pub use route::OnionRoute;
115pub(crate) use route::OnionRouteCandidates;
116pub use route::OnionRouteHop;
117pub use route::OnionRouteRequest;
118pub use runtime::OnionPipelineHandle;
119pub use signature::OnionBackendName;
120pub use signature::OnionInputType;
121pub use signature::OnionInvokeShape;
122pub use signature::OnionLatencyClass;
123pub use signature::OnionServiceName;
124pub use signature::OnionShape;
125pub use signature::OnionWidthClass;
126pub use signature::ONION_BACKEND_NAME_MAX_BYTES;
127pub use sphinx::class::OnionLoopClass;
128pub use target::OnionProxyTarget;
129pub use target::OnionProxyTargetError;
130#[cfg(rings_native)]
131pub use udp::NativeOnionUdpSession;
132pub use udp::OnionUdpBindConfig;
133pub use udp::OnionUdpBindMode;
134pub use udp::OnionUdpClientFrame;
135pub use udp::OnionUdpPinholeTable;
136pub use udp::OnionUdpServerFrame;
137
138pub const ONION_EXITS_TOPIC: &str = "onion_exits";
140
141#[derive(Clone, Copy, Debug, Deserialize, Eq, Hash, Ord, PartialEq, PartialOrd, Serialize)]
153pub struct OnionProcessEpoch([u8; 16]);
154
155impl OnionProcessEpoch {
156 pub const fn new(bytes: [u8; 16]) -> Self {
158 Self(bytes)
159 }
160
161 pub(crate) const fn to_bytes(self) -> [u8; 16] {
163 self.0
164 }
165
166 pub fn from_rng(rng: &mut impl rand::RngCore) -> Self {
168 let mut bytes = [0_u8; 16];
169 rng.fill_bytes(&mut bytes);
170 Self(bytes)
171 }
172
173 pub fn random() -> Self {
175 Self::from_rng(&mut rings_core::utils::SystemEntropy)
176 }
177}
178
179#[derive(Clone, Debug)]
186pub struct OnionProcessEpochCell(Arc<RwLock<OnionProcessEpoch>>);
187
188impl OnionProcessEpochCell {
189 pub fn new(epoch: OnionProcessEpoch) -> Self {
191 Self(Arc::new(RwLock::new(epoch)))
192 }
193
194 pub fn get(&self) -> OnionProcessEpoch {
196 self.0
197 .read()
198 .map_or_else(|poisoned| *poisoned.into_inner(), |epoch| *epoch)
199 }
200
201 pub(crate) fn renew(&self, epoch: OnionProcessEpoch) {
203 match self.0.write() {
204 Ok(mut current) => *current = epoch,
205 Err(poisoned) => *poisoned.into_inner() = epoch,
206 }
207 }
208}
209
210const DEFAULT_ONION_EXIT_HEARTBEAT_INTERVAL_SECS: u64 = 30;
211const DEFAULT_ONION_EXIT_TTL_SECS: u64 = 90;
212const ONION_EXIT_DESCRIPTOR_DOMAIN_TAG: DomainTag = domain_tag!("rings-node:onion-exit-descriptor");
214
215pub(crate) const fn default_onion_exit_heartbeat_interval_secs() -> u64 {
217 DEFAULT_ONION_EXIT_HEARTBEAT_INTERVAL_SECS
218}
219
220pub(crate) const fn default_onion_exit_ttl_secs() -> u64 {
222 DEFAULT_ONION_EXIT_TTL_SECS
223}
224
225pub(crate) const fn default_advertise_onion_relay() -> bool {
227 false
228}
229
230pub(crate) const fn default_advertise_onion_exit() -> bool {
232 false
233}
234
235pub fn default_onion_exit_services() -> Vec<OnionServiceName> {
238 OnionServiceName::world_facing().collect()
239}
240
241pub fn https_onion_exit_services() -> Vec<OnionServiceName> {
243 vec![OnionServiceName::https()]
244}
245
246pub fn default_onion_exit_policy() -> OnionExitPolicy {
248 OnionExitPolicy::default()
249}
250
251#[derive(Clone, Debug, Default, Deserialize, Serialize, Eq, PartialEq)]
256#[serde(deny_unknown_fields)]
257pub struct OnionExitPolicy {
258 pub allowed_targets: Vec<OnionExitTarget>,
260 pub denied_targets: Vec<OnionExitTarget>,
262 pub max_sessions: u32,
264 pub max_bytes_per_minute: u64,
266}
267
268#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
282#[serde(try_from = "String", into = "String")]
283pub struct OnionExitTarget(OnionExitTargetPattern);
284
285#[derive(Clone, Debug, Eq, PartialEq)]
287enum OnionExitTargetPattern {
288 Any,
290 AnyHost(u16),
292 Authority(OnionProxyTarget),
294}
295
296impl OnionExitTarget {
297 const WILDCARD: &'static str = "*";
299
300 pub fn parse(target: impl AsRef<str>) -> Result<Self> {
302 let raw = target.as_ref().trim();
303 let invalid = |error: &dyn std::fmt::Display| {
304 Error::InvalidConfig(format!(
305 "invalid onion exit target {:?}; expected host:port, *:port or *:*: {error}",
306 target.as_ref()
307 ))
308 };
309 let pattern = match raw.split_once(':') {
310 _ if raw == Self::WILDCARD => OnionExitTargetPattern::Any,
311 Some((Self::WILDCARD, Self::WILDCARD)) => OnionExitTargetPattern::Any,
312 Some((Self::WILDCARD, port)) => match port.parse::<u16>() {
313 Ok(0) => return Err(invalid(&OnionProxyTargetError::ZeroPort)),
314 Ok(port) => OnionExitTargetPattern::AnyHost(port),
315 Err(_) => return Err(invalid(&OnionProxyTargetError::InvalidPort)),
316 },
317 _ => OnionExitTargetPattern::Authority(
318 OnionProxyTarget::parse_authority(raw).map_err(|error| invalid(&error))?,
319 ),
320 };
321 Ok(Self(pattern))
322 }
323
324 pub fn matches(&self, target: &OnionProxyTarget) -> bool {
326 match &self.0 {
327 OnionExitTargetPattern::Any => true,
328 OnionExitTargetPattern::AnyHost(port) => target.port() == *port,
329 OnionExitTargetPattern::Authority(authority) => authority == target,
330 }
331 }
332
333 pub fn is_public_ip_literal_authority(&self) -> bool {
335 matches!(
336 &self.0,
337 OnionExitTargetPattern::Authority(target)
338 if target::validate_public_ip_literal(target).is_ok()
339 )
340 }
341}
342
343impl std::fmt::Display for OnionExitTarget {
344 fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
346 match &self.0 {
347 OnionExitTargetPattern::Any => write!(formatter, "*:*"),
348 OnionExitTargetPattern::AnyHost(port) => write!(formatter, "*:{port}"),
349 OnionExitTargetPattern::Authority(authority) => {
350 formatter.write_str(authority.authority().as_str())
351 }
352 }
353 }
354}
355
356impl TryFrom<String> for OnionExitTarget {
357 type Error = String;
358
359 fn try_from(value: String) -> std::result::Result<Self, Self::Error> {
360 Self::parse(&value).map_err(|error| error.to_string())
361 }
362}
363
364impl From<OnionExitTarget> for String {
365 fn from(target: OnionExitTarget) -> Self {
366 target.to_string()
367 }
368}
369
370impl OnionExitPolicy {
371 pub fn from_target_strings(
373 allowed_targets: Vec<String>,
374 denied_targets: Vec<String>,
375 ) -> Result<Self> {
376 Ok(Self {
377 allowed_targets: parse_exit_targets(allowed_targets)?,
378 denied_targets: parse_exit_targets(denied_targets)?,
379 ..Self::default()
380 })
381 }
382
383 pub fn is_closed(&self) -> bool {
385 self.allowed_targets.is_empty()
386 }
387
388 pub fn validate_targets(&self) -> Result<()> {
390 if self.is_closed() {
391 return Err(Error::InvalidConfig(
392 "advertise_onion_exit requires at least one valid onion_exit_policy allowed target"
393 .to_string(),
394 ));
395 }
396 Ok(())
397 }
398
399 pub fn validate_browser_targets(&self) -> Result<()> {
402 self.validate_targets()?;
403 if let Some(target) = self
404 .allowed_targets
405 .iter()
406 .find(|target| !target.is_public_ip_literal_authority())
407 {
408 return Err(Error::InvalidConfig(format!(
409 "browser HTTPS onion exit policy only supports public IP-literal allowed_targets, got {target}"
410 )));
411 }
412 Ok(())
413 }
414
415 pub fn allows_target(&self, target: &OnionProxyTarget) -> bool {
418 !self.is_closed() && !self.denies(target) && self.allows(target)
419 }
420
421 pub fn allows_udp_bind(&self, mode: OnionUdpBindMode) -> bool {
429 if self.is_closed()
430 || self
431 .denied_targets
432 .iter()
433 .any(|denied| matches!(denied.0, OnionExitTargetPattern::Any))
434 {
435 return false;
436 }
437 self.allowed_targets.iter().any(|allowed| match &allowed.0 {
438 OnionExitTargetPattern::Any => true,
439 OnionExitTargetPattern::AnyHost(port) => !self.denied_targets.iter().any(|denied| {
440 matches!(
441 denied.0,
442 OnionExitTargetPattern::AnyHost(denied_port) if denied_port == *port
443 )
444 }),
445 OnionExitTargetPattern::Authority(authority) => {
446 authority
447 .host()
448 .parse::<std::net::IpAddr>()
449 .is_ok_and(|ip| ip.is_ipv6() == mode.is_ipv6())
450 && !self.denies(authority)
451 }
452 })
453 }
454
455 fn allows(&self, target: &OnionProxyTarget) -> bool {
457 self.allowed_targets
458 .iter()
459 .any(|allowed| allowed.matches(target))
460 }
461
462 fn denies(&self, target: &OnionProxyTarget) -> bool {
464 self.denied_targets
465 .iter()
466 .any(|denied| denied.matches(target))
467 }
468}
469
470fn parse_exit_targets(targets: Vec<String>) -> Result<Vec<OnionExitTarget>> {
471 targets
472 .into_iter()
473 .map(OnionExitTarget::parse)
474 .collect::<Result<Vec<_>>>()
475}
476
477#[derive(Clone, Debug, Deserialize, Serialize, Eq, PartialEq)]
479pub struct OnionExitDescriptorBody {
480 pub did: Did,
482 pub public_key: VerificationPublicKey,
484 pub delegatee_public_key: PublicKey<33>,
486 pub process_epoch: OnionProcessEpoch,
488 pub node_type: OnlineNodeType,
490 pub network_id: u32,
492 pub service: OnionServiceName,
494 pub policy: OnionExitPolicy,
496 pub started_at_ms: u128,
498 pub fresh_for_ms: u64,
501 pub expires_at_ms: u128,
503 pub version: String,
505}
506
507impl OnionExitDescriptorBody {
508 fn body_ref(&self) -> OnionExitDescriptorBodyRef<'_> {
509 OnionExitDescriptorBodyRef {
510 did: self.did,
511 public_key: &self.public_key,
512 delegatee_public_key: &self.delegatee_public_key,
513 process_epoch: self.process_epoch,
514 node_type: &self.node_type,
515 network_id: self.network_id,
516 service: &self.service,
517 policy: &self.policy,
518 started_at_ms: self.started_at_ms,
519 fresh_for_ms: self.fresh_for_ms,
520 expires_at_ms: self.expires_at_ms,
521 version: self.version.as_str(),
522 }
523 }
524
525 fn signing_data(&self) -> CoreResult<Vec<u8>> {
526 self.body_ref().signing_data()
527 }
528}
529
530impl SignedDescriptorBody for OnionExitDescriptorBody {
531 type Descriptor = OnionExitDescriptor;
532
533 const DOMAIN_TAG: DomainTag = ONION_EXIT_DESCRIPTOR_DOMAIN_TAG;
534
535 fn body_did(&self) -> Did {
536 self.did
537 }
538
539 fn body_public_key(&self) -> &VerificationPublicKey {
540 &self.public_key
541 }
542
543 fn body_network_id(&self) -> u32 {
544 self.network_id
545 }
546
547 fn body_signing_data(&self) -> CoreResult<Vec<u8>> {
548 self.signing_data()
549 }
550
551 fn into_signed_descriptor(self, signature: MessageVerification) -> Self::Descriptor {
552 OnionExitDescriptor {
553 did: self.did,
554 public_key: self.public_key,
555 delegatee_public_key: self.delegatee_public_key,
556 process_epoch: self.process_epoch,
557 node_type: self.node_type,
558 network_id: self.network_id,
559 service: self.service,
560 policy: self.policy,
561 started_at_ms: self.started_at_ms,
562 heartbeat_at_ms: 0,
563 fresh_for_ms: self.fresh_for_ms,
564 expires_at_ms: self.expires_at_ms,
565 version: self.version,
566 signature,
567 }
568 }
569}
570
571#[derive(Serialize)]
572struct OnionExitDescriptorBodyRef<'a> {
573 did: Did,
574 public_key: &'a VerificationPublicKey,
575 delegatee_public_key: &'a PublicKey<33>,
576 process_epoch: OnionProcessEpoch,
577 node_type: &'a OnlineNodeType,
578 network_id: u32,
579 service: &'a OnionServiceName,
580 policy: &'a OnionExitPolicy,
581 started_at_ms: u128,
582 fresh_for_ms: u64,
583 expires_at_ms: u128,
584 version: &'a str,
585}
586
587impl OnionExitDescriptorBodyRef<'_> {
588 fn signing_data(&self) -> CoreResult<Vec<u8>> {
589 rings_codec::serialize(self).map_err(CoreError::CodecSerialize)
590 }
591}
592
593#[derive(Clone, Debug, Deserialize, Serialize, Eq, PartialEq)]
595pub struct OnionExitDescriptor {
596 pub did: Did,
598 pub public_key: VerificationPublicKey,
600 pub delegatee_public_key: PublicKey<33>,
602 pub process_epoch: OnionProcessEpoch,
604 pub node_type: OnlineNodeType,
606 pub network_id: u32,
608 pub service: OnionServiceName,
610 pub policy: OnionExitPolicy,
612 pub started_at_ms: u128,
614 #[serde(skip)]
618 pub heartbeat_at_ms: u128,
619 pub fresh_for_ms: u64,
621 pub expires_at_ms: u128,
623 pub version: String,
625 pub signature: MessageVerification,
627}
628
629impl OnionExitDescriptor {
630 pub fn new_signed(
632 body: OnionExitDescriptorBody,
633 signer: MessageSigner<impl Borrow<DelegateeKey>>,
634 ) -> CoreResult<Self> {
635 sign_descriptor_body(
636 body,
637 signer,
638 "onion exit descriptor DID/public key/session mismatch",
639 )
640 }
641
642 fn body_ref(&self) -> OnionExitDescriptorBodyRef<'_> {
643 let Self {
644 did,
645 public_key,
646 delegatee_public_key,
647 process_epoch,
648 node_type,
649 network_id,
650 service,
651 policy,
652 started_at_ms,
653 heartbeat_at_ms: _,
654 fresh_for_ms,
655 expires_at_ms,
656 version,
657 signature: _,
658 } = self;
659
660 OnionExitDescriptorBodyRef {
661 did: *did,
662 public_key,
663 delegatee_public_key,
664 process_epoch: *process_epoch,
665 node_type,
666 network_id: *network_id,
667 service,
668 policy,
669 started_at_ms: *started_at_ms,
670 fresh_for_ms: *fresh_for_ms,
671 expires_at_ms: *expires_at_ms,
672 version: version.as_str(),
673 }
674 }
675
676 fn signing_data(&self) -> CoreResult<Vec<u8>> {
677 self.body_ref().signing_data()
678 }
679
680 pub fn offers_service(&self, service: &str) -> bool {
684 self.service.matches(service)
685 }
686
687 pub fn verify_signature(&self, network_id: u32) -> bool {
689 self.descriptor_verify_signature(network_id)
690 }
691
692 pub fn is_expired_at(&self, now_ms: u128) -> bool {
695 self.descriptor_is_expired_at(now_ms)
696 }
697
698 pub fn is_live_at(&self, now_ms: u128, network_id: u32) -> bool {
701 self.descriptor_is_live_at(now_ms, network_id)
702 }
703
704 pub fn latest_valid_by_service_did(
709 descriptors: impl IntoIterator<Item = Self>,
710 now_ms: u128,
711 network_id: u32,
712 include_expired: bool,
713 ) -> Vec<Self> {
714 latest_valid_by_key(
715 descriptors,
716 Self::registration_key,
717 now_ms,
718 network_id,
719 include_expired,
720 )
721 .into_values()
722 .collect()
723 }
724
725 pub(crate) fn registration_key(&self) -> (Did, OnionServiceName) {
728 (self.did, self.service.clone())
729 }
730}
731
732impl SignedDescriptor for OnionExitDescriptor {
733 type Body = OnionExitDescriptorBody;
734
735 fn descriptor_did(&self) -> Did {
736 self.did
737 }
738
739 fn descriptor_public_key(&self) -> &VerificationPublicKey {
740 &self.public_key
741 }
742
743 fn descriptor_network_id(&self) -> u32 {
744 self.network_id
745 }
746
747 fn descriptor_signature(&self) -> &MessageVerification {
748 &self.signature
749 }
750
751 fn descriptor_heartbeat_at_ms(&self) -> u128 {
752 self.heartbeat_at_ms
753 }
754
755 fn descriptor_expires_at_ms(&self) -> u128 {
756 self.expires_at_ms
757 }
758
759 fn descriptor_fresh_for_ms(&self) -> u64 {
760 self.fresh_for_ms
761 }
762
763 fn descriptor_signing_data(&self) -> CoreResult<Vec<u8>> {
764 self.signing_data()
765 }
766
767 fn heard_at(self, heartbeat_at_ms: u128) -> Self {
768 Self {
769 heartbeat_at_ms,
770 ..self
771 }
772 }
773}
774
775impl RegistryElement for OnionExitDescriptor {}
776
777#[derive(Clone, Debug, Default, Eq, PartialEq)]
779pub struct OnionExitDescriptorDecodeReport {
780 pub descriptors: Vec<OnionExitDescriptor>,
782 pub rejected_values: usize,
784}
785
786impl OnionExitDescriptorDecodeReport {
787 pub const fn has_rejections(&self) -> bool {
789 self.rejected_values > 0
790 }
791}
792
793#[derive(Clone, Debug)]
795pub(crate) struct OnionExitRegistration {
796 heartbeat_interval: Duration,
797 node_type: OnlineNodeType,
798 process_epoch: OnionProcessEpochCell,
799 clock: SharedClock,
800 started_at_ms: u128,
801 offer: OnionExitOffer,
802 publisher: DhtRegistrationPublisher<Vec<OnionExitDescriptor>>,
803}
804
805impl OnionExitRegistration {
806 #[cfg(all(test, not(target_family = "wasm")))]
807 pub(crate) fn new(
808 heartbeat_interval: Duration,
809 ttl: Duration,
810 node_type: OnlineNodeType,
811 offer: OnionExitOffer,
812 process_epoch: OnionProcessEpochCell,
813 ) -> Self {
814 Self::new_with_clock(
815 heartbeat_interval,
816 ttl,
817 node_type,
818 offer,
819 process_epoch,
820 Arc::new(SystemClock),
821 )
822 }
823
824 pub(crate) fn new_with_clock(
825 heartbeat_interval: Duration,
826 ttl: Duration,
827 node_type: OnlineNodeType,
828 offer: OnionExitOffer,
829 process_epoch: OnionProcessEpochCell,
830 clock: SharedClock,
831 ) -> Self {
832 let started_at_ms = clock.now_ms();
833 Self {
834 heartbeat_interval,
835 node_type,
836 process_epoch,
837 clock,
838 started_at_ms,
839 offer,
840 publisher: DhtRegistrationPublisher::new(ONION_EXITS_TOPIC, heartbeat_interval, ttl),
841 }
842 }
843
844 pub fn descriptors_at(
846 &self,
847 context: &RegistrationContext<'_>,
848 terms: LeaseTerms,
849 ) -> Result<Vec<OnionExitDescriptor>> {
850 self.offer
851 .services()
852 .iter()
853 .cloned()
854 .map(|service| self.descriptor_for_service(context, terms, service))
855 .collect()
856 }
857
858 fn descriptor_for_service(
859 &self,
860 context: &RegistrationContext<'_>,
861 terms: LeaseTerms,
862 service: OnionServiceName,
863 ) -> Result<OnionExitDescriptor> {
864 OnionExitDescriptor::new_signed(
865 OnionExitDescriptorBody {
866 did: context.did(),
867 public_key: context.delegator_verification_pubkey()?,
868 delegatee_public_key: context.delegatee_key().delegatee_public_key(),
869 process_epoch: self.process_epoch.get(),
870 node_type: self.node_type.clone(),
871 network_id: context.network_id(),
872 service,
873 policy: self.offer.policy().clone(),
874 started_at_ms: self.started_at_ms,
875 fresh_for_ms: terms.fresh_for_ms,
876 expires_at_ms: terms.expires_at_ms,
877 version: crate::util::build_version(),
878 },
879 context.message_signer(),
880 )
881 .map_err(Error::CoreError)
882 }
883
884 pub async fn publish_descriptors(
887 &self,
888 context: &RegistrationContext<'_>,
889 ) -> Result<Vec<OnionExitDescriptor>> {
890 self.publisher
891 .publish_lease(context, self.clock.now_ms(), |terms| {
892 self.descriptors_at(context, terms)
893 })
894 .await
895 }
896
897 pub fn decode_descriptors_from_entry(
899 entry: &rings_core::dht::entry::Entry,
900 ) -> OnionExitDescriptorDecodeReport {
901 let mut report = OnionExitDescriptorDecodeReport::default();
902 for (value, heard_at_ms) in heard_elements(entry) {
903 match OnionExitDescriptor::from_element(value) {
904 Ok(descriptor) => report.descriptors.push(descriptor.heard_at(heard_at_ms)),
905 Err(error) => {
906 report.rejected_values = report.rejected_values.saturating_add(1);
907 tracing::debug!(
908 "rejected onion-exit descriptor registry value at schema boundary: {error}"
909 );
910 }
911 }
912 }
913 report
914 }
915
916 pub fn descriptors_from_entry(
918 entry: &rings_core::dht::entry::Entry,
919 ) -> Vec<OnionExitDescriptor> {
920 let report = Self::decode_descriptors_from_entry(entry);
921 if report.has_rejections() {
922 tracing::warn!(
923 rejected_values = report.rejected_values,
924 "ignored unsupported onion-exit descriptor registry values"
925 );
926 }
927 report.descriptors
928 }
929}
930
931#[cfg_attr(rings_browser, async_trait(?Send))]
932#[cfg_attr(rings_native, async_trait)]
933impl RegistrationTask for OnionExitRegistration {
934 fn name(&self) -> &'static str {
935 "onion-exit"
936 }
937
938 fn interval(&self) -> Duration {
939 self.heartbeat_interval
940 }
941
942 async fn register_once(&self, context: &RegistrationContext<'_>) -> Result<()> {
943 self.publish_descriptors(context).await.map(|_| ())
944 }
945}
946
947#[cfg(test)]
948pub(crate) mod tests;