rings_node/descriptor.rs
1//! Shared helpers for signed DHT descriptors.
2//!
3//! A descriptor is signed by the node's [`MessageSigner`], so its signature is bound to the
4//! signer's overlay exactly like every other message, and verified under the *receiver's*
5//! overlay. The body also carries `network_id` as a signed field; signing refuses a body whose
6//! stated overlay differs from the signer's, so a verified descriptor's stated overlay is the
7//! overlay it was signed for, and a descriptor issued in one overlay does not verify in another.
8//!
9//! Lease law (#918; removal-stability paper, Laws 8 and 9): a descriptor is a signed lease. Its
10//! body signs the lease end `expires_at_ms = ℓ` and the freshness window `fresh_for_ms = T`,
11//! and nothing that changes between heartbeats, so its bytes are fixed for the lease and a
12//! heartbeat re-appends them, which raises their dot without writing a remove. The time a
13//! reader last heard the descriptor, `heartbeat_at_ms = τ*`, is the dot of its element in the
14//! fetched carrier: it is not signed and not encoded, so a re-append or a forged dot can raise
15//! it, but never past the signed `ℓ`. A reader at `t` holds the descriptor live iff it verifies,
16//! its terms are admissible, `ℓ ≤ t + Λ + σ` and `T ≤ Λ` (`registry_lease`), and `t ≤ ℓ` and
17//! `t ≤ τ* + T + σ`. The terms are the signer's choice, so the reader bounds them: a lease longer
18//! than `Λ`, or a window longer than the lease, is never live, and a registrant that stops is
19//! listed at most `Λ + σ` after its last write against any signer, writer or syncer.
20
21use std::borrow::Borrow;
22use std::collections::btree_map::Entry;
23use std::collections::BTreeMap;
24use std::time::Duration;
25
26use bytes::Bytes;
27use rings_core::consts::DEFAULT_TTL_MS;
28use rings_core::consts::TS_OFFSET_TOLERANCE_MS;
29use rings_core::delegation::DelegateeKey;
30use rings_core::dht::entry::Entry as DhtEntry;
31use rings_core::dht::Did;
32use rings_core::ecc::VerificationPublicKey;
33use rings_core::error::Error;
34use rings_core::error::Result;
35use rings_core::message::DomainTag;
36use rings_core::message::MessageSigner;
37use rings_core::message::MessageVerification;
38use rings_core::message::SigningDomain;
39use serde::de::DeserializeOwned;
40use serde::Serialize;
41
42/// The signed fields of one descriptor kind.
43pub trait SignedDescriptorBody: Sized {
44 /// Concrete signed descriptor type produced from `Self`.
45 type Descriptor;
46
47 /// Message family of this descriptor kind.
48 const DOMAIN_TAG: DomainTag;
49
50 /// Return the signer's account DID stated in the body.
51 fn body_did(&self) -> Did;
52 /// Return the signer's account verification public key stated in the body.
53 fn body_public_key(&self) -> &VerificationPublicKey;
54 /// Return the overlay network identifier stated in the body.
55 fn body_network_id(&self) -> u32;
56 /// Canonical byte serialization covered by the descriptor signature.
57 fn body_signing_data(&self) -> Result<Vec<u8>>;
58 /// Assemble the signed descriptor from `self` and `signature`.
59 fn into_signed_descriptor(self, signature: MessageVerification) -> Self::Descriptor;
60}
61
62/// The registry lease `Λ`: the data default lifetime `L`, so a replayed descriptor outlives its
63/// registrant by at most `L` (removal-stability paper, Def. 7), and the bound a reader puts on
64/// every signed lease and freshness window.
65pub const fn registry_lease() -> Duration {
66 Duration::from_millis(DEFAULT_TTL_MS)
67}
68
69/// Sign `body` with the node's authority.
70///
71/// Pre: the body names the signer's account and public key, and states the signer's overlay.
72pub fn sign_descriptor_body<B>(
73 body: B,
74 signer: MessageSigner<impl Borrow<DelegateeKey>>,
75 mismatch_message: &'static str,
76) -> Result<B::Descriptor>
77where
78 B: SignedDescriptorBody,
79{
80 let did = body.body_did();
81 if body.body_public_key().did() != did || signer.delegator_did() != did {
82 return Err(Error::InvalidMessage(mismatch_message.to_string()));
83 }
84 if body.body_network_id() != signer.network_id() {
85 return Err(Error::InvalidMessage(
86 "descriptor states an overlay other than the signer's".to_string(),
87 ));
88 }
89
90 let signature = signer.sign(B::DOMAIN_TAG, &body.body_signing_data()?)?;
91 Ok(body.into_signed_descriptor(signature))
92}
93
94/// A published descriptor: its body plus the signature over it.
95pub trait SignedDescriptor: Sized {
96 /// The body this descriptor was signed from; fixes the message family.
97 type Body: SignedDescriptorBody<Descriptor = Self>;
98
99 /// Return the signer's account DID stated in the descriptor.
100 fn descriptor_did(&self) -> Did;
101 /// Return the signer's account verification public key stated in the descriptor.
102 fn descriptor_public_key(&self) -> &VerificationPublicKey;
103 /// The overlay the body states.
104 fn descriptor_network_id(&self) -> u32;
105 /// Return the signature envelope attached to this descriptor.
106 fn descriptor_signature(&self) -> &MessageVerification;
107 /// When a reader last heard this descriptor, `τ*`: unsigned (see the lease law).
108 fn descriptor_heartbeat_at_ms(&self) -> u128;
109 /// The signed lease end `ℓ`.
110 fn descriptor_expires_at_ms(&self) -> u128;
111 /// The signed freshness window `T`.
112 fn descriptor_fresh_for_ms(&self) -> u64;
113 /// Canonical byte serialization covered by the descriptor signature.
114 fn descriptor_signing_data(&self) -> Result<Vec<u8>>;
115 /// This descriptor as heard at `heartbeat_at_ms`, its element's dot: the one unsigned field.
116 fn heard_at(self, heartbeat_at_ms: u128) -> Self;
117
118 /// Verify the signature under the receiver's overlay `network_id`, the DID/public-key
119 /// binding of the signer, and that the body states that same overlay, so a verified
120 /// descriptor's stated overlay is the overlay it was signed for.
121 fn descriptor_verify_signature(&self, network_id: u32) -> bool {
122 self.descriptor_verify_signature_at(network_id, rings_core::utils::get_epoch_ms())
123 }
124
125 /// Verify the descriptor's signature, stated overlay, and delegation liveness at `at_ms`.
126 fn descriptor_verify_signature_at(&self, network_id: u32, at_ms: u128) -> bool {
127 if self.descriptor_network_id() != network_id {
128 return false;
129 }
130 let did = self.descriptor_did();
131 let public_key = self.descriptor_public_key();
132 let signature = self.descriptor_signature();
133 if public_key.did() != did || signature.delegation.delegator_did() != did {
134 return false;
135 }
136
137 let Ok(delegatee_public_key) = signature.delegation.delegator_verification_pubkey() else {
138 return false;
139 };
140 if &delegatee_public_key != public_key {
141 return false;
142 }
143
144 let Ok(data) = self.descriptor_signing_data() else {
145 return false;
146 };
147 let domain =
148 SigningDomain::new(<Self::Body as SignedDescriptorBody>::DOMAIN_TAG, network_id);
149 signature.verify_at(domain, &data, at_ms)
150 }
151
152 /// The last instant a reader holds this descriptor live: `min(ℓ, τ* + T + σ)`.
153 fn descriptor_live_until_ms(&self) -> u128 {
154 let heard_until = self
155 .descriptor_heartbeat_at_ms()
156 .saturating_add(u128::from(self.descriptor_fresh_for_ms()))
157 .saturating_add(TS_OFFSET_TOLERANCE_MS);
158 self.descriptor_expires_at_ms().min(heard_until)
159 }
160
161 /// Whether this descriptor is no longer live at `now_ms`: its lease ended, or it was not
162 /// heard within its freshness window and the skew tolerance.
163 fn descriptor_is_expired_at(&self, now_ms: u128) -> bool {
164 self.descriptor_live_until_ms() < now_ms
165 }
166
167 /// Whether the signed lease terms are within the reader's bounds at `now_ms`: the lease
168 /// ends at most `Λ + σ` from now and the freshness window is at most `Λ`. A longer lease or
169 /// window is the signer's choice, not a registry's, so it is never live.
170 fn descriptor_terms_admissible_at(&self, now_ms: u128) -> bool {
171 let lease_ms = registry_lease().as_millis();
172 self.descriptor_expires_at_ms()
173 <= now_ms
174 .saturating_add(lease_ms)
175 .saturating_add(TS_OFFSET_TOLERANCE_MS)
176 && u128::from(self.descriptor_fresh_for_ms()) <= lease_ms
177 }
178
179 /// Whether a reader at `now_ms` in overlay `network_id` lists this descriptor: it verifies,
180 /// its terms are admissible, and it is not expired (the lease law).
181 fn descriptor_is_live_at(&self, now_ms: u128, network_id: u32) -> bool {
182 self.descriptor_verify_signature_at(network_id, now_ms)
183 && self.descriptor_terms_admissible_at(now_ms)
184 && !self.descriptor_is_expired_at(now_ms)
185 }
186
187 /// Return whether this descriptor supersedes `other` of the same key: the later lease wins,
188 /// then the later heartbeat, and a tie is decided by `(signed body, signature)`, so the order
189 /// is total on distinct descriptors. The lease leads because it is signed: a replayed older
190 /// lease can be heard later than the current one, but never outranks it. A descriptor whose
191 /// content fails to encode never supersedes, and is superseded by one that encodes.
192 fn supersedes(&self, other: &Self) -> bool {
193 let rank = |descriptor: &Self| {
194 (
195 descriptor.descriptor_expires_at_ms(),
196 descriptor.descriptor_heartbeat_at_ms(),
197 )
198 };
199 let content = |descriptor: &Self| {
200 Some((
201 descriptor.descriptor_signing_data().ok()?,
202 rings_codec::serialize(descriptor.descriptor_signature()).ok()?,
203 ))
204 };
205 rank(self)
206 .cmp(&rank(other))
207 .then_with(|| content(self).cmp(&content(other)))
208 == std::cmp::Ordering::Greater
209 }
210}
211
212/// Select the newest descriptor per DID that verifies under the receiver's overlay.
213pub fn latest_valid_by_did<D>(
214 descriptors: impl IntoIterator<Item = D>,
215 now_ms: u128,
216 network_id: u32,
217 include_expired: bool,
218) -> Vec<D>
219where
220 D: SignedDescriptor,
221{
222 latest_valid_by_key(
223 descriptors,
224 SignedDescriptor::descriptor_did,
225 now_ms,
226 network_id,
227 include_expired,
228 )
229 .into_values()
230 .collect()
231}
232
233/// Select the newest descriptor per `key` that verifies under the receiver's overlay, and live at
234/// `now_ms` unless `include_expired`: the join `⊔` of the descriptors under
235/// [`SignedDescriptor::supersedes`] within each key, a total order, so the selection does not
236/// depend on the input order.
237pub fn latest_valid_by_key<K, D>(
238 descriptors: impl IntoIterator<Item = D>,
239 key: impl Fn(&D) -> K,
240 now_ms: u128,
241 network_id: u32,
242 include_expired: bool,
243) -> BTreeMap<K, D>
244where
245 K: Ord,
246 D: SignedDescriptor,
247{
248 let mut latest = BTreeMap::<K, D>::new();
249 for descriptor in descriptors {
250 if include_expired {
251 if !descriptor.descriptor_verify_signature_at(network_id, now_ms) {
252 continue;
253 }
254 } else if !descriptor.descriptor_is_live_at(now_ms, network_id) {
255 continue;
256 }
257 match latest.entry(key(&descriptor)) {
258 Entry::Occupied(mut entry) => {
259 if descriptor.supersedes(entry.get()) {
260 entry.insert(descriptor);
261 }
262 }
263 Entry::Vacant(entry) => {
264 entry.insert(descriptor);
265 }
266 }
267 }
268 latest
269}
270
271/// A descriptor as one element of its DHT registry: the element is the descriptor's codec
272/// encoding, carried as is.
273///
274/// Law (round trip): `from_element(to_element(d)) = Ok(d)`.
275pub trait RegistryElement: Serialize + DeserializeOwned {
276 /// This descriptor as a registry element.
277 fn to_element(&self) -> Result<Bytes> {
278 rings_codec::serialize(self)
279 .map(Bytes::from)
280 .map_err(Error::CodecSerialize)
281 }
282
283 /// The descriptor the registry element `element` encodes.
284 fn from_element(element: &[u8]) -> Result<Self> {
285 rings_codec::deserialize(element).map_err(Error::CodecDeserialize)
286 }
287}
288
289/// The registry elements of `entry`, each with the issue time of its dot, `τ*`: the time the
290/// newest write of those bytes was stamped, which a heartbeat's re-append raises.
291///
292/// Law: a served carrier is normalized, so its dots align with its elements; an element without
293/// a dot (none in a normalized carrier) is not heard and is skipped.
294pub fn heard_elements(entry: &DhtEntry) -> impl Iterator<Item = (&Bytes, u128)> {
295 entry.data.iter().zip(
296 entry
297 .crdt
298 .dots
299 .iter()
300 .map(|dot| dot.version.logical_time_ms),
301 )
302}
303
304/// Decode every element of `entry` as `D`, heard at its dot; elements that do not decode are
305/// skipped.
306pub fn heard_descriptors<D>(entry: &DhtEntry) -> Vec<D>
307where D: SignedDescriptor + RegistryElement {
308 heard_elements(entry)
309 .filter_map(|(element, heard_at_ms)| {
310 D::from_element(element)
311 .ok()
312 .map(|descriptor| descriptor.heard_at(heard_at_ms))
313 })
314 .collect()
315}