1use 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
67pub(crate) const fn default_online_node_heartbeat_interval_secs() -> u64 {
69 DEFAULT_ONLINE_NODE_HEARTBEAT_INTERVAL_SECS
70}
71
72pub(crate) const fn default_online_node_ttl_secs() -> u64 {
74 DEFAULT_ONLINE_NODE_TTL_SECS
75}
76
77pub(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
93pub(crate) const fn default_advertise_presence() -> bool {
95 true
96}
97
98pub fn registry_refresh_bound() -> Duration {
107 registry_lease() / 2
108}
109
110pub(crate) const fn early_publish_armed(heartbeat: bool, edges_at_start: usize) -> bool {
118 heartbeat && edges_at_start == 0
119}
120
121pub(crate) const fn republish_due(armed: bool, admitted_edges: usize) -> bool {
136 armed && admitted_edges > 0
137}
138
139pub(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
161pub struct TimingKeys<'a> {
163 pub heartbeat_interval: &'a str,
165 pub ttl: &'a str,
167 pub enabled_by: Option<&'a str>,
169}
170
171pub 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
215pub struct RegistrationContext<'a> {
220 processor: &'a Processor,
221 stop: StopToken,
222 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 pub(crate) fn reporting(mut self) -> Self {
242 self.receipts = Some(Mutex::new(Vec::new()));
243 self
244 }
245
246 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 pub fn should_stop(&self) -> bool {
258 self.stop.should_stop()
259 }
260
261 pub fn ensure_running(&self) -> Result<()> {
264 if self.should_stop() {
265 return Err(Error::RegistrationStopped);
266 }
267 Ok(())
268 }
269
270 pub fn did(&self) -> Did {
272 self.processor.did()
273 }
274
275 pub fn now_ms(&self) -> u128 {
277 self.processor.clock().now_ms()
278 }
279
280 pub fn network_id(&self) -> u32 {
282 self.processor.swarm.network_id()
283 }
284
285 pub fn storage_redundancy(&self) -> u16 {
287 self.processor.swarm.storage_redundancy()
288 }
289
290 pub fn dht_virtual_nodes(&self) -> u16 {
292 self.processor.swarm.dht_virtual_nodes()
293 }
294
295 pub fn relay_custody(&self) -> RelayCustody {
297 self.processor.swarm.dht().relay_custody()
298 }
299
300 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 pub fn delegatee_key(&self) -> DelegateeKey {
310 self.processor.delegatee_key()
311 }
312
313 pub fn onion_process_epoch(&self) -> crate::onion::OnionProcessEpoch {
315 self.processor.onion_process_epoch().get()
316 }
317
318 pub fn message_signer(&self) -> MessageSigner<DelegateeKey> {
320 MessageSigner::new(self.delegatee_key(), self.network_id())
321 }
322
323 fn storage(&self) -> ScopedStorage<'_> {
325 self.processor.swarm.scoped_storage(self.stop.clone())
326 }
327
328 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#[derive(Clone, Copy, Debug, Eq, PartialEq)]
354pub struct LeaseTerms {
355 pub fresh_for_ms: u64,
357 pub expires_at_ms: u128,
359}
360
361pub trait LeaseDescriptors: Clone {
367 type Descriptor: SignedDescriptor + RegistryElement;
369
370 fn as_slice(&self) -> &[Self::Descriptor];
372
373 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#[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#[derive(Clone, Debug)]
434pub struct DhtRegistrationPublisher<S> {
435 topic: String,
436 renewal_margin_ms: u128,
438 fresh_for_ms: u64,
440 held: Arc<AsyncMutex<Option<HeldLease<S>>>>,
443}
444
445impl<S: LeaseDescriptors> DhtRegistrationPublisher<S> {
446 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 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 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
532fn 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#[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 fn name(&self) -> &'static str;
550
551 fn interval(&self) -> Duration;
553
554 async fn register_once(&self, context: &RegistrationContext<'_>) -> Result<()>;
556}
557
558#[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 onion_relay: Option<OnionProcessEpochCell>,
569 publisher: DhtRegistrationPublisher<[OnlineNodeDescriptor; 1]>,
570}
571
572impl OnlineNodeRegistration {
573 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 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 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 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 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;