Skip to main content

rings_node/onion/
invoke_descriptor.rs

1//! Signed descriptors and DHT registration for intermediate `invoke` symbols (#834 D1′, D2).
2//!
3//! A node publishes one signed [`OnionInvokeDescriptor`] per `(shape, backend)` pair in `Σ_I × Ω`
4//! under [`ONION_INVOKES_TOPIC`], carrying the same `process_epoch` `e_n` as its `relay`
5//! registration and the `quota(n, f, ω)` policy ([`OnionInvokePolicy`]). Applications and client
6//! constants are never published.
7
8use std::borrow::Borrow;
9use std::time::Duration;
10
11use async_trait::async_trait;
12use rings_core::delegation::DelegateeKey;
13use rings_core::dht::Did;
14use rings_core::domain_tag;
15use rings_core::ecc::PublicKey;
16use rings_core::ecc::VerificationPublicKey;
17use rings_core::error::Error as CoreError;
18use rings_core::error::Result as CoreResult;
19use rings_core::message::DomainTag;
20use rings_core::message::MessageSigner;
21use rings_core::message::MessageVerification;
22use rings_core::utils::SharedClock;
23use serde::Deserialize;
24use serde::Serialize;
25
26use super::role::OnionInvokeOffer;
27use super::signature::OnionBackendName;
28use super::signature::OnionInvokeShape;
29use super::OnionProcessEpoch;
30use super::OnionProcessEpochCell;
31use crate::descriptor::heard_elements;
32use crate::descriptor::latest_valid_by_key;
33use crate::descriptor::sign_descriptor_body;
34use crate::descriptor::RegistryElement;
35use crate::descriptor::SignedDescriptor;
36use crate::descriptor::SignedDescriptorBody;
37use crate::error::Error;
38use crate::error::Result;
39use crate::online::OnlineNodeType;
40use crate::registration::DhtRegistrationPublisher;
41use crate::registration::LeaseTerms;
42use crate::registration::RegistrationContext;
43use crate::registration::RegistrationTask;
44
45/// DHT topic used for signed intermediate `invoke` symbol descriptors (#834 D2).
46pub const ONION_INVOKES_TOPIC: &str = "onion_invokes";
47
48/// Message family of the onion-invoke descriptor signature.
49const ONION_INVOKE_DESCRIPTOR_DOMAIN_TAG: DomainTag =
50    domain_tag!("rings-node:onion-invoke-descriptor");
51
52/// Signed `quota(n, f, ω)` policy for one `(node, shape, backend)` registration (#834 D2).
53#[derive(Clone, Copy, Debug, Default, Deserialize, Eq, PartialEq, Serialize)]
54#[serde(deny_unknown_fields)]
55pub struct OnionInvokePolicy {
56    /// Maximum concurrent in-flight invocations of `(shape, backend)` on this node.
57    /// `0` means unspecified (clamped to the protocol hard bound).
58    pub max_concurrent: u32,
59    /// Maximum invocations per minute of `(shape, backend)` on this node.
60    /// `0` means unspecified.
61    pub max_invocations_per_minute: u64,
62}
63
64/// Descriptor fields covered by the onion-invoke signature.
65#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
66pub struct OnionInvokeDescriptorBody {
67    /// DID of the hosting node/account.
68    pub did: Did,
69    /// Account public key corresponding to `did`.
70    pub public_key: VerificationPublicKey,
71    /// Delegation public key: the Sphinx key `pk_i` a loop's header blinds the hop's layer to.
72    pub delegatee_public_key: PublicKey<33>,
73    /// Process epoch `e_n` of the registering process, equal to its `relay` registration's.
74    pub process_epoch: OnionProcessEpoch,
75    /// Runtime family of this node.
76    pub node_type: OnlineNodeType,
77    /// Network identifier.
78    pub network_id: u32,
79    /// Closed `invoke` shape `f ∈ Σ_I`.
80    pub shape: OnionInvokeShape,
81    /// Canonical open backend name `ω ∈ Ω`.
82    pub backend: OnionBackendName,
83    /// Signed per-`(node, shape, backend)` quota policy.
84    pub policy: OnionInvokePolicy,
85    /// Process start timestamp in milliseconds since Unix epoch.
86    pub started_at_ms: u128,
87    /// Freshness window `T` in milliseconds.
88    pub fresh_for_ms: u64,
89    /// Lease end `ℓ` in milliseconds since Unix epoch.
90    pub expires_at_ms: u128,
91    /// Node software version.
92    pub version: String,
93}
94
95impl OnionInvokeDescriptorBody {
96    fn body_ref(&self) -> OnionInvokeDescriptorBodyRef<'_> {
97        OnionInvokeDescriptorBodyRef {
98            did: self.did,
99            public_key: &self.public_key,
100            delegatee_public_key: &self.delegatee_public_key,
101            process_epoch: self.process_epoch,
102            node_type: &self.node_type,
103            network_id: self.network_id,
104            shape: &self.shape,
105            backend: &self.backend,
106            policy: &self.policy,
107            started_at_ms: self.started_at_ms,
108            fresh_for_ms: self.fresh_for_ms,
109            expires_at_ms: self.expires_at_ms,
110            version: self.version.as_str(),
111        }
112    }
113
114    fn signing_data(&self) -> CoreResult<Vec<u8>> {
115        self.body_ref().signing_data()
116    }
117}
118
119impl SignedDescriptorBody for OnionInvokeDescriptorBody {
120    type Descriptor = OnionInvokeDescriptor;
121
122    const DOMAIN_TAG: DomainTag = ONION_INVOKE_DESCRIPTOR_DOMAIN_TAG;
123
124    fn body_did(&self) -> Did {
125        self.did
126    }
127
128    fn body_public_key(&self) -> &VerificationPublicKey {
129        &self.public_key
130    }
131
132    fn body_network_id(&self) -> u32 {
133        self.network_id
134    }
135
136    fn body_signing_data(&self) -> CoreResult<Vec<u8>> {
137        self.signing_data()
138    }
139
140    fn into_signed_descriptor(self, signature: MessageVerification) -> Self::Descriptor {
141        OnionInvokeDescriptor {
142            did: self.did,
143            public_key: self.public_key,
144            delegatee_public_key: self.delegatee_public_key,
145            process_epoch: self.process_epoch,
146            node_type: self.node_type,
147            network_id: self.network_id,
148            shape: self.shape,
149            backend: self.backend,
150            policy: self.policy,
151            started_at_ms: self.started_at_ms,
152            heartbeat_at_ms: 0,
153            fresh_for_ms: self.fresh_for_ms,
154            expires_at_ms: self.expires_at_ms,
155            version: self.version,
156            signature,
157        }
158    }
159}
160
161#[derive(Serialize)]
162struct OnionInvokeDescriptorBodyRef<'a> {
163    did: Did,
164    public_key: &'a VerificationPublicKey,
165    delegatee_public_key: &'a PublicKey<33>,
166    process_epoch: OnionProcessEpoch,
167    node_type: &'a OnlineNodeType,
168    network_id: u32,
169    shape: &'a OnionInvokeShape,
170    backend: &'a OnionBackendName,
171    policy: &'a OnionInvokePolicy,
172    started_at_ms: u128,
173    fresh_for_ms: u64,
174    expires_at_ms: u128,
175    version: &'a str,
176}
177
178impl OnionInvokeDescriptorBodyRef<'_> {
179    fn signing_data(&self) -> CoreResult<Vec<u8>> {
180        rings_codec::serialize(self).map_err(CoreError::CodecSerialize)
181    }
182}
183
184/// Signed descriptor published for one `(shape, backend)` `invoke` registration (#834 D2).
185#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
186pub struct OnionInvokeDescriptor {
187    /// DID of the hosting node/account.
188    pub did: Did,
189    /// Account public key corresponding to `did`.
190    pub public_key: VerificationPublicKey,
191    /// Delegation public key: the Sphinx key `pk_i` a loop's header blinds the hop's layer to.
192    pub delegatee_public_key: PublicKey<33>,
193    /// Process epoch `e_n` of the registering process, equal to its `relay` registration's.
194    pub process_epoch: OnionProcessEpoch,
195    /// Runtime family of this node.
196    pub node_type: OnlineNodeType,
197    /// Network identifier.
198    pub network_id: u32,
199    /// Closed `invoke` shape `f ∈ Σ_I`.
200    pub shape: OnionInvokeShape,
201    /// Canonical open backend name `ω ∈ Ω`.
202    pub backend: OnionBackendName,
203    /// Signed per-`(node, shape, backend)` quota policy.
204    pub policy: OnionInvokePolicy,
205    /// Process start timestamp in milliseconds since Unix epoch.
206    pub started_at_ms: u128,
207    /// When the reader last heard this descriptor, in milliseconds since Unix epoch (`0` until heard).
208    #[serde(skip)]
209    pub heartbeat_at_ms: u128,
210    /// Freshness window `T` in milliseconds.
211    pub fresh_for_ms: u64,
212    /// Lease end `ℓ` in milliseconds since Unix epoch.
213    pub expires_at_ms: u128,
214    /// Node software version.
215    pub version: String,
216    /// Signature covering every field above except `heartbeat_at_ms`.
217    pub signature: MessageVerification,
218}
219
220impl OnionInvokeDescriptor {
221    /// Create and sign an onion-invoke descriptor.
222    pub fn new_signed(
223        body: OnionInvokeDescriptorBody,
224        signer: MessageSigner<impl Borrow<DelegateeKey>>,
225    ) -> CoreResult<Self> {
226        sign_descriptor_body(
227            body,
228            signer,
229            "onion invoke descriptor DID/public key/session mismatch",
230        )
231    }
232
233    fn body_ref(&self) -> OnionInvokeDescriptorBodyRef<'_> {
234        OnionInvokeDescriptorBodyRef {
235            did: self.did,
236            public_key: &self.public_key,
237            delegatee_public_key: &self.delegatee_public_key,
238            process_epoch: self.process_epoch,
239            node_type: &self.node_type,
240            network_id: self.network_id,
241            shape: &self.shape,
242            backend: &self.backend,
243            policy: &self.policy,
244            started_at_ms: self.started_at_ms,
245            fresh_for_ms: self.fresh_for_ms,
246            expires_at_ms: self.expires_at_ms,
247            version: self.version.as_str(),
248        }
249    }
250
251    fn signing_data(&self) -> CoreResult<Vec<u8>> {
252        self.body_ref().signing_data()
253    }
254
255    /// Verify the descriptor signature and DID/public-key binding.
256    pub fn verify_signature(&self, network_id: u32) -> bool {
257        self.descriptor_verify_signature(network_id)
258    }
259
260    /// Returns whether this descriptor is expired at `now_ms`.
261    pub fn is_expired_at(&self, now_ms: u128) -> bool {
262        self.descriptor_is_expired_at(now_ms)
263    }
264
265    /// Returns whether a reader lists this descriptor as live at `now_ms`.
266    pub fn is_live_at(&self, now_ms: u128, network_id: u32) -> bool {
267        self.descriptor_is_live_at(now_ms, network_id)
268    }
269
270    /// Select the newest valid onion-invoke descriptor per `(DID, shape, backend)` (#834 D2).
271    pub fn latest_valid_by_symbol_did(
272        descriptors: impl IntoIterator<Item = Self>,
273        now_ms: u128,
274        network_id: u32,
275        include_expired: bool,
276    ) -> Vec<Self> {
277        latest_valid_by_key(
278            descriptors,
279            Self::registration_key,
280            now_ms,
281            network_id,
282            include_expired,
283        )
284        .into_values()
285        .collect()
286    }
287
288    /// Return the registration key `(DID, shape, backend)`.
289    pub(crate) fn registration_key(&self) -> (Did, OnionInvokeShape, OnionBackendName) {
290        (self.did, self.shape, self.backend.clone())
291    }
292}
293
294impl SignedDescriptor for OnionInvokeDescriptor {
295    type Body = OnionInvokeDescriptorBody;
296
297    fn descriptor_did(&self) -> Did {
298        self.did
299    }
300
301    fn descriptor_public_key(&self) -> &VerificationPublicKey {
302        &self.public_key
303    }
304
305    fn descriptor_network_id(&self) -> u32 {
306        self.network_id
307    }
308
309    fn descriptor_signature(&self) -> &MessageVerification {
310        &self.signature
311    }
312
313    fn descriptor_heartbeat_at_ms(&self) -> u128 {
314        self.heartbeat_at_ms
315    }
316
317    fn descriptor_expires_at_ms(&self) -> u128 {
318        self.expires_at_ms
319    }
320
321    fn descriptor_fresh_for_ms(&self) -> u64 {
322        self.fresh_for_ms
323    }
324
325    fn descriptor_signing_data(&self) -> CoreResult<Vec<u8>> {
326        self.signing_data()
327    }
328
329    fn heard_at(self, heartbeat_at_ms: u128) -> Self {
330        Self {
331            heartbeat_at_ms,
332            ..self
333        }
334    }
335}
336
337impl RegistryElement for OnionInvokeDescriptor {}
338
339/// Result of decoding one onion-invoke registry entry.
340#[derive(Clone, Debug, Default, Eq, PartialEq)]
341pub struct OnionInvokeDescriptorDecodeReport {
342    /// Descriptors that decoded successfully under the closed signature and backend grammar.
343    pub descriptors: Vec<OnionInvokeDescriptor>,
344    /// Number of registry values explicitly rejected at the decode boundary.
345    pub rejected_values: usize,
346}
347
348impl OnionInvokeDescriptorDecodeReport {
349    /// Return whether the entry contained values this node could not decode.
350    pub const fn has_rejections(&self) -> bool {
351        self.rejected_values > 0
352    }
353}
354
355/// Periodic node-layer DHT registration for offered `(shape, backend)` pairs.
356#[derive(Clone, Debug)]
357pub(crate) struct OnionInvokeRegistration {
358    heartbeat_interval: Duration,
359    node_type: OnlineNodeType,
360    process_epoch: OnionProcessEpochCell,
361    started_at_ms: u128,
362    offer: OnionInvokeOffer,
363    clock: SharedClock,
364    publisher: DhtRegistrationPublisher<Vec<OnionInvokeDescriptor>>,
365}
366
367impl OnionInvokeRegistration {
368    pub(crate) fn new_with_clock(
369        heartbeat_interval: Duration,
370        ttl: Duration,
371        node_type: OnlineNodeType,
372        offer: OnionInvokeOffer,
373        process_epoch: OnionProcessEpochCell,
374        clock: SharedClock,
375    ) -> Self {
376        let started_at_ms = clock.now_ms();
377        Self {
378            heartbeat_interval,
379            node_type,
380            process_epoch,
381            started_at_ms,
382            offer,
383            clock,
384            publisher: DhtRegistrationPublisher::new(ONION_INVOKES_TOPIC, heartbeat_interval, ttl),
385        }
386    }
387
388    /// Build this node's signed `invoke` descriptors under `terms`.
389    pub fn descriptors_at(
390        &self,
391        context: &RegistrationContext<'_>,
392        terms: LeaseTerms,
393    ) -> Result<Vec<OnionInvokeDescriptor>> {
394        self.offer
395            .entries()
396            .map(|((shape, backend), policy)| {
397                OnionInvokeDescriptor::new_signed(
398                    OnionInvokeDescriptorBody {
399                        did: context.did(),
400                        public_key: context.delegator_verification_pubkey()?,
401                        delegatee_public_key: context.delegatee_key().delegatee_public_key(),
402                        process_epoch: self.process_epoch.get(),
403                        node_type: self.node_type.clone(),
404                        network_id: context.network_id(),
405                        shape: *shape,
406                        backend: backend.clone(),
407                        policy: *policy,
408                        started_at_ms: self.started_at_ms,
409                        fresh_for_ms: terms.fresh_for_ms,
410                        expires_at_ms: terms.expires_at_ms,
411                        version: crate::util::build_version(),
412                    },
413                    context.message_signer(),
414                )
415                .map_err(Error::CoreError)
416            })
417            .collect()
418    }
419
420    /// Publish one heartbeat of this node's signed `invoke` descriptors.
421    pub async fn publish_descriptors(
422        &self,
423        context: &RegistrationContext<'_>,
424    ) -> Result<Vec<OnionInvokeDescriptor>> {
425        self.publisher
426            .publish_lease(context, self.clock.now_ms(), |terms| {
427                self.descriptors_at(context, terms)
428            })
429            .await
430    }
431
432    /// Decode `invoke` descriptors from a DHT entry, counting schema rejections.
433    pub fn decode_descriptors_from_entry(
434        entry: &rings_core::dht::entry::Entry,
435    ) -> OnionInvokeDescriptorDecodeReport {
436        let mut report = OnionInvokeDescriptorDecodeReport::default();
437        for (value, heard_at_ms) in heard_elements(entry) {
438            match OnionInvokeDescriptor::from_element(value) {
439                Ok(descriptor) => report.descriptors.push(descriptor.heard_at(heard_at_ms)),
440                Err(error) => {
441                    report.rejected_values = report.rejected_values.saturating_add(1);
442                    tracing::debug!(
443                        "rejected onion-invoke descriptor registry value at schema boundary: {error}"
444                    );
445                }
446            }
447        }
448        report
449    }
450
451    /// Decode `invoke` descriptors from a DHT entry, dropping rejected values.
452    pub fn descriptors_from_entry(
453        entry: &rings_core::dht::entry::Entry,
454    ) -> Vec<OnionInvokeDescriptor> {
455        let report = Self::decode_descriptors_from_entry(entry);
456        if report.has_rejections() {
457            tracing::warn!(
458                rejected_values = report.rejected_values,
459                "ignored unsupported onion-invoke descriptor registry values"
460            );
461        }
462        report.descriptors
463    }
464}
465
466#[cfg_attr(rings_browser, async_trait(?Send))]
467#[cfg_attr(rings_native, async_trait)]
468impl RegistrationTask for OnionInvokeRegistration {
469    fn name(&self) -> &'static str {
470        "onion-invoke"
471    }
472
473    fn interval(&self) -> Duration {
474        self.heartbeat_interval
475    }
476
477    async fn register_once(&self, context: &RegistrationContext<'_>) -> Result<()> {
478        self.publish_descriptors(context).await.map(|_| ())
479    }
480}