Skip to main content

rings_node/
registration.rs

1//! Node-layer DHT registration tasks.
2//!
3//! A registration task is a built-in periodic node-side publisher. The shared publisher owns
4//! the heartbeat of the online-node, onion-exit and DNS-relay service registries.
5//!
6//! Boundedness (#918): a registry carrier is a data topic, so each descriptor expires
7//! individually at its dot's issue time plus the data element horizon
8//! `H = EntryKind::Data.max_lifetime_ms()` unless it is written again. A descriptor is a signed
9//! lease of length `Λ` (`registry_lease`) whose bytes are fixed, so a heartbeat re-appends
10//! the same bytes, which raises their dot and writes no remove, and reads nothing. A registrant
11//! therefore writes no remove at all, and leaves at most `⌈H / (Λ − 2I)⌉ + 1` descriptors within
12//! the horizon (13 at the defaults); the element cap keeps the newest dots, so superseded leases,
13//! which no heartbeat refreshes, are the first it drops. No publisher compacts; a reset floor
14//! stamped by one owner would erase every concurrent descriptor that owner never received
15//! (#867).
16//!
17//! Ghost bound (removal-stability paper, Prop. 10): a registrant that stops at `t_s` is listed
18//! until at most `t_s + T + σ` while nobody re-appends its bytes, and until at most its signed
19//! lease end `ℓ ≤ t_s + Λ` against any writer or syncer.
20//!
21//! Trigger (#855): a registration publishes at every heartbeat, and once more at its node's
22//! first admitted edge after a heartbeat that began with none (`republish_due`). Such a
23//! heartbeat settled at the node alone, and the early publish routes the same lease through the
24//! edge to the registry's owners. It is a heartbeat of the lease like any other, so the
25//! boundedness law and the ghost bound hold as stated.
26
27use std::sync::Arc;
28use std::sync::Mutex;
29use std::sync::PoisonError;
30use std::time::Duration;
31
32use async_trait::async_trait;
33use bytes::Bytes;
34use futures::lock::Mutex as AsyncMutex;
35use rings_core::delegation::DelegateeKey;
36use rings_core::dht::Did;
37use rings_core::dht::RelayCustody;
38use rings_core::ecc::PublicKey;
39use rings_core::ecc::VerificationPublicKey;
40use rings_core::lifecycle::StopToken;
41use rings_core::message::ChordStorageInterface;
42use rings_core::message::MessageSigner;
43use rings_core::message::ScopedStorage;
44use rings_core::swarm::storage_api::StoreReceipt;
45use rings_core::utils::SharedClock;
46use rings_core::utils::SystemClock;
47use rings_runtime::MaybeSendSync;
48
49use crate::descriptor::heard_descriptors;
50use crate::descriptor::registry_lease;
51use crate::descriptor::RegistryElement;
52use crate::descriptor::SignedDescriptor;
53use crate::error::Error;
54use crate::error::Result;
55use crate::onion::OnionProcessEpochCell;
56use crate::online::OnlineNodeCapabilities;
57use crate::online::OnlineNodeDescriptor;
58use crate::online::OnlineNodeDescriptorBody;
59use crate::online::OnlineNodeType;
60use crate::online::ONLINE_NODES_TOPIC;
61use crate::processor::stoppable_storage_error;
62use crate::processor::Processor;
63
64const DEFAULT_ONLINE_NODE_HEARTBEAT_INTERVAL_SECS: u64 = 30;
65const DEFAULT_ONLINE_NODE_TTL_SECS: u64 = 90;
66
67/// Default online-node registry heartbeat interval in seconds.
68pub(crate) const fn default_online_node_heartbeat_interval_secs() -> u64 {
69    DEFAULT_ONLINE_NODE_HEARTBEAT_INTERVAL_SECS
70}
71
72/// Default online-node registry descriptor TTL in seconds.
73pub(crate) const fn default_online_node_ttl_secs() -> u64 {
74    DEFAULT_ONLINE_NODE_TTL_SECS
75}
76
77/// Default runtime family advertised in the online-node registry.
78///
79/// FFI providers override this explicitly at runtime via [`ProcessorConfig::online_node_type`] so
80/// building the workspace with `--features ffi` or `--all-features` never taints native daemon
81/// descriptors.
82pub(crate) fn default_online_node_type() -> OnlineNodeType {
83    #[cfg(all(feature = "browser", target_family = "wasm"))]
84    {
85        OnlineNodeType::Browser
86    }
87    #[cfg(not(all(feature = "browser", target_family = "wasm")))]
88    {
89        OnlineNodeType::Native
90    }
91}
92
93/// Default node presence advertisement enablement.
94pub(crate) const fn default_advertise_presence() -> bool {
95    true
96}
97
98/// The heartbeat interval `I` below which a registry stays fresh: half the lease, `Λ / 2`.
99///
100/// Below it a lease spans more than two heartbeats, so the publisher renews it at most once per
101/// `Λ − 2I` and a registrant leaves a bounded number of descriptors (the boundedness law). Each
102/// append requests the data default lifetime `L = Λ` for the carrier, stamped on the publisher's
103/// clock, which an owner whose clock runs up to `σ = TS_OFFSET_TOLERANCE_MS` ahead retires at
104/// `L − σ`; `Λ / 2 < L − σ`, so the carrier also outlives every gap between heartbeats, a failed
105/// one included (`2I < Λ`).
106pub fn registry_refresh_bound() -> Duration {
107    registry_lease() / 2
108}
109
110/// Whether the publish after one that began with `edges_at_start` admitted edges may come
111/// before its heartbeat (#855): only after a heartbeat that began with none, which settled at
112/// this node alone and reached no registry owner. An early publish arms nothing.
113///
114/// ```text
115///   armed(heartbeat, e₀) = heartbeat ∧ e₀ = 0
116/// ```
117pub(crate) const fn early_publish_armed(heartbeat: bool, edges_at_start: usize) -> bool {
118    heartbeat && edges_at_start == 0
119}
120
121/// Whether an armed registration publishes now, before its heartbeat (#855): it has an admitted
122/// edge, through which a publish reaches the registry's owners. A first registration made before
123/// the node joined the overlay is thus published again at its first edge, not one heartbeat
124/// later.
125///
126/// Law (first edge): only a heartbeat arms the trigger and the early publish disarms it, so
127/// under any sequence of admissions and retirements a registration publishes at most once
128/// between two heartbeats beyond them. An early publish is an ordinary heartbeat of the lease
129/// (the heartbeat law of [`DhtRegistrationPublisher`]): it raises the dots of the same bytes, so
130/// the boundedness law, the freshness window `T` and the lease end `ℓ` are unchanged.
131///
132/// ```text
133///   republish_due(armed, e) = armed ∧ e ≥ 1
134/// ```
135pub(crate) const fn republish_due(armed: bool, admitted_edges: usize) -> bool {
136    armed && admitted_edges > 0
137}
138
139/// Validate a registry's scheduling when the switch `advertise_setting` enables it: the
140/// heartbeat interval `{registry}_heartbeat_interval` is below the descriptor TTL
141/// `{registry}_ttl` and below [`registry_refresh_bound`]. `registry` is the configuration-key
142/// prefix of the registry the error names.
143pub(crate) fn validate_registration_timing(
144    registry: &str,
145    advertise_setting: &str,
146    advertised: bool,
147    heartbeat_interval: Duration,
148    ttl: Duration,
149) -> Result<()> {
150    if !advertised {
151        return Ok(());
152    }
153    let keys = TimingKeys {
154        heartbeat_interval: &format!("{registry}_heartbeat_interval"),
155        ttl: &format!("{registry}_ttl"),
156        enabled_by: Some(advertise_setting),
157    };
158    validate_schedule(&keys, heartbeat_interval, ttl)
159}
160
161/// The settings that schedule one registry, as its timing errors name them.
162pub struct TimingKeys<'a> {
163    /// The setting of the heartbeat interval.
164    pub heartbeat_interval: &'a str,
165    /// The setting of the descriptor time-to-live.
166    pub ttl: &'a str,
167    /// The switch that enables the registry, if one does.
168    pub enabled_by: Option<&'a str>,
169}
170
171/// Validate a registry's scheduling: the heartbeat interval is below the descriptor TTL and
172/// below [`registry_refresh_bound`], and the TTL is at most the registry lease; an error names
173/// the settings in `keys`.
174///
175/// `I < T` keeps a registrant listed between heartbeats: a reader whose clock `t_r` runs at most
176/// `σ` ahead of the publisher's `t_w` lists it while `t_r ≤ τ* + T + σ`, which holds whenever
177/// `t_w − τ* ≤ T`, and `τ*` is stamped on the publisher's clock when the heartbeat is sent; the
178/// heartbeat's propagation to the owners must fit in `T − I`. `T ≤ Λ` because a reader refuses
179/// a longer window as not a registry's (the lease law of `descriptor`).
180pub fn validate_schedule(
181    keys: &TimingKeys<'_>,
182    heartbeat_interval: Duration,
183    ttl: Duration,
184) -> Result<()> {
185    let TimingKeys {
186        heartbeat_interval: heartbeat_key,
187        ttl: ttl_key,
188        enabled_by,
189    } = keys;
190    if heartbeat_interval >= ttl {
191        let condition = enabled_by
192            .map(|switch| format!(" when {switch} is enabled"))
193            .unwrap_or_default();
194        return Err(Error::InvalidConfig(format!(
195            "{heartbeat_key} ({heartbeat_interval:?}) must be less than {ttl_key} \
196             ({ttl:?}){condition}"
197        )));
198    }
199    let lease = registry_lease();
200    if ttl > lease {
201        return Err(Error::InvalidConfig(format!(
202            "{ttl_key} ({ttl:?}) must be at most {lease:?}, the registry lease"
203        )));
204    }
205    let bound = registry_refresh_bound();
206    if heartbeat_interval >= bound {
207        return Err(Error::InvalidConfig(format!(
208            "{heartbeat_key} ({heartbeat_interval:?}) must be less than {bound:?}, half the \
209             registry lease"
210        )));
211    }
212    Ok(())
213}
214
215/// Capability passed to registration tasks.
216///
217/// The context exposes only the node facts and DHT publication operation that a
218/// registry needs. The task does not own the processor.
219pub struct RegistrationContext<'a> {
220    processor: &'a Processor,
221    stop: StopToken,
222    /// When set, every append asks its owners for a store report (#866), and its receipt is
223    /// kept here for the daemon.
224    receipts: Option<Mutex<Vec<StoreReceipt>>>,
225}
226
227impl<'a> RegistrationContext<'a> {
228    pub(crate) fn new(processor: &'a Processor) -> Self {
229        Self::new_with_stop(processor, StopToken::never())
230    }
231
232    pub(crate) const fn new_with_stop(processor: &'a Processor, stop: StopToken) -> Self {
233        Self {
234            processor,
235            stop,
236            receipts: None,
237        }
238    }
239
240    /// This context with every append asking its owners for a store report (#866).
241    pub(crate) fn reporting(mut self) -> Self {
242        self.receipts = Some(Mutex::new(Vec::new()));
243        self
244    }
245
246    /// The receipts of the reported appends made through this context, or `None` when it was
247    /// not reporting.
248    pub(crate) fn into_receipts(self) -> Option<Vec<StoreReceipt>> {
249        self.receipts.map(|receipts| {
250            receipts
251                .into_inner()
252                .unwrap_or_else(PoisonError::into_inner)
253        })
254    }
255
256    /// Return whether the owning registration daemon has requested shutdown.
257    pub fn should_stop(&self) -> bool {
258        self.stop.should_stop()
259    }
260
261    /// Return [`Error::RegistrationStopped`] if the owning registration daemon has requested
262    /// shutdown.
263    pub fn ensure_running(&self) -> Result<()> {
264        if self.should_stop() {
265            return Err(Error::RegistrationStopped);
266        }
267        Ok(())
268    }
269
270    /// Return the local node DID.
271    pub fn did(&self) -> Did {
272        self.processor.did()
273    }
274
275    /// Return the current Unix epoch timestamp in milliseconds from the processor's clock.
276    pub fn now_ms(&self) -> u128 {
277        self.processor.clock().now_ms()
278    }
279
280    /// Return the local network id.
281    pub fn network_id(&self) -> u32 {
282        self.processor.swarm.network_id()
283    }
284
285    /// Return storage redundancy for the local DHT protocol mode.
286    pub fn storage_redundancy(&self) -> u16 {
287        self.processor.swarm.storage_redundancy()
288    }
289
290    /// Return storage virtual-node positions for the local DHT protocol mode.
291    pub fn dht_virtual_nodes(&self) -> u16 {
292        self.processor.swarm.dht_virtual_nodes()
293    }
294
295    /// Return the relay custody the local node declares: whether it holds relay mail.
296    pub fn relay_custody(&self) -> RelayCustody {
297        self.processor.swarm.dht().relay_custody()
298    }
299
300    /// Return the account verification public key.
301    pub fn delegator_verification_pubkey(&self) -> Result<VerificationPublicKey> {
302        self.processor
303            .swarm
304            .delegator_verification_pubkey()
305            .map_err(Error::CoreError)
306    }
307
308    /// Return the local session signing key.
309    pub fn delegatee_key(&self) -> DelegateeKey {
310        self.processor.delegatee_key()
311    }
312
313    /// Return the current process epoch (`OnionProcessEpoch`) of this node.
314    pub fn onion_process_epoch(&self) -> crate::onion::OnionProcessEpoch {
315        self.processor.onion_process_epoch().get()
316    }
317
318    /// The authority that signs this node's descriptors: its delegatee key inside its overlay.
319    pub fn message_signer(&self) -> MessageSigner<DelegateeKey> {
320        MessageSigner::new(self.delegatee_key(), self.network_id())
321    }
322
323    /// The DHT operations of this registration: their rerouting waits end at its stop.
324    fn storage(&self) -> ScopedStorage<'_> {
325        self.processor.swarm.scoped_storage(self.stop.clone())
326    }
327
328    /// Append `data` to `topic`, stopping cooperatively with the registration; a reporting
329    /// context keeps the append's store receipt.
330    pub async fn append_data(&self, topic: &str, data: Bytes) -> Result<()> {
331        let Some(receipts) = &self.receipts else {
332            return self
333                .storage()
334                .storage_append_data(topic, data)
335                .await
336                .map_err(stoppable_storage_error);
337        };
338        let receipt = self
339            .storage()
340            .storage_append_data_reported(topic, data)
341            .await
342            .map_err(stoppable_storage_error)?;
343        receipts
344            .lock()
345            .unwrap_or_else(PoisonError::into_inner)
346            .push(receipt);
347        Ok(())
348    }
349}
350
351/// The terms of a registry lease: the signed lease end `ℓ` and freshness window `T` every
352/// descriptor of the lease carries (see the lease law of `descriptor`).
353#[derive(Clone, Copy, Debug, Eq, PartialEq)]
354pub struct LeaseTerms {
355    /// Freshness window `T` in milliseconds.
356    pub fresh_for_ms: u64,
357    /// Lease end `ℓ` in milliseconds since Unix epoch.
358    pub expires_at_ms: u128,
359}
360
361/// The descriptors one registration publishes under a lease: one (`[D; 1]`) or one per service
362/// (`Vec<D>`), so a caller gets back exactly the shape it built.
363///
364/// Law: `heard_at(t)` maps [`SignedDescriptor::heard_at`] over the descriptors and keeps their
365/// number and order.
366pub trait LeaseDescriptors: Clone {
367    /// The descriptor type.
368    type Descriptor: SignedDescriptor + RegistryElement;
369
370    /// The descriptors, in publication order.
371    fn as_slice(&self) -> &[Self::Descriptor];
372
373    /// The descriptors as heard at `heartbeat_at_ms`.
374    fn heard_at(self, heartbeat_at_ms: u128) -> Self;
375}
376
377impl<D> LeaseDescriptors for [D; 1]
378where D: SignedDescriptor + RegistryElement + Clone
379{
380    type Descriptor = D;
381
382    fn as_slice(&self) -> &[D] {
383        self
384    }
385
386    fn heard_at(self, heartbeat_at_ms: u128) -> Self {
387        self.map(|descriptor| descriptor.heard_at(heartbeat_at_ms))
388    }
389}
390
391impl<D> LeaseDescriptors for Vec<D>
392where D: SignedDescriptor + RegistryElement + Clone
393{
394    type Descriptor = D;
395
396    fn as_slice(&self) -> &[D] {
397        self
398    }
399
400    fn heard_at(self, heartbeat_at_ms: u128) -> Self {
401        self.into_iter()
402            .map(|descriptor| descriptor.heard_at(heartbeat_at_ms))
403            .collect()
404    }
405}
406
407/// The lease a publisher holds: its terms, the delegatee public key that signed it, the signed
408/// bodies it was issued over, its descriptors, and the elements every heartbeat of the lease
409/// re-appends.
410#[derive(Clone, Debug)]
411struct HeldLease<S> {
412    terms: LeaseTerms,
413    delegatee_public_key: PublicKey<33>,
414    bodies: Vec<Vec<u8>>,
415    descriptors: S,
416    elements: Vec<Bytes>,
417}
418
419/// Common publisher for DHT-backed registries: the heartbeat of a signed lease (#918;
420/// removal-stability paper, Law 8).
421///
422/// Law (heartbeat): a heartbeat at `t` appends exactly the current lease's elements, the same
423/// bytes every time, so it raises their dots and writes no remove; it reads nothing. It issues a
424/// new lease, `ℓ' = t + Λ`, only when `t + 2I ≥ ℓ` or when a signed field changed, and appends
425/// the new lease's elements instead; it never removes the old ones, which readers outrank by
426/// their lease and the element horizon retires.
427///
428/// ```text
429///   heartbeat(t):
430///     held ∧ t + 2I < ℓ ∧ bodies(ℓ) = held.bodies ─▶ Extend(held.elements)
431///     otherwise ─▶ held ← sign(bodies(t + Λ)); Extend(held.elements)
432/// ```
433#[derive(Clone, Debug)]
434pub struct DhtRegistrationPublisher<S> {
435    topic: String,
436    /// The renewal margin `2I`: a lease is renewed once fewer than two heartbeats remain in it.
437    renewal_margin_ms: u128,
438    /// The freshness window `T` this registration signs.
439    fresh_for_ms: u64,
440    /// The lease held, if any; its lock serializes only the synchronous lease state transition
441    /// and is released before appending descriptor elements over the DHT (`publish_lease`).
442    held: Arc<AsyncMutex<Option<HeldLease<S>>>>,
443}
444
445impl<S: LeaseDescriptors> DhtRegistrationPublisher<S> {
446    /// A publisher for `topic` whose heartbeat runs every `heartbeat_interval` and whose
447    /// descriptors are fresh for `fresh_for`.
448    pub fn new(
449        topic: impl Into<String>,
450        heartbeat_interval: Duration,
451        fresh_for: Duration,
452    ) -> Self {
453        Self {
454            topic: topic.into(),
455            renewal_margin_ms: heartbeat_interval.as_millis().saturating_mul(2),
456            fresh_for_ms: u64::try_from(fresh_for.as_millis()).unwrap_or(u64::MAX),
457            held: Arc::new(AsyncMutex::new(None)),
458        }
459    }
460
461    /// Publish one heartbeat at `now_ms` of the lease whose descriptors `descriptors_for` signs
462    /// under given terms (the heartbeat law), returning them as heard now.
463    ///
464    /// Each append is rerouted as `Processor::storage_fetch` documents, and its rerouting wait
465    /// ends at the registration's stop.
466    pub async fn publish_lease(
467        &self,
468        context: &RegistrationContext<'_>,
469        now_ms: u128,
470        descriptors_for: impl Fn(LeaseTerms) -> Result<S>,
471    ) -> Result<S> {
472        // Scope `held` strictly around the synchronous lease transition; network/DHT appends run
473        // outside the lock so a slow placement never stalls concurrent heartbeat state checks.
474        let lease = {
475            let mut held = rings_core::utils::SlowLockGuard::acquire(
476                "DhtRegistrationPublisher::held",
477                self.held.lock(),
478            )
479            .await;
480            context.ensure_running()?;
481            let delegatee_public_key = context.delegatee_key().delegatee_public_key();
482            let kept = match held.as_ref() {
483                Some(lease)
484                    if lease.delegatee_public_key == delegatee_public_key
485                        && now_ms.saturating_add(self.renewal_margin_ms)
486                            < lease.terms.expires_at_ms =>
487                {
488                    let bodies = signing_data(descriptors_for(lease.terms)?.as_slice())?;
489                    (bodies == lease.bodies).then(|| lease.clone())
490                }
491                _ => None,
492            };
493            match kept {
494                Some(lease) => lease,
495                None => {
496                    let nominal_expires_at_ms = now_ms.saturating_add(registry_lease().as_millis());
497                    let max_admissible_expires_at_ms = nominal_expires_at_ms
498                        .saturating_add(rings_core::consts::TS_OFFSET_TOLERANCE_MS);
499                    let terms = LeaseTerms {
500                        fresh_for_ms: self.fresh_for_ms,
501                        expires_at_ms: nominal_expires_at_ms
502                            .max(held.as_ref().map_or(0, |previous| {
503                                previous.terms.expires_at_ms.saturating_add(1)
504                            }))
505                            .min(max_admissible_expires_at_ms),
506                    };
507                    let descriptors = descriptors_for(terms)?;
508                    let lease = HeldLease {
509                        terms,
510                        delegatee_public_key,
511                        bodies: signing_data(descriptors.as_slice())?,
512                        elements: descriptors
513                            .as_slice()
514                            .iter()
515                            .map(|descriptor| descriptor.to_element().map_err(Error::CoreError))
516                            .collect::<Result<_>>()?,
517                        descriptors,
518                    };
519                    **held = Some(lease.clone());
520                    lease
521                }
522            }
523        };
524        for element in &lease.elements {
525            context.ensure_running()?;
526            context.append_data(&self.topic, element.clone()).await?;
527        }
528        Ok(lease.descriptors.heard_at(now_ms))
529    }
530}
531
532/// The signed bodies of `descriptors`, which decide whether a lease still describes them.
533fn signing_data<D: SignedDescriptor>(descriptors: &[D]) -> Result<Vec<Vec<u8>>> {
534    descriptors
535        .iter()
536        .map(|descriptor| {
537            descriptor
538                .descriptor_signing_data()
539                .map_err(Error::CoreError)
540        })
541        .collect()
542}
543
544/// Periodic node-layer registration.
545#[cfg_attr(all(feature = "browser", target_family = "wasm"), async_trait(?Send))]
546#[cfg_attr(not(all(feature = "browser", target_family = "wasm")), async_trait)]
547pub trait RegistrationTask: MaybeSendSync {
548    /// Stable name used in logs.
549    fn name(&self) -> &'static str;
550
551    /// Time between registration attempts.
552    fn interval(&self) -> Duration;
553
554    /// Publish one registration heartbeat.
555    async fn register_once(&self, context: &RegistrationContext<'_>) -> Result<()>;
556}
557
558/// Online-node registry task.
559#[derive(Clone, Debug)]
560pub struct OnlineNodeRegistration {
561    heartbeat_interval: Duration,
562    node_type: OnlineNodeType,
563    clock: SharedClock,
564    started_at_ms: u128,
565    endpoint_hint: Option<String>,
566    /// The process epoch this node registers `relay` at, if it relays (#834 D2): read at every
567    /// heartbeat, so a renewed epoch is published by the next one.
568    onion_relay: Option<OnionProcessEpochCell>,
569    publisher: DhtRegistrationPublisher<[OnlineNodeDescriptor; 1]>,
570}
571
572impl OnlineNodeRegistration {
573    /// Create an online-node registration task.
574    pub fn new(
575        heartbeat_interval: Duration,
576        ttl: Duration,
577        node_type: OnlineNodeType,
578        endpoint_hint: Option<String>,
579        onion_relay: Option<OnionProcessEpochCell>,
580    ) -> Self {
581        Self::new_with_clock(
582            heartbeat_interval,
583            ttl,
584            node_type,
585            endpoint_hint,
586            onion_relay,
587            Arc::new(SystemClock),
588        )
589    }
590
591    /// Create an online-node registration task bound to an explicit [`SharedClock`].
592    pub fn new_with_clock(
593        heartbeat_interval: Duration,
594        ttl: Duration,
595        node_type: OnlineNodeType,
596        endpoint_hint: Option<String>,
597        onion_relay: Option<OnionProcessEpochCell>,
598        clock: SharedClock,
599    ) -> Self {
600        let started_at_ms = clock.now_ms();
601        Self {
602            heartbeat_interval,
603            node_type,
604            clock,
605            started_at_ms,
606            endpoint_hint,
607            onion_relay,
608            publisher: DhtRegistrationPublisher::new(ONLINE_NODES_TOPIC, heartbeat_interval, ttl),
609        }
610    }
611
612    /// Build this node's signed descriptor under the lease `terms`.
613    pub(crate) fn descriptor_at(
614        &self,
615        context: &RegistrationContext<'_>,
616        terms: LeaseTerms,
617    ) -> Result<OnlineNodeDescriptor> {
618        OnlineNodeDescriptor::new_signed(
619            OnlineNodeDescriptorBody {
620                did: context.did(),
621                public_key: context.delegator_verification_pubkey()?,
622                delegatee_public_key: context.delegatee_key().delegatee_public_key(),
623                node_type: self.node_type.clone(),
624                network_id: context.network_id(),
625                storage_redundancy: context.storage_redundancy(),
626                dht_virtual_nodes: context.dht_virtual_nodes(),
627                capabilities: OnlineNodeCapabilities {
628                    onion_relay: self.onion_relay.as_ref().map(OnionProcessEpochCell::get),
629                    relay_custody: context.relay_custody(),
630                },
631                endpoint_hint: self.endpoint_hint.clone(),
632                started_at_ms: self.started_at_ms,
633                fresh_for_ms: terms.fresh_for_ms,
634                expires_at_ms: terms.expires_at_ms,
635                version: crate::util::build_version(),
636            },
637            context.message_signer(),
638        )
639        .map_err(Error::CoreError)
640    }
641
642    /// Publish one heartbeat of this node's signed online descriptor, returning it as heard
643    /// now.
644    pub(crate) async fn publish_descriptor(
645        &self,
646        context: &RegistrationContext<'_>,
647    ) -> Result<OnlineNodeDescriptor> {
648        let [descriptor] = self
649            .publisher
650            .publish_lease(context, self.clock.now_ms(), |terms| {
651                self.descriptor_at(context, terms)
652                    .map(|descriptor| [descriptor])
653            })
654            .await?;
655        Ok(descriptor)
656    }
657
658    /// Decode online-node descriptors from a DHT entry, each heard at its element's dot.
659    pub fn descriptors_from_entry(
660        entry: &rings_core::dht::entry::Entry,
661    ) -> Vec<OnlineNodeDescriptor> {
662        heard_descriptors(entry)
663    }
664}
665
666#[cfg_attr(all(feature = "browser", target_family = "wasm"), async_trait(?Send))]
667#[cfg_attr(not(all(feature = "browser", target_family = "wasm")), async_trait)]
668impl RegistrationTask for OnlineNodeRegistration {
669    fn name(&self) -> &'static str {
670        "online-node"
671    }
672
673    fn interval(&self) -> Duration {
674        self.heartbeat_interval
675    }
676
677    async fn register_once(&self, context: &RegistrationContext<'_>) -> Result<()> {
678        self.publish_descriptor(context).await.map(|_| ())
679    }
680}
681
682mod readiness;
683
684pub(crate) use readiness::RegistrationReadiness;
685
686#[cfg(test)]
687mod test_first_edge;
688#[cfg(all(test, rings_native))]
689mod test_lease_and_readiness_model;