1use std::collections::BTreeMap;
4use std::future::Future;
5use std::pin::Pin;
6use std::str::FromStr;
7use std::sync::atomic::AtomicU64;
8use std::sync::atomic::Ordering;
9use std::sync::Arc;
10use std::sync::Mutex;
11
12use async_trait::async_trait;
13use rings_core::delegation::DelegateeKey;
14use rings_core::delegation::DelegationBuilder;
15use rings_core::dht::Did;
16use rings_core::dht::EntryStorage;
17use rings_core::dht::RemovalStorage;
18use rings_core::ecc::PublicKey;
19use rings_core::lifecycle::StopToken;
20use rings_core::measure::EvidenceCounters;
21use rings_core::measure::EvidenceDigest;
22use rings_core::measure::EvidenceError;
23use rings_core::measure::EvidencePage;
24use rings_core::measure::PeerMeasurement;
25use rings_core::message::ReplayStorage;
26use rings_core::storage::MemStorage;
27use rings_core::swarm::application::ApplicationData;
28use rings_core::swarm::application::ApplicationMessage;
29use rings_rpc::protos::rings_node_handler::InternalRpcHandler;
30use rings_runtime::MaybeSendSync;
31use serde::Deserialize;
32use serde::Serialize;
33
34use crate::error::Error;
35use crate::error::Result;
36use crate::extension::Backend;
37use crate::extension::BackendObserver;
38use crate::extension::DispatchDropCounters;
39use crate::extension::DispatchDrops;
40use crate::mail::registration::MailOffer;
41use crate::measure::EvidenceCollectorIdentity;
42use crate::measure::EvidenceStorage;
43use crate::measure::MeasureStorage;
44use crate::measure::PeriodicMeasure;
45use crate::measure::UnavailableEvidenceStorage;
46#[cfg(feature = "node")]
47use crate::onion::native::NativeOnionCircuitHandle;
48use crate::onion::runtime::OnionRuntime;
49use crate::onion::OnionEntryGuardStorage;
50use crate::prelude::wasm_export;
51#[cfg(not(all(feature = "browser", target_family = "wasm")))]
52use crate::processor::DelegationHorizon;
53use crate::processor::Processor;
54use crate::processor::ProcessorBuilder;
55use crate::processor::ProcessorConfig;
56use crate::release::StoresReleased;
57
58const CLOSE_DRAIN_TIMEOUT: std::time::Duration = std::time::Duration::from_secs(5);
59
60#[cfg(all(feature = "browser", target_family = "wasm"))]
61pub mod browser;
62
63async fn await_close_phase<F>(
64 phase_fut: F,
65 timeout: std::time::Duration,
66 phase: &'static str,
67) -> bool
68where
69 F: Future<Output = ()>,
70{
71 let deadline = rings_runtime::sleep(timeout);
72 futures::pin_mut!(phase_fut, deadline);
73 match futures::future::select(phase_fut, deadline).await {
74 futures::future::Either::Left(((), _)) => true,
75 futures::future::Either::Right((timer, _)) => {
76 match timer {
77 Ok(()) => tracing::warn!(
78 phase,
79 timeout_ms = u64::try_from(timeout.as_millis()).unwrap_or(u64::MAX),
80 "provider close timed out waiting for shutdown phase"
81 ),
82 Err(error) => tracing::warn!(
83 phase,
84 ?error,
85 "provider close timer unavailable while waiting for shutdown phase"
86 ),
87 }
88 false
89 }
90 }
91}
92#[cfg(feature = "ffi")]
93pub mod ffi;
94
95const E2E_EVENT_CAPACITY: usize = 4096;
97
98#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
100pub struct E2eEvent {
101 pub kind: String,
103 pub from: String,
105 pub public_key: Option<String>,
107 pub ephemeral_public_key: Option<String>,
109 pub stream_id: Option<String>,
111 pub sequence: Option<u64>,
113 pub is_final: Option<bool>,
115 pub ciphertext_blocks: Option<usize>,
117 pub ciphertext: Option<String>,
119}
120
121#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
123pub struct TakeE2eEventsResponse {
124 pub events: Vec<E2eEvent>,
126 pub dropped: u64,
128}
129
130#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
132pub struct SigningHorizonSnapshot {
133 pub expires_at_ms: String,
135 pub horizon_ms: String,
137 pub remaining_ms: String,
139 pub signs_now: bool,
141}
142
143#[derive(Default)]
144pub(crate) struct E2eInbox {
145 events: Mutex<Vec<E2eEvent>>,
146 dropped: AtomicU64,
147}
148
149impl E2eInbox {
150 pub(crate) fn take(&self) -> Result<TakeE2eEventsResponse> {
151 let mut events = self.events.lock().map_err(|_| Error::Lock)?;
152 Ok(TakeE2eEventsResponse {
153 events: std::mem::take(&mut *events),
154 dropped: self.dropped.load(Ordering::Relaxed),
155 })
156 }
157
158 fn push(&self, event: E2eEvent) -> Result<()> {
159 let mut events = self.events.lock().map_err(|_| Error::Lock)?;
160 if events.len() < E2E_EVENT_CAPACITY {
161 events.push(event);
162 } else {
163 let dropped = self
164 .dropped
165 .fetch_add(1, Ordering::Relaxed)
166 .saturating_add(1);
167 tracing::debug!(dropped, "provider E2E event inbox full; event dropped");
168 }
169 Ok(())
170 }
171}
172
173impl BackendObserver for E2eInbox {
174 fn e2e_message(&self, message: &ApplicationMessage) {
175 match e2e_event_from_message(message)
176 .and_then(|event| event.map_or(Ok(()), |e| self.push(e)))
177 {
178 Ok(()) => {}
179 Err(error) => tracing::warn!(error = ?error, "provider E2E event not retained"),
180 }
181 }
182}
183
184struct CompositeBackendObserver {
185 e2e_inbox: Arc<E2eInbox>,
186 extra: Option<Arc<dyn BackendObserver>>,
187}
188
189impl BackendObserver for CompositeBackendObserver {
190 fn link_fact(&self, fact: crate::extension::ext::LinkFact) {
191 if let Some(extra) = self.extra.as_deref() {
192 extra.link_fact(fact);
193 }
194 }
195
196 fn e2e_message(&self, message: &ApplicationMessage) {
197 self.e2e_inbox.e2e_message(message);
198 if let Some(extra) = self.extra.as_deref() {
199 extra.e2e_message(message);
200 }
201 }
202
203 fn custom_envelope(&self, from: Did, bytes: &[u8]) {
204 if let Some(extra) = self.extra.as_deref() {
205 extra.custom_envelope(from, bytes);
206 }
207 }
208}
209
210fn e2e_event_from_message(message: &ApplicationMessage) -> Result<Option<E2eEvent>> {
211 let from = message.from.to_string();
212 Ok(Some(match &message.data {
213 ApplicationData::E2eHandshakeRequest(request) => E2eEvent {
214 kind: "handshakeRequest".to_owned(),
215 from,
216 public_key: Some(public_key_json_string(request.requester_public_key)?),
217 ephemeral_public_key: None,
218 stream_id: None,
219 sequence: None,
220 is_final: None,
221 ciphertext_blocks: None,
222 ciphertext: None,
223 },
224 ApplicationData::E2eHandshakeResponse(response) => E2eEvent {
225 kind: "handshakeResponse".to_owned(),
226 from,
227 public_key: Some(public_key_json_string(response.responder_public_key)?),
228 ephemeral_public_key: None,
229 stream_id: None,
230 sequence: None,
231 is_final: None,
232 ciphertext_blocks: None,
233 ciphertext: None,
234 },
235 ApplicationData::E2eStreamFrame(frame) => E2eEvent {
236 kind: "streamFrame".to_owned(),
237 from,
238 public_key: Some(public_key_json_string(frame.sender_public_key)?),
239 ephemeral_public_key: Some(public_key_json_string(frame.ephemeral_public_key)?),
240 stream_id: Some(frame.stream_id.to_string()),
241 sequence: Some(frame.sequence),
242 is_final: Some(frame.is_final),
243 ciphertext_blocks: Some(frame.ciphertext_blocks()),
244 ciphertext: Some(base64::encode(&frame.ciphertext)),
245 },
246 _ => return Ok(None),
247 }))
248}
249
250fn public_key_json_string(public_key: PublicKey<33>) -> Result<String> {
251 let value = serde_json::to_value(public_key)?;
252 value.as_str().map(str::to_owned).ok_or(Error::InvalidData)
253}
254
255mod u128_decimal_string {
256 use serde::de::Error as _;
257 use serde::Deserialize;
258 use serde::Deserializer;
259 use serde::Serializer;
260
261 #[derive(Deserialize)]
262 #[serde(untagged)]
263 enum StringOrU64 {
264 Str(String),
265 Num(u64),
266 }
267
268 pub(super) fn serialize<S: Serializer>(value: &u128, serializer: S) -> Result<S::Ok, S::Error> {
269 serializer.serialize_str(&value.to_string())
270 }
271
272 pub(super) fn deserialize<'de, D: Deserializer<'de>>(
273 deserializer: D,
274 ) -> Result<u128, D::Error> {
275 match StringOrU64::deserialize(deserializer)? {
276 StringOrU64::Str(raw) => raw.parse::<u128>().map_err(D::Error::custom),
277 StringOrU64::Num(num) => Ok(u128::from(num)),
278 }
279 }
280}
281
282#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
284pub struct RegistryElementSnapshot {
285 pub data_base64: String,
287 #[serde(with = "u128_decimal_string")]
289 pub heartbeat_at_ms: u128,
290}
291
292#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
294pub struct LookupRegistryResponse {
295 pub topic: String,
297 pub network_id: u32,
299 #[serde(with = "u128_decimal_string")]
301 pub now_ms: u128,
302 pub elements: Vec<RegistryElementSnapshot>,
304}
305
306#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
308pub struct OnionEligibleStage {
309 pub did: Did,
311 #[serde(default, skip_serializing_if = "Option::is_none")]
313 pub process_epoch: Option<crate::onion::OnionProcessEpoch>,
314 #[serde(default, skip_serializing_if = "Option::is_none")]
316 pub delegatee_public_key: Option<PublicKey<33>>,
317}
318
319#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
321pub struct OnionInvokeRpcRequest {
322 pub shape: crate::onion::OnionInvokeShape,
324 pub backend: crate::onion::OnionBackendName,
326 #[serde(default, skip_serializing_if = "Option::is_none")]
328 pub constants_base64: Option<String>,
329 #[serde(default)]
331 pub input_base64: String,
332 #[serde(default, skip_serializing_if = "Option::is_none")]
334 pub eligible_dids: Option<Vec<Did>>,
335 #[serde(default, skip_serializing_if = "Option::is_none")]
337 pub eligible_stages: Option<Vec<OnionEligibleStage>>,
338 #[serde(default, skip_serializing_if = "Option::is_none")]
340 pub timeout_ms: Option<u64>,
341}
342
343#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
345pub struct OnionInvokeRpcResponse {
346 pub stage_did: Did,
348 pub stage_process_epoch: crate::onion::OnionProcessEpoch,
350 pub stage_delegatee_public_key: PublicKey<33>,
352 pub output_base64: String,
354}
355
356fn is_builtin_local_rpc_method(method: &str) -> bool {
357 matches!(
358 method,
359 "takeE2eEvents"
360 | "dispatchDropCounters"
361 | "signingHorizon"
362 | "renewDelegateeKey"
363 | "lookupRegistry"
364 | "onionInvoke"
365 | "ConnectPeerViaHttp"
366 ) || rings_rpc::method::Method::try_from(method).is_ok()
367}
368
369#[cfg_attr(all(feature = "browser", target_family = "wasm"), async_trait(?Send))]
371#[cfg_attr(not(all(feature = "browser", target_family = "wasm")), async_trait)]
372pub trait LocalRpcMethod: MaybeSendSync {
373 async fn call(&self, params: serde_json::Value) -> Result<serde_json::Value>;
375}
376
377#[derive(Clone)]
379#[allow(dead_code)]
380#[wasm_export]
381pub struct Provider {
382 processor: Arc<Processor>,
383 handler: InternalRpcHandler,
384 extensions: crate::extension::ext::Extensions,
385 dispatch_drops: Arc<DispatchDrops>,
386 e2e_inbox: Arc<E2eInbox>,
387 custom_rpc: Arc<Mutex<BTreeMap<String, Arc<dyn LocalRpcMethod>>>>,
389 onion_runtime: Arc<Mutex<Option<OnionRuntime>>>,
392 #[cfg(all(feature = "browser", target_family = "wasm"))]
393 onion_directory_endpoint: Arc<Mutex<Option<BrowserDirectoryEndpoint>>>,
394 #[cfg(all(feature = "browser", target_family = "wasm"))]
397 browser_mail: Option<std::rc::Rc<browser::provider::mail::BrowserMail>>,
398 #[cfg(all(feature = "browser", target_family = "wasm"))]
400 pagehide: Option<std::rc::Rc<browser::provider::listener::PagehideListener>>,
401}
402
403#[cfg(all(feature = "browser", target_family = "wasm"))]
404#[derive(Clone)]
405pub(crate) struct BrowserDirectoryEndpoint {
406 pub(crate) url: String,
407 pub(crate) api_token: Option<Arc<str>>,
408}
409
410#[cfg(all(feature = "browser", target_family = "wasm"))]
412pub type AsyncSigner = Box<dyn Fn(String) -> Pin<Box<dyn Future<Output = Result<Vec<u8>>>>>>;
413
414#[cfg(not(all(feature = "browser", target_family = "wasm")))]
416pub type AsyncSigner = Box<dyn Fn(String) -> Pin<Box<dyn Future<Output = Result<Vec<u8>>> + Send>>>;
417
418#[allow(clippy::type_complexity)]
420pub enum Signer {
421 Sync(Box<dyn Fn(String) -> Result<Vec<u8>>>),
423 Async(AsyncSigner),
425}
426
427#[derive(Default)]
430pub(crate) struct ProviderStores {
431 pub(crate) entry: Option<EntryStorage>,
433 pub(crate) relay: Option<EntryStorage>,
435 pub(crate) removals: Option<RemovalStorage>,
437 pub(crate) measure: Option<MeasureStorage>,
439 pub(crate) evidence: Option<EvidenceStorage>,
441 pub(crate) guards: Option<OnionEntryGuardStorage>,
443 pub(crate) replay: Option<ReplayStorage>,
445 pub(crate) released: StoresReleased,
447}
448
449#[allow(dead_code)]
450impl Provider {
451 pub fn from_processor(processor: Arc<Processor>) -> Self {
453 let extensions = crate::extension::ext::Extensions::new_weak(&processor);
454 #[cfg(all(feature = "browser", target_family = "wasm"))]
455 let pagehide = browser::provider::listener::PagehideListener::register(&processor)
456 .map(std::rc::Rc::new);
457 Self {
458 processor,
459 handler: InternalRpcHandler,
460 extensions,
461 dispatch_drops: Arc::default(),
462 e2e_inbox: Arc::default(),
463 custom_rpc: Arc::new(Mutex::new(BTreeMap::new())),
464 onion_runtime: Arc::new(Mutex::new(None)),
465 #[cfg(all(feature = "browser", target_family = "wasm"))]
466 onion_directory_endpoint: Arc::new(Mutex::new(None)),
467 #[cfg(all(feature = "browser", target_family = "wasm"))]
468 browser_mail: None,
469 #[cfg(all(feature = "browser", target_family = "wasm"))]
470 pagehide,
471 }
472 }
473
474 pub const fn processor(&self) -> &Arc<Processor> {
476 &self.processor
477 }
478
479 pub fn register_local_rpc_method(
485 &self,
486 method: impl Into<String>,
487 handler: impl LocalRpcMethod + 'static,
488 ) -> Result<()> {
489 let name = method.into();
490 let trimmed = name.trim();
491 if trimmed.is_empty() || trimmed != name {
492 return Err(Error::InvalidConfig(format!(
493 "invalid local RPC method name {name:?}"
494 )));
495 }
496 if is_builtin_local_rpc_method(&name) {
497 return Err(Error::InvalidConfig(format!(
498 "cannot override built-in RPC method {name:?}"
499 )));
500 }
501 let mut table = self.custom_rpc.lock().map_err(|_| Error::Lock)?;
502 if table.contains_key(&name) {
503 return Err(Error::InvalidConfig(format!(
504 "local RPC method {name:?} is already registered"
505 )));
506 }
507 table.insert(name, Arc::new(handler));
508 Ok(())
509 }
510
511 pub async fn lookup_registry_raw(&self, topic: &str) -> Result<LookupRegistryResponse> {
514 let trimmed = topic.trim();
515 if trimmed.is_empty() {
516 return Err(Error::InvalidConfig(
517 "registry topic must be non-empty".to_string(),
518 ));
519 }
520 let now_ms = self.processor.clock().now_ms();
521 let network_id = self.processor.swarm.network_id();
522 let elements = match self.processor.fetch_topic_entry(trimmed).await? {
523 Some(entry) => crate::descriptor::heard_elements(&entry)
524 .map(|(bytes, heartbeat_at_ms)| RegistryElementSnapshot {
525 data_base64: base64::encode(bytes.as_ref()),
526 heartbeat_at_ms,
527 })
528 .collect(),
529 None => Vec::new(),
530 };
531 Ok(LookupRegistryResponse {
532 topic: trimmed.to_string(),
533 network_id,
534 now_ms,
535 elements,
536 })
537 }
538
539 pub async fn onion_invoke_raw(
543 &self,
544 request: OnionInvokeRpcRequest,
545 ) -> Result<OnionInvokeRpcResponse> {
546 let constants = match request.constants_base64.as_deref() {
547 Some(raw) if !raw.is_empty() => base64::decode(raw)
548 .map_err(|e| Error::InvalidConfig(format!("invalid constants_base64: {e}")))?,
549 _ => Vec::new(),
550 };
551 let input = if request.input_base64.is_empty() {
552 Vec::new()
553 } else {
554 base64::decode(request.input_base64.as_str())
555 .map_err(|e| Error::InvalidConfig(format!("invalid input_base64: {e}")))?
556 };
557 let stage = crate::onion::OnionInvokeStage::new(request.shape, request.backend, constants)?;
558 let pipeline = stage.into_pipeline();
559
560 let did_filter: Option<std::collections::BTreeSet<Did>> =
561 request.eligible_dids.map(|dids| dids.into_iter().collect());
562 let stage_filter = request.eligible_stages;
563 let predicate = |desc: &crate::onion::OnionInvokeDescriptor| {
564 let did_ok = did_filter
565 .as_ref()
566 .is_none_or(|allowed| allowed.contains(&desc.did));
567 let stage_ok = stage_filter.as_ref().is_none_or(|allowed| {
568 allowed.iter().any(|cand| {
569 cand.did == desc.did
570 && cand
571 .process_epoch
572 .is_none_or(|epoch| epoch == desc.process_epoch)
573 && cand
574 .delegatee_public_key
575 .is_none_or(|pk| pk == desc.delegatee_public_key)
576 })
577 });
578 did_ok && stage_ok
579 };
580
581 #[cfg(all(feature = "browser", target_family = "wasm"))]
582 let route = browser::provider::onion_proxy::build_browser_onion_pipeline_route_filtered(
583 Arc::clone(&self.processor),
584 self.onion_directory_endpoint()?,
585 &pipeline,
586 predicate,
587 )
588 .await?;
589
590 #[cfg(not(all(feature = "browser", target_family = "wasm")))]
591 let route = self
592 .processor
593 .build_onion_pipeline_route_filtered(&pipeline, predicate)
594 .await?;
595
596 let stage_desc = route.descriptors().first().ok_or_else(|| {
597 Error::InvalidConfig("selected onion invoke route had no stage descriptor".to_string())
598 })?;
599 let stage_did = stage_desc.did;
600 let stage_process_epoch = stage_desc.process_epoch;
601 let stage_delegatee_public_key = stage_desc.delegatee_public_key;
602
603 let handle = self.onion_pipeline()?;
604 let timeout = request.timeout_ms.map(std::time::Duration::from_millis);
605 let output = handle
606 .invoke_pipeline_over_route_with_options(
607 &route,
608 &pipeline,
609 pipeline.loop_class(),
610 &input,
611 timeout,
612 )
613 .await?;
614 Ok(OnionInvokeRpcResponse {
615 stage_did,
616 stage_process_epoch,
617 stage_delegatee_public_key,
618 output_base64: base64::encode(&output),
619 })
620 }
621
622 pub fn extensions(&self) -> crate::extension::ext::Extensions {
625 self.extensions.clone()
626 }
627
628 pub(crate) fn onion_runtime(&self) -> Result<OnionRuntime> {
640 let mut slot = self.onion_runtime.lock().map_err(|_| Error::Lock)?;
641 if let Some(runtime) = slot.as_ref() {
642 return Ok(runtime.clone());
643 }
644 let runtime = OnionRuntime::install(&self.extensions())?;
645 *slot = Some(runtime.clone());
646 Ok(runtime)
647 }
648
649 pub(crate) fn install_relay_onion_runtime(&self) -> Result<()> {
656 if self.processor.onion_role().registers_relay() {
657 self.onion_runtime().map(drop)
658 } else {
659 Ok(())
660 }
661 }
662
663 pub fn onion_pipeline(&self) -> Result<crate::onion::OnionPipelineHandle> {
666 self.onion_runtime()
667 .map(crate::onion::OnionPipelineHandle::new)
668 }
669
670 pub(crate) fn dispatch_drops(&self) -> Arc<DispatchDrops> {
672 Arc::clone(&self.dispatch_drops)
673 }
674
675 pub fn dispatch_drop_counters(&self) -> DispatchDropCounters {
677 self.dispatch_drops.counters()
678 }
679
680 pub(crate) fn take_e2e_events_internal(&self) -> Result<TakeE2eEventsResponse> {
681 self.e2e_inbox.take()
682 }
683
684 #[cfg(not(all(feature = "browser", target_family = "wasm")))]
686 pub fn take_e2e_events(&self) -> Result<TakeE2eEventsResponse> {
687 self.take_e2e_events_internal()
688 }
689
690 pub(crate) fn signing_horizon_snapshot(&self) -> SigningHorizonSnapshot {
691 let now_ms = self.processor.clock().now_ms();
692 let horizon = self.processor.signing_horizon();
693 SigningHorizonSnapshot {
694 expires_at_ms: horizon.expires_at_ms().to_string(),
695 horizon_ms: horizon.horizon_ms().to_string(),
696 remaining_ms: horizon.horizon_ms().saturating_sub(now_ms).to_string(),
697 signs_now: horizon.signs_at(now_ms),
698 }
699 }
700
701 #[cfg(not(all(feature = "browser", target_family = "wasm")))]
703 pub fn signing_horizon(&self) -> DelegationHorizon {
704 self.processor.signing_horizon()
705 }
706
707 #[cfg(not(all(feature = "browser", target_family = "wasm")))]
709 pub fn renew_delegatee_key(&self, next: DelegateeKey) -> Result<DelegationHorizon> {
710 self.processor
711 .renew_delegatee_key(next, self.processor.clock().now_ms())
712 }
713
714 pub(crate) fn core(&self) -> crate::extension::ext::Core {
717 self.extensions.core()
718 }
719
720 pub fn register_protocol<P, I>(&self, protocol: P, interpret: I) -> Result<()>
724 where
725 P: crate::extension::ext::Protocol + rings_runtime::MaybeSendSync + 'static,
726 P::State: rings_runtime::MaybeSendSync + 'static,
727 P::Effect: rings_runtime::MaybeSendSync,
728 I: crate::extension::ext::Interpret<Effect = P::Effect>
729 + rings_runtime::MaybeSendSync
730 + 'static,
731 {
732 self.extensions.register(protocol, interpret)
733 }
734
735 pub async fn send(
738 &self,
739 to: rings_core::dht::Did,
740 namespace: &str,
741 payload: bytes::Bytes,
742 ) -> Result<()> {
743 self.core().send(to, namespace, payload).await
744 }
745
746 pub async fn peer_measurement(&self, did: Did) -> Option<PeerMeasurement> {
748 self.processor.peer_measurement(did).await
749 }
750
751 pub async fn peer_measurements(&self) -> Vec<PeerMeasurement> {
753 self.processor.peer_measurements().await
754 }
755
756 pub async fn provisional_evidence_page(
758 &self,
759 after: Option<EvidenceDigest>,
760 limit: std::num::NonZeroUsize,
761 ) -> std::result::Result<EvidencePage<Did>, EvidenceError> {
762 self.processor.provisional_evidence_page(after, limit).await
763 }
764
765 pub async fn provisional_evidence_counters(&self) -> EvidenceCounters {
767 self.processor.provisional_evidence_counters().await
768 }
769
770 pub fn origin_quota_counters(&self) -> rings_core::message::OriginQuotaCounters {
772 self.processor.origin_quota_counters()
773 }
774
775 pub(crate) async fn flush_measurements(&self) -> Result<()> {
776 self.processor.flush_measurements().await
777 }
778
779 pub async fn registrations_published(&self) {
782 self.processor.registrations_published().await
783 }
784
785 pub(crate) async fn leave_internal(&self) -> Result<()> {
786 self.processor.leave().await
787 }
788
789 #[cfg(not(all(feature = "browser", target_family = "wasm")))]
793 pub async fn leave(&self) -> Result<()> {
794 self.leave_internal().await
795 }
796
797 pub async fn close(self) -> Result<()> {
836 self.close_with_drain_timeout(CLOSE_DRAIN_TIMEOUT).await
837 }
838
839 pub(crate) async fn close_with_drain_timeout(
840 self,
841 drain_timeout: std::time::Duration,
842 ) -> Result<()> {
843 let tasks = self.processor.tasks().clone();
844 tasks.stop();
845 await_close_phase(
846 self.processor.await_listener_generations(),
847 drain_timeout,
848 "listener_generations",
849 )
850 .await;
851 await_close_phase(tasks.drained(), drain_timeout, "tasks_before_network_close").await;
852 let closed = self.processor.close_with_timeout(drain_timeout).await;
853 await_close_phase(tasks.drained(), drain_timeout, "tasks_after_network_close").await;
854 let released = self.processor.stores_released();
855 let Self {
856 processor,
857 handler,
858 extensions,
859 dispatch_drops,
860 e2e_inbox,
861 custom_rpc,
862 onion_runtime,
863 #[cfg(all(feature = "browser", target_family = "wasm"))]
864 onion_directory_endpoint,
865 #[cfg(all(feature = "browser", target_family = "wasm"))]
866 browser_mail,
867 #[cfg(all(feature = "browser", target_family = "wasm"))]
868 pagehide,
869 } = self;
870 drop((
871 handler,
872 extensions,
873 dispatch_drops,
874 e2e_inbox,
875 custom_rpc,
876 onion_runtime,
877 ));
878 #[cfg(all(feature = "browser", target_family = "wasm"))]
879 drop((onion_directory_endpoint, browser_mail, pagehide));
880 match Arc::into_inner(processor) {
882 Some(processor) => {
883 drop(processor);
884 if !await_close_phase(
885 std::future::IntoFuture::into_future(released.clone()),
886 drain_timeout,
887 "stores_released",
888 )
889 .await
890 {
891 if let Err(error) = closed {
892 tracing::warn!(%error, "a closing node whose stores are still held failed to close its network");
893 }
894 return Err(Error::ProviderStillShared { released });
895 }
896 closed
897 }
898 None => {
899 if let Err(error) = closed {
900 tracing::warn!(%error, "a shared node failed to close its network");
901 }
902 Err(Error::ProviderStillShared { released })
903 }
904 }
905 }
906
907 pub(crate) async fn new_provider_with_storage_internal(
909 config: ProcessorConfig,
910 stores: ProviderStores,
911 ) -> Result<Provider> {
912 Self::new_provider_with_storage_and_mail_internal(config, stores, None).await
913 }
914
915 async fn new_provider_with_storage_and_mail_internal(
918 config: ProcessorConfig,
919 stores: ProviderStores,
920 mail_offer: Option<MailOffer>,
921 ) -> Result<Provider> {
922 let ProviderStores {
923 entry: entry_storage,
924 relay: relay_storage,
925 removals: removal_storage,
926 measure: measure_storage,
927 evidence: evidence_storage,
928 guards: onion_entry_guard_storage,
929 replay: replay_storage,
930 released,
931 } = stores;
932 let entry_storage = entry_storage.unwrap_or_else(|| Box::new(MemStorage::new()));
933 let measure_storage = measure_storage.unwrap_or_else(|| Box::new(MemStorage::new()));
934 let evidence_storage = evidence_storage
935 .unwrap_or_else(|| Box::new(UnavailableEvidenceStorage) as EvidenceStorage);
936 let onion_entry_guard_storage =
937 onion_entry_guard_storage.unwrap_or_else(|| Box::new(MemStorage::new()));
938
939 let collector = EvidenceCollectorIdentity::new(
940 config.network_id(),
941 config.delegatee_key().delegator_did(),
942 );
943 let measure = PeriodicMeasure::new_with_evidence_storage_and_clock(
944 measure_storage,
945 evidence_storage,
946 collector,
947 config.clock().clone(),
948 )
949 .await?;
950
951 let processor_builder = ProcessorBuilder::from_config(&config)?
952 .storage(entry_storage)
953 .onion_entry_guard_storage(onion_entry_guard_storage)
954 .measure(measure)
955 .stores_released(released);
956 let processor_builder = match replay_storage {
957 Some(replay_storage) => processor_builder.replay_storage(replay_storage),
958 None => processor_builder,
959 };
960 let processor_builder = match relay_storage {
961 Some(relay_storage) => processor_builder.relay_storage(relay_storage),
962 None => processor_builder,
963 };
964 let processor_builder = match removal_storage {
965 Some(removal_storage) => processor_builder.removal_storage(removal_storage),
966 None => processor_builder,
967 };
968 let processor_builder = match mail_offer {
969 Some(offer) => processor_builder.receive_mail(offer),
970 None => processor_builder,
971 };
972
973 let processor = Arc::new(processor_builder.build()?);
974
975 Ok(Self::from_processor(processor))
976 }
977
978 pub(crate) async fn new_provider_internal(
987 network_id: u32,
988 ice_servers: String,
989 stabilize_interval: u64,
990 account: String,
991 account_type: String,
992 signer: Signer,
993 stores: ProviderStores,
994 ) -> Result<Provider> {
995 Self::new_provider_internal_with_config(
996 network_id,
997 ice_servers,
998 stabilize_interval,
999 account,
1000 account_type,
1001 signer,
1002 stores,
1003 core::convert::identity,
1004 )
1005 .await
1006 }
1007
1008 pub(crate) async fn mint_delegatee_key(
1009 account: String,
1010 account_type: String,
1011 signer: Signer,
1012 ) -> Result<DelegateeKey> {
1013 let mut sk_builder = DelegationBuilder::new(account, account_type);
1014 let proof = sk_builder.unsigned_proof();
1015 let sig = match signer {
1016 Signer::Sync(s) => s(proof)?,
1017 Signer::Async(s) => s(proof).await?,
1018 };
1019 sk_builder = sk_builder.set_delegator_signature(sig);
1020 sk_builder.build().map_err(Error::InternalError)
1021 }
1022
1023 #[allow(clippy::too_many_arguments)]
1024 pub(crate) async fn new_provider_internal_with_config(
1025 network_id: u32,
1026 ice_servers: String,
1027 stabilize_interval: u64,
1028 account: String,
1029 account_type: String,
1030 signer: Signer,
1031 stores: ProviderStores,
1032 configure: impl FnOnce(ProcessorConfig) -> ProcessorConfig,
1033 ) -> Result<Provider> {
1034 let delegatee_key = Self::mint_delegatee_key(account, account_type, signer).await?;
1035 let config =
1036 ProcessorConfig::new(network_id, ice_servers, delegatee_key, stabilize_interval);
1037 let config = configure(config);
1038 Self::new_provider_with_storage_internal(config, stores).await
1039 }
1040
1041 pub fn set_backend(&self) -> Result<()> {
1053 self.serve_application(None)
1054 }
1055
1056 pub fn set_backend_with_observer(&self, observer: Arc<dyn BackendObserver>) -> Result<()> {
1058 self.serve_application(Some(observer))
1059 }
1060
1061 pub(crate) fn serve_application(
1063 &self,
1064 observer: Option<Arc<dyn BackendObserver>>,
1065 ) -> Result<()> {
1066 let tasks = self.processor.tasks();
1067 let spawner = tasks.spawner().map_err(|_| {
1069 Error::ExtensionError("no runtime to serve the application inbox".to_owned())
1070 })?;
1071 let service = self.application_service(observer, tasks.stop_token())?;
1072 spawner.spawn(service);
1073 Ok(())
1074 }
1075
1076 pub fn application_service(
1093 &self,
1094 observer: Option<Arc<dyn BackendObserver>>,
1095 stop: StopToken,
1096 ) -> Result<impl Future<Output = ()> + 'static> {
1097 let inbox = self
1098 .processor
1099 .swarm
1100 .application_inbox()
1101 .map_err(Error::InternalError)?;
1102 let composite_observer: Arc<dyn BackendObserver> = Arc::new(CompositeBackendObserver {
1103 e2e_inbox: Arc::clone(&self.e2e_inbox),
1104 extra: observer,
1105 });
1106 let backend = Backend::new(Arc::new(self.clone())).observed_by(composite_observer);
1107 Ok(backend.serve(inbox, stop))
1108 }
1109
1110 pub async fn request_internal(
1113 &self,
1114 method: String,
1115 params: serde_json::Value,
1116 ) -> Result<serde_json::Value> {
1117 tracing::debug!("request {}", method);
1118 match method.as_str() {
1119 "takeE2eEvents" => return Ok(serde_json::to_value(self.take_e2e_events_internal()?)?),
1120 "dispatchDropCounters" => {
1121 return Ok(serde_json::to_value(self.dispatch_drop_counters())?);
1122 }
1123 "signingHorizon" => return Ok(serde_json::to_value(self.signing_horizon_snapshot())?),
1124 "renewDelegateeKey" => {
1125 let raw_key = params
1126 .get("delegatee_key")
1127 .and_then(serde_json::Value::as_str)
1128 .ok_or_else(|| {
1129 Error::InternalRpcError(jsonrpc_core::Error::invalid_params(
1130 "missing string field `delegatee_key`",
1131 ))
1132 })?;
1133 let next = DelegateeKey::from_str(raw_key)?;
1134 self.processor
1135 .renew_delegatee_key(next, self.processor.clock().now_ms())?;
1136 return Ok(serde_json::to_value(self.signing_horizon_snapshot())?);
1137 }
1138 "lookupRegistry" => {
1139 let topic = params
1140 .get("topic")
1141 .and_then(serde_json::Value::as_str)
1142 .ok_or_else(|| {
1143 Error::InternalRpcError(jsonrpc_core::Error::invalid_params(
1144 "missing string field `topic`",
1145 ))
1146 })?;
1147 let resp = self.lookup_registry_raw(topic).await?;
1148 return Ok(serde_json::to_value(resp)?);
1149 }
1150 "onionInvoke" => {
1151 let req: OnionInvokeRpcRequest = serde_json::from_value(params).map_err(|e| {
1152 Error::InternalRpcError(jsonrpc_core::Error::invalid_params(format!(
1153 "invalid onionInvoke params: {e}"
1154 )))
1155 })?;
1156 let resp = self.onion_invoke_raw(req).await?;
1157 return Ok(serde_json::to_value(resp)?);
1158 }
1159 _ => {}
1160 }
1161 if !is_builtin_local_rpc_method(method.as_str()) {
1162 let custom_handler = {
1163 let table = self.custom_rpc.lock().map_err(|_| Error::Lock)?;
1164 table.get(method.as_str()).cloned()
1165 };
1166 if let Some(handler) = custom_handler {
1167 return handler.call(params).await;
1168 }
1169 }
1170 #[cfg(all(feature = "browser", target_family = "wasm"))]
1171 let onion_directory_endpoint = onion_directory_endpoint_from_rpc(method.as_str(), ¶ms);
1172 let result = self
1173 .handler
1174 .handle_request(self.processor.clone(), method, params)
1175 .await
1176 .map_err(Error::InternalRpcError)?;
1177 #[cfg(all(feature = "browser", target_family = "wasm"))]
1178 if let Some(endpoint) = onion_directory_endpoint {
1179 self.set_onion_directory_endpoint(Some(endpoint))?;
1180 }
1181 Ok(result)
1182 }
1183}
1184
1185#[cfg(feature = "node")]
1186impl Provider {
1187 pub async fn request<T>(
1189 &self,
1190 method: rings_rpc::method::Method,
1191 params: T,
1192 ) -> Result<serde_json::Value>
1193 where
1194 T: serde::Serialize,
1195 {
1196 let params = serde_json::to_value(params)?;
1197 self.request_internal(method.to_string(), params).await
1198 }
1199
1200 pub async fn listen(&self) -> Result<()> {
1206 self.install_relay_onion_runtime()?;
1207 self.processor.listen().await;
1208 Ok(())
1209 }
1210
1211 pub async fn listen_with(&self, stop: StopToken) -> Result<()> {
1216 self.install_relay_onion_runtime()?;
1217 self.processor.listen_with(stop).await;
1218 Ok(())
1219 }
1220
1221 pub fn onion_circuit(&self) -> Result<NativeOnionCircuitHandle> {
1229 self.onion_runtime().map(NativeOnionCircuitHandle::new)
1230 }
1231}
1232
1233#[cfg(all(feature = "browser", target_family = "wasm"))]
1234fn onion_directory_endpoint_from_rpc(
1235 method: &str,
1236 params: &serde_json::Value,
1237) -> Option<BrowserDirectoryEndpoint> {
1238 if !matches!(method, "connectPeerViaHttp" | "ConnectPeerViaHttp") {
1239 return None;
1240 }
1241 let url = params
1242 .get("url")
1243 .and_then(serde_json::Value::as_str)
1244 .map(str::trim)
1245 .filter(|url| !url.is_empty())
1246 .map(ToOwned::to_owned)?;
1247 let api_token = params
1248 .get("api_token")
1249 .and_then(serde_json::Value::as_str)
1250 .map(str::trim)
1251 .filter(|token| !token.is_empty())
1252 .map(Arc::<str>::from)?;
1253 Some(BrowserDirectoryEndpoint {
1254 url,
1255 api_token: Some(api_token),
1256 })
1257}
1258
1259#[cfg(all(feature = "browser", target_family = "wasm"))]
1260impl Provider {
1261 pub(crate) fn set_onion_directory_endpoint(
1262 &self,
1263 endpoint: Option<BrowserDirectoryEndpoint>,
1264 ) -> Result<()> {
1265 let mut slot = self
1266 .onion_directory_endpoint
1267 .lock()
1268 .map_err(|_| Error::Lock)?;
1269 *slot = endpoint;
1270 Ok(())
1271 }
1272
1273 pub(crate) fn onion_directory_endpoint(&self) -> Result<Option<BrowserDirectoryEndpoint>> {
1274 self.onion_directory_endpoint
1275 .lock()
1276 .map(|slot| slot.clone())
1277 .map_err(|_| Error::Lock)
1278 }
1279}
1280
1281#[cfg(all(test, feature = "node", not(target_family = "wasm")))]
1282mod local_rpc_tests {
1283 use std::sync::Arc;
1284
1285 use async_trait::async_trait;
1286 use rings_core::delegation::DelegateeKey;
1287 use rings_core::ecc::SecretKey;
1288 use rings_core::storage::MemStorage;
1289 use serde_json::json;
1290
1291 use super::LocalRpcMethod;
1292 use super::Provider;
1293 use crate::processor::ProcessorBuilder;
1294 use crate::processor::ProcessorConfig;
1295
1296 struct EchoMethod;
1297
1298 #[async_trait]
1299 impl LocalRpcMethod for EchoMethod {
1300 async fn call(&self, params: serde_json::Value) -> crate::error::Result<serde_json::Value> {
1301 Ok(params)
1302 }
1303 }
1304
1305 fn test_provider() -> crate::error::Result<Provider> {
1306 let key = SecretKey::random();
1307 let delegatee_key = DelegateeKey::new_with_seckey(&key)?;
1308 let config =
1309 ProcessorConfig::new(1, String::new(), delegatee_key, 200).dht_virtual_nodes(0);
1310 let replay = Box::new(MemStorage::new());
1311 let processor = Arc::new(
1312 ProcessorBuilder::from_config(&config)?
1313 .advertise_presence(false)
1314 .replay_storage(replay)
1315 .build()?,
1316 );
1317 Ok(Provider::from_processor(processor))
1318 }
1319
1320 #[tokio::test]
1321 async fn register_local_rpc_method_rejects_builtins_whitespace_and_duplicates(
1322 ) -> crate::error::Result<()> {
1323 let provider = test_provider()?;
1324 for invalid in [
1325 "",
1326 " ",
1327 " customMethod",
1328 "customMethod ",
1329 "nodeDid",
1330 "connectPeerViaHttp",
1331 "ConnectPeerViaHttp",
1332 "takeE2eEvents",
1333 "dispatchDropCounters",
1334 "signingHorizon",
1335 "renewDelegateeKey",
1336 "lookupRegistry",
1337 "onionInvoke",
1338 ] {
1339 assert!(
1340 provider
1341 .register_local_rpc_method(invalid, EchoMethod)
1342 .is_err(),
1343 "expected {invalid:?} to be rejected"
1344 );
1345 }
1346
1347 provider.register_local_rpc_method("ext.echo", EchoMethod)?;
1348 assert!(
1349 provider
1350 .register_local_rpc_method("ext.echo", EchoMethod)
1351 .is_err(),
1352 "duplicate custom RPC method must be rejected"
1353 );
1354 let echoed = provider
1355 .request_internal("ext.echo".to_string(), json!({"hello": "world"}))
1356 .await?;
1357 assert_eq!(echoed, json!({"hello": "world"}));
1358 provider.close().await?;
1359 Ok(())
1360 }
1361}