Skip to main content

rings_node/dns_relay/
registration.rs

1//! The heartbeat that keeps a node's service descriptor in the DHT.
2//!
3//! A descriptor is a registry element on the node's own [`service_topic`]: a signed lease whose
4//! bytes each heartbeat re-appends ([`DhtRegistrationPublisher::publish_lease`], #918), so the
5//! topic holds one live descriptor per node, written without a remove, and a reader stops
6//! listing it within its freshness window once the node stops. A node that stops serving
7//! publishes an offer with no port and no record, a new lease, which a relay reads as a
8//! withdrawal.
9
10use std::collections::BTreeMap;
11use std::time::Duration;
12
13use async_trait::async_trait;
14use rings_core::ecc::VerificationPublicKey;
15use rings_dns_relay::AnnouncementError;
16use rings_dns_relay::ProxyProtocol;
17
18use super::descriptor::announcement_of;
19use super::descriptor::service_topic;
20use super::descriptor::ServedPort;
21use super::descriptor::ServedTxt;
22use super::descriptor::ServiceDescriptor;
23use super::descriptor::ServiceDescriptorBody;
24use crate::error::Error;
25use crate::error::Result;
26use crate::prelude::rings_core::dht::Did;
27use crate::registration::DhtRegistrationPublisher;
28use crate::registration::LeaseTerms;
29use crate::registration::RegistrationContext;
30use crate::registration::RegistrationTask;
31
32/// What a node offers through DNS relays: the ports it serves, each with how its service learns
33/// a connection's origin, and its TXT records, validated as an announcement, with the timing of
34/// the heartbeat that publishes them.
35#[derive(Clone, Debug, Eq, PartialEq)]
36pub struct ServiceOffer {
37    ports: BTreeMap<u16, ProxyProtocol>,
38    txt: Vec<ServedTxt>,
39    heartbeat_interval: Duration,
40    ttl: Duration,
41}
42
43impl ServiceOffer {
44    /// The offer of `ports` and `txt`, published every `heartbeat_interval` and live for `ttl`.
45    ///
46    /// Post: the descriptor this offer signs converts to a valid
47    /// [`Announcement`](rings_dns_relay::Announcement); a relay never rejects what a node
48    /// publishes.
49    pub fn new(
50        ports: BTreeMap<u16, ProxyProtocol>,
51        txt: Vec<ServedTxt>,
52        heartbeat_interval: Duration,
53        ttl: Duration,
54    ) -> std::result::Result<Self, AnnouncementError> {
55        let offer = Self {
56            ports,
57            txt,
58            heartbeat_interval,
59            ttl,
60        };
61        announcement_of(offer.served_ports(), &offer.txt)?;
62        Ok(offer)
63    }
64
65    /// The ports this offer serves, ascending.
66    pub fn served_ports(&self) -> impl Iterator<Item = ServedPort> + '_ {
67        self.ports.iter().map(|(port, proxy_protocol)| ServedPort {
68            port: *port,
69            proxy_protocol: *proxy_protocol,
70        })
71    }
72
73    /// How often the descriptor is published.
74    pub fn heartbeat_interval(&self) -> Duration {
75        self.heartbeat_interval
76    }
77
78    /// How long each published descriptor is live.
79    pub fn ttl(&self) -> Duration {
80        self.ttl
81    }
82
83    /// The unsigned descriptor body of this offer for `did`, with key `public_key` in overlay
84    /// `network_id`, under the lease `terms`.
85    fn body(
86        &self,
87        did: Did,
88        public_key: VerificationPublicKey,
89        network_id: u32,
90        terms: LeaseTerms,
91    ) -> ServiceDescriptorBody {
92        ServiceDescriptorBody {
93            did,
94            public_key,
95            network_id,
96            ports: self.served_ports().collect(),
97            txt: self.txt.clone(),
98            fresh_for_ms: terms.fresh_for_ms,
99            expires_at_ms: terms.expires_at_ms,
100        }
101    }
102}
103
104/// The registration task publishing a node's service descriptor.
105#[derive(Clone, Debug)]
106pub(crate) struct ServiceRegistration {
107    offer: ServiceOffer,
108    publisher: DhtRegistrationPublisher<[ServiceDescriptor; 1]>,
109}
110
111impl ServiceRegistration {
112    /// The registration of `offer` for the node `did`.
113    pub(crate) fn new(did: Did, offer: ServiceOffer) -> Self {
114        Self {
115            publisher: DhtRegistrationPublisher::new(
116                service_topic(did),
117                offer.heartbeat_interval,
118                offer.ttl,
119            ),
120            offer,
121        }
122    }
123
124    /// This node's signed descriptor under the lease `terms`.
125    pub(crate) fn descriptor_at(
126        &self,
127        context: &RegistrationContext<'_>,
128        terms: LeaseTerms,
129    ) -> Result<ServiceDescriptor> {
130        let body = self.offer.body(
131            context.did(),
132            context.delegator_verification_pubkey()?,
133            context.network_id(),
134            terms,
135        );
136        ServiceDescriptor::new_signed(body, context.message_signer()).map_err(Error::CoreError)
137    }
138}
139
140#[cfg_attr(rings_browser, async_trait(?Send))]
141#[cfg_attr(rings_native, async_trait)]
142impl RegistrationTask for ServiceRegistration {
143    fn name(&self) -> &'static str {
144        "dns-relay-services"
145    }
146
147    fn interval(&self) -> Duration {
148        self.offer.heartbeat_interval
149    }
150
151    async fn register_once(&self, context: &RegistrationContext<'_>) -> Result<()> {
152        self.publisher
153            .publish_lease(context, context.now_ms(), |terms| {
154                self.descriptor_at(context, terms)
155                    .map(|descriptor| [descriptor])
156            })
157            .await
158            .map(drop)
159    }
160}