1use std::borrow::Borrow;
4
5use rings_core::delegation::DelegateeKey;
6use rings_core::dht::Did;
7use rings_core::dht::RelayCustody;
8use rings_core::domain_tag;
9use rings_core::ecc::PublicKey;
10use rings_core::ecc::VerificationPublicKey;
11use rings_core::error::Error;
12use rings_core::error::Result;
13use rings_core::message::DhtProtocolMode;
14use rings_core::message::DomainTag;
15use rings_core::message::MessageSigner;
16use rings_core::message::MessageVerification;
17use serde::Deserialize;
18use serde::Serialize;
19
20use crate::descriptor::latest_valid_by_did;
21use crate::descriptor::sign_descriptor_body;
22use crate::descriptor::RegistryElement;
23use crate::descriptor::SignedDescriptor;
24use crate::descriptor::SignedDescriptorBody;
25use crate::onion::OnionProcessEpoch;
26
27pub const ONLINE_NODES_TOPIC: &str = "online_nodes";
29const ONLINE_NODE_DESCRIPTOR_DOMAIN_TAG: DomainTag =
31 domain_tag!("rings-node:online-node-descriptor");
32
33#[derive(Clone, Debug, Deserialize, Serialize, Eq, PartialEq)]
35pub enum OnlineNodeType {
36 Browser,
38 Native,
40 Ffi,
42}
43
44#[derive(Clone, Copy, Debug, Default, Deserialize, Serialize, Eq, PartialEq)]
54pub struct OnlineNodeCapabilities {
55 pub onion_relay: Option<OnionProcessEpoch>,
57 pub relay_custody: RelayCustody,
59}
60
61impl OnlineNodeCapabilities {
62 pub const fn onion_relay(epoch: OnionProcessEpoch) -> Self {
64 Self {
65 onion_relay: Some(epoch),
66 relay_custody: RelayCustody::Holds,
67 }
68 }
69}
70
71#[derive(Clone, Debug, Deserialize, Serialize, Eq, PartialEq)]
73pub struct OnlineNodeDescriptorBody {
74 pub did: Did,
76 pub public_key: VerificationPublicKey,
78 pub delegatee_public_key: PublicKey<33>,
80 pub node_type: OnlineNodeType,
82 pub network_id: u32,
84 pub storage_redundancy: u16,
86 pub dht_virtual_nodes: u16,
88 pub capabilities: OnlineNodeCapabilities,
90 pub endpoint_hint: Option<String>,
92 pub started_at_ms: u128,
94 pub fresh_for_ms: u64,
97 pub expires_at_ms: u128,
99 pub version: String,
101}
102
103impl OnlineNodeDescriptorBody {
104 fn body_ref(&self) -> OnlineNodeDescriptorBodyRef<'_> {
105 OnlineNodeDescriptorBodyRef {
106 did: self.did,
107 public_key: &self.public_key,
108 delegatee_public_key: &self.delegatee_public_key,
109 node_type: &self.node_type,
110 network_id: self.network_id,
111 storage_redundancy: self.storage_redundancy,
112 dht_virtual_nodes: self.dht_virtual_nodes,
113 capabilities: self.capabilities,
114 endpoint_hint: &self.endpoint_hint,
115 started_at_ms: self.started_at_ms,
116 fresh_for_ms: self.fresh_for_ms,
117 expires_at_ms: self.expires_at_ms,
118 version: self.version.as_str(),
119 }
120 }
121
122 fn signing_data(&self) -> Result<Vec<u8>> {
123 self.body_ref().signing_data()
124 }
125}
126
127impl SignedDescriptorBody for OnlineNodeDescriptorBody {
128 type Descriptor = OnlineNodeDescriptor;
129
130 const DOMAIN_TAG: DomainTag = ONLINE_NODE_DESCRIPTOR_DOMAIN_TAG;
131
132 fn body_did(&self) -> Did {
133 self.did
134 }
135
136 fn body_public_key(&self) -> &VerificationPublicKey {
137 &self.public_key
138 }
139
140 fn body_network_id(&self) -> u32 {
141 self.network_id
142 }
143
144 fn body_signing_data(&self) -> Result<Vec<u8>> {
145 self.signing_data()
146 }
147
148 fn into_signed_descriptor(self, signature: MessageVerification) -> Self::Descriptor {
149 OnlineNodeDescriptor {
150 did: self.did,
151 public_key: self.public_key,
152 delegatee_public_key: self.delegatee_public_key,
153 node_type: self.node_type,
154 network_id: self.network_id,
155 storage_redundancy: self.storage_redundancy,
156 dht_virtual_nodes: self.dht_virtual_nodes,
157 capabilities: self.capabilities,
158 endpoint_hint: self.endpoint_hint,
159 started_at_ms: self.started_at_ms,
160 heartbeat_at_ms: 0,
161 fresh_for_ms: self.fresh_for_ms,
162 expires_at_ms: self.expires_at_ms,
163 version: self.version,
164 signature,
165 }
166 }
167}
168
169#[derive(Serialize)]
170struct OnlineNodeDescriptorBodyRef<'a> {
171 did: Did,
172 public_key: &'a VerificationPublicKey,
173 delegatee_public_key: &'a PublicKey<33>,
174 node_type: &'a OnlineNodeType,
175 network_id: u32,
176 storage_redundancy: u16,
177 dht_virtual_nodes: u16,
178 capabilities: OnlineNodeCapabilities,
179 endpoint_hint: &'a Option<String>,
180 started_at_ms: u128,
181 fresh_for_ms: u64,
182 expires_at_ms: u128,
183 version: &'a str,
184}
185
186impl OnlineNodeDescriptorBodyRef<'_> {
187 fn signing_data(&self) -> Result<Vec<u8>> {
188 rings_codec::serialize(self).map_err(Error::CodecSerialize)
189 }
190}
191
192#[derive(Clone, Debug, Deserialize, Serialize, Eq, PartialEq)]
194pub struct OnlineNodeDescriptor {
195 pub did: Did,
197 pub public_key: VerificationPublicKey,
199 pub delegatee_public_key: PublicKey<33>,
201 pub node_type: OnlineNodeType,
203 pub network_id: u32,
205 pub storage_redundancy: u16,
207 pub dht_virtual_nodes: u16,
209 pub capabilities: OnlineNodeCapabilities,
211 pub endpoint_hint: Option<String>,
213 pub started_at_ms: u128,
215 #[serde(skip)]
219 pub heartbeat_at_ms: u128,
220 pub fresh_for_ms: u64,
222 pub expires_at_ms: u128,
224 pub version: String,
226 pub signature: MessageVerification,
228}
229
230impl OnlineNodeDescriptor {
231 pub fn new_signed(
233 body: OnlineNodeDescriptorBody,
234 signer: MessageSigner<impl Borrow<DelegateeKey>>,
235 ) -> Result<Self> {
236 sign_descriptor_body(
237 body,
238 signer,
239 "online node descriptor DID/public key/session mismatch",
240 )
241 }
242
243 fn body_ref(&self) -> OnlineNodeDescriptorBodyRef<'_> {
244 let Self {
245 did,
246 public_key,
247 delegatee_public_key,
248 node_type,
249 network_id,
250 storage_redundancy,
251 dht_virtual_nodes,
252 capabilities,
253 endpoint_hint,
254 started_at_ms,
255 heartbeat_at_ms: _,
256 fresh_for_ms,
257 expires_at_ms,
258 version,
259 signature: _,
260 } = self;
261
262 OnlineNodeDescriptorBodyRef {
263 did: *did,
264 public_key,
265 delegatee_public_key,
266 node_type,
267 network_id: *network_id,
268 storage_redundancy: *storage_redundancy,
269 dht_virtual_nodes: *dht_virtual_nodes,
270 capabilities: *capabilities,
271 endpoint_hint,
272 started_at_ms: *started_at_ms,
273 fresh_for_ms: *fresh_for_ms,
274 expires_at_ms: *expires_at_ms,
275 version: version.as_str(),
276 }
277 }
278
279 fn signing_data(&self) -> Result<Vec<u8>> {
280 self.body_ref().signing_data()
281 }
282
283 pub const fn dht_protocol_mode(&self) -> DhtProtocolMode {
285 DhtProtocolMode::new(
286 self.network_id,
287 self.storage_redundancy,
288 self.dht_virtual_nodes,
289 )
290 }
291
292 pub fn matches_dht_protocol(&self, expected: DhtProtocolMode) -> bool {
294 self.dht_protocol_mode().matches(expected)
295 }
296
297 pub fn verify_signature(&self, network_id: u32) -> bool {
305 self.descriptor_verify_signature(network_id)
306 }
307
308 pub fn is_expired_at(&self, now_ms: u128) -> bool {
311 self.descriptor_is_expired_at(now_ms)
312 }
313
314 pub fn is_live_at(&self, now_ms: u128, network_id: u32) -> bool {
318 self.descriptor_is_live_at(now_ms, network_id)
319 }
320
321 pub fn latest_valid_by_did(
323 descriptors: impl IntoIterator<Item = Self>,
324 now_ms: u128,
325 network_id: u32,
326 include_expired: bool,
327 ) -> Vec<Self> {
328 latest_valid_by_did(descriptors, now_ms, network_id, include_expired)
329 }
330}
331
332impl SignedDescriptor for OnlineNodeDescriptor {
333 type Body = OnlineNodeDescriptorBody;
334
335 fn descriptor_did(&self) -> Did {
336 self.did
337 }
338
339 fn descriptor_public_key(&self) -> &VerificationPublicKey {
340 &self.public_key
341 }
342
343 fn descriptor_network_id(&self) -> u32 {
344 self.network_id
345 }
346
347 fn descriptor_signature(&self) -> &MessageVerification {
348 &self.signature
349 }
350
351 fn descriptor_heartbeat_at_ms(&self) -> u128 {
352 self.heartbeat_at_ms
353 }
354
355 fn descriptor_expires_at_ms(&self) -> u128 {
356 self.expires_at_ms
357 }
358
359 fn descriptor_fresh_for_ms(&self) -> u64 {
360 self.fresh_for_ms
361 }
362
363 fn descriptor_signing_data(&self) -> Result<Vec<u8>> {
364 self.signing_data()
365 }
366
367 fn heard_at(self, heartbeat_at_ms: u128) -> Self {
368 Self {
369 heartbeat_at_ms,
370 ..self
371 }
372 }
373}
374
375impl RegistryElement for OnlineNodeDescriptor {}
376
377#[cfg(test)]
378mod tests {
379 use rings_core::consts::TS_OFFSET_TOLERANCE_MS;
380 use rings_core::delegation::DelegateeKey;
381 use rings_core::ecc::SecretKey;
382
383 use super::*;
384 use crate::tests::TEST_NETWORK_ID;
385
386 fn test_delegatee_key(secret: &SecretKey) -> Result<DelegateeKey> {
389 DelegateeKey::new_with_seckey_at(secret, u64::MAX, 0)
390 }
391
392 fn descriptor_at(
395 heartbeat_at_ms: u128,
396 fresh_for_ms: u64,
397 expires_at_ms: u128,
398 ) -> Result<OnlineNodeDescriptor> {
399 let key = SecretKey::random();
400 let delegatee_key = test_delegatee_key(&key)?;
401 Ok(
402 descriptor_of(&delegatee_key, "test", fresh_for_ms, expires_at_ms)?
403 .heard_at(heartbeat_at_ms),
404 )
405 }
406
407 fn descriptor_of(
410 delegatee_key: &DelegateeKey,
411 version: &str,
412 fresh_for_ms: u64,
413 expires_at_ms: u128,
414 ) -> Result<OnlineNodeDescriptor> {
415 let did = delegatee_key.delegator_did();
416 OnlineNodeDescriptor::new_signed(
417 OnlineNodeDescriptorBody {
418 did,
419 public_key: delegatee_key.delegation().delegator_verification_pubkey()?,
420 delegatee_public_key: delegatee_key.delegatee_public_key(),
421 node_type: OnlineNodeType::Native,
422 network_id: 1,
423 storage_redundancy: 6,
424 dht_virtual_nodes: 0,
425 capabilities: OnlineNodeCapabilities::default(),
426 endpoint_hint: None,
427 started_at_ms: 10,
428 fresh_for_ms,
429 expires_at_ms,
430 version: version.to_string(),
431 },
432 MessageSigner::new(delegatee_key, TEST_NETWORK_ID),
433 )
434 }
435
436 #[test]
440 fn test_latest_valid_by_did_breaks_an_equal_lease_by_content() -> Result<()> {
441 let account = SecretKey::random();
442 let delegatee_key = test_delegatee_key(&account)?;
443 let other_delegatee_key = test_delegatee_key(&account)?;
444 let one = descriptor_of(&delegatee_key, "test", 100, 200)?.heard_at(20);
445 let other_process = descriptor_of(&other_delegatee_key, "test", 100, 200)?.heard_at(20);
446 assert_eq!(other_process.did, one.did);
447 assert_ne!(other_process, one);
448
449 let forward = OnlineNodeDescriptor::latest_valid_by_did(
450 [one.clone(), other_process.clone()],
451 50,
452 TEST_NETWORK_ID,
453 false,
454 );
455 let reverse = OnlineNodeDescriptor::latest_valid_by_did(
456 [other_process, one],
457 50,
458 TEST_NETWORK_ID,
459 false,
460 );
461 assert_eq!(forward, reverse);
462 assert_eq!(forward.len(), 1);
463 Ok(())
464 }
465
466 #[test]
467 fn test_descriptor_signature_covers_mutable_fields() -> Result<()> {
468 let mut descriptor = descriptor_at(20, 10, 30)?;
469 assert!(descriptor.verify_signature(TEST_NETWORK_ID));
470
471 descriptor.node_type = OnlineNodeType::Browser;
472 assert!(!descriptor.verify_signature(TEST_NETWORK_ID));
473 descriptor = descriptor_at(20, 10, 30)?;
474 descriptor.storage_redundancy = 7;
475 assert!(!descriptor.verify_signature(TEST_NETWORK_ID));
476 descriptor = descriptor_at(20, 10, 30)?;
477 descriptor.expires_at_ms = 31;
478 assert!(!descriptor.verify_signature(TEST_NETWORK_ID));
479 descriptor = descriptor_at(20, 10, 30)?;
480 descriptor.fresh_for_ms = 11;
481 assert!(!descriptor.verify_signature(TEST_NETWORK_ID));
482 Ok(())
483 }
484
485 #[test]
488 fn test_heard_time_is_neither_signed_nor_encoded() -> Result<()> {
489 let unheard = descriptor_at(0, 10, 30)?;
490 let heard = unheard.clone().heard_at(25);
491 assert!(heard.verify_signature(TEST_NETWORK_ID));
492 let element = heard.to_element()?;
493 assert_eq!(element, unheard.to_element()?);
494 assert_eq!(OnlineNodeDescriptor::from_element(&element)?, unheard);
495 Ok(())
496 }
497
498 #[test]
501 fn test_a_descriptor_is_live_within_its_lease_and_freshness() -> Result<()> {
502 let skew = TS_OFFSET_TOLERANCE_MS;
503 let fresh = descriptor_at(1_000, 90, 10_000)?;
504 assert!(fresh.is_live_at(1_000 + 90 + skew, TEST_NETWORK_ID));
505 assert!(!fresh.is_live_at(1_000 + 90 + skew + 1, TEST_NETWORK_ID));
506
507 let replayed = descriptor_at(10_000, 90, 10_000)?;
508 assert!(replayed.is_live_at(10_000, TEST_NETWORK_ID));
509 let replayed_late = descriptor_at(10_001, 90, 10_000)?;
510 assert!(
511 !replayed_late.is_live_at(10_001, TEST_NETWORK_ID),
512 "a fresh dot never extends a lease past its signed end"
513 );
514 Ok(())
515 }
516
517 #[test]
521 fn test_a_descriptor_with_terms_past_the_lease_is_never_live() -> Result<()> {
522 let lease = crate::descriptor::registry_lease().as_millis();
523 let lease_u64 = u64::try_from(lease).unwrap_or(u64::MAX);
524 let skew = TS_OFFSET_TOLERANCE_MS;
525 let now = 1_000_000;
526
527 let at_bound = descriptor_at(now, lease_u64, now + lease + skew)?;
528 assert!(at_bound.is_live_at(now, TEST_NETWORK_ID));
529 let long_lease = descriptor_at(now, 90_000, now + lease + skew + 1)?;
530 assert!(!long_lease.is_live_at(now, TEST_NETWORK_ID));
531 let long_window = descriptor_at(now, lease_u64 + 1, now + 90_000)?;
532 assert!(!long_window.is_live_at(now, TEST_NETWORK_ID));
533 assert!(
534 long_lease.is_live_at(now + skew + 1, TEST_NETWORK_ID),
535 "a lease within reach of the reader's clock is live again"
536 );
537 Ok(())
538 }
539
540 #[test]
541 fn test_descriptor_round_trips_through_dht_encoding() -> Result<()> {
542 let descriptor = descriptor_at(0, 10, 30)?;
543 let element = descriptor.to_element()?;
544 let decoded = OnlineNodeDescriptor::from_element(&element)?;
545
546 assert_eq!(decoded, descriptor);
547 assert!(decoded.verify_signature(TEST_NETWORK_ID));
548 Ok(())
549 }
550
551 #[test]
555 fn test_a_descriptor_requires_its_delegation_to_be_live_at_now() -> Result<()> {
556 let skew = TS_OFFSET_TOLERANCE_MS;
557 let issued_at = 10_000;
558 let delegation_ttl = 1_000;
559 let key = SecretKey::random();
560 let delegatee_key = DelegateeKey::new_with_seckey_at(&key, delegation_ttl, issued_at)?;
561 let descriptor = descriptor_of(&delegatee_key, "test", 20_000, 25_000)?.heard_at(5_000);
562
563 assert!(!descriptor.is_live_at(issued_at - skew - 1, TEST_NETWORK_ID));
564 assert!(descriptor.is_live_at(issued_at - skew, TEST_NETWORK_ID));
565 assert!(descriptor.is_live_at(issued_at + u128::from(delegation_ttl), TEST_NETWORK_ID));
566 assert!(!descriptor.is_live_at(issued_at + u128::from(delegation_ttl) + 1, TEST_NETWORK_ID));
567 Ok(())
568 }
569
570 #[test]
573 fn test_latest_valid_by_did_filters_expired_and_keeps_the_newest_lease() -> Result<()> {
574 let key = SecretKey::random();
575 let delegatee_key = test_delegatee_key(&key)?;
576 let older = descriptor_of(&delegatee_key, "old", 100, 90)?.heard_at(45);
577 let newer = descriptor_of(&delegatee_key, "new", 100, 100)?.heard_at(40);
578 let other_live = descriptor_at(25, 100, 100)?;
579 let expired = descriptor_at(30, 100, 40)?;
580
581 let descriptors = OnlineNodeDescriptor::latest_valid_by_did(
582 vec![
583 older.clone(),
584 newer.clone(),
585 other_live.clone(),
586 expired.clone(),
587 ],
588 50,
589 TEST_NETWORK_ID,
590 false,
591 );
592
593 assert_eq!(descriptors.len(), 2);
594 assert!(descriptors.iter().any(|descriptor| descriptor == &newer));
595 assert!(descriptors
596 .iter()
597 .any(|descriptor| descriptor == &other_live));
598
599 let with_expired = OnlineNodeDescriptor::latest_valid_by_did(
600 vec![older, newer, other_live, expired],
601 50,
602 TEST_NETWORK_ID,
603 true,
604 );
605 assert_eq!(with_expired.len(), 3);
606 Ok(())
607 }
608}