1use 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
45pub const ONION_INVOKES_TOPIC: &str = "onion_invokes";
47
48const ONION_INVOKE_DESCRIPTOR_DOMAIN_TAG: DomainTag =
50 domain_tag!("rings-node:onion-invoke-descriptor");
51
52#[derive(Clone, Copy, Debug, Default, Deserialize, Eq, PartialEq, Serialize)]
54#[serde(deny_unknown_fields)]
55pub struct OnionInvokePolicy {
56 pub max_concurrent: u32,
59 pub max_invocations_per_minute: u64,
62}
63
64#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
66pub struct OnionInvokeDescriptorBody {
67 pub did: Did,
69 pub public_key: VerificationPublicKey,
71 pub delegatee_public_key: PublicKey<33>,
73 pub process_epoch: OnionProcessEpoch,
75 pub node_type: OnlineNodeType,
77 pub network_id: u32,
79 pub shape: OnionInvokeShape,
81 pub backend: OnionBackendName,
83 pub policy: OnionInvokePolicy,
85 pub started_at_ms: u128,
87 pub fresh_for_ms: u64,
89 pub expires_at_ms: u128,
91 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#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
186pub struct OnionInvokeDescriptor {
187 pub did: Did,
189 pub public_key: VerificationPublicKey,
191 pub delegatee_public_key: PublicKey<33>,
193 pub process_epoch: OnionProcessEpoch,
195 pub node_type: OnlineNodeType,
197 pub network_id: u32,
199 pub shape: OnionInvokeShape,
201 pub backend: OnionBackendName,
203 pub policy: OnionInvokePolicy,
205 pub started_at_ms: u128,
207 #[serde(skip)]
209 pub heartbeat_at_ms: u128,
210 pub fresh_for_ms: u64,
212 pub expires_at_ms: u128,
214 pub version: String,
216 pub signature: MessageVerification,
218}
219
220impl OnionInvokeDescriptor {
221 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 pub fn verify_signature(&self, network_id: u32) -> bool {
257 self.descriptor_verify_signature(network_id)
258 }
259
260 pub fn is_expired_at(&self, now_ms: u128) -> bool {
262 self.descriptor_is_expired_at(now_ms)
263 }
264
265 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 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 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#[derive(Clone, Debug, Default, Eq, PartialEq)]
341pub struct OnionInvokeDescriptorDecodeReport {
342 pub descriptors: Vec<OnionInvokeDescriptor>,
344 pub rejected_values: usize,
346}
347
348impl OnionInvokeDescriptorDecodeReport {
349 pub const fn has_rejections(&self) -> bool {
351 self.rejected_values > 0
352 }
353}
354
355#[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 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 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 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 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}