Skip to main content

rings_node/provider/
mod.rs

1//! General Provider, this module provide Provider implementation for FFI and WASM
2
3use 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
95/// Maximum E2E events retained in a provider's bounded [`E2eInbox`] before further events drop.
96const E2E_EVENT_CAPACITY: usize = 4096;
97
98/// One inbound E2E handshake or stream-frame event retained by [`Provider`].
99#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
100pub struct E2eEvent {
101    /// Event kind (`"handshakeRequest"`, `"handshakeResponse"`, or `"streamFrame"`).
102    pub kind: String,
103    /// Verified sender DID.
104    pub from: String,
105    /// Sender / responder compressed secp256k1 public key when present.
106    pub public_key: Option<String>,
107    /// Per-frame ECIES ephemeral secp256k1 public key for `"streamFrame"` events.
108    pub ephemeral_public_key: Option<String>,
109    /// Stream UUID for `"streamFrame"` events.
110    pub stream_id: Option<String>,
111    /// Stream sequence number for `"streamFrame"` events.
112    pub sequence: Option<u64>,
113    /// Whether this frame terminates the stream.
114    pub is_final: Option<bool>,
115    /// Legacy block count reported for `"streamFrame"` events.
116    pub ciphertext_blocks: Option<usize>,
117    /// Base64-encoded ciphertext payload for `"streamFrame"` events.
118    pub ciphertext: Option<String>,
119}
120
121/// Snapshot returned when draining retained E2E events from [`Provider`].
122#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
123pub struct TakeE2eEventsResponse {
124    /// Events retained since the previous drain.
125    pub events: Vec<E2eEvent>,
126    /// Cumulative events dropped since provider creation because the bounded inbox was full.
127    pub dropped: u64,
128}
129
130/// JSON/JS-safe snapshot of this node's active delegation signing horizon.
131#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
132pub struct SigningHorizonSnapshot {
133    /// Delegation expiry timestamp in Unix epoch milliseconds (decimal string).
134    pub expires_at_ms: String,
135    /// First millisecond at which outbound frames can no longer be signed (decimal string).
136    pub horizon_ms: String,
137    /// Milliseconds remaining before `horizon_ms` at snapshot time (decimal string).
138    pub remaining_ms: String,
139    /// Whether this node can sign outbound frames at snapshot time.
140    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/// One raw element observed in a DHT registry carrier (`lookupRegistry`).
283#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
284pub struct RegistryElementSnapshot {
285    /// Base64-encoded `rings_codec` element bytes.
286    pub data_base64: String,
287    /// CRDT dot logical timestamp `τ*` in Unix epoch milliseconds (decimal string in JSON).
288    #[serde(with = "u128_decimal_string")]
289    pub heartbeat_at_ms: u128,
290}
291
292/// Response returned by the generic `lookupRegistry` local RPC primitive.
293#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
294pub struct LookupRegistryResponse {
295    /// Queried DHT registry topic string.
296    pub topic: String,
297    /// Local overlay network identifier.
298    pub network_id: u32,
299    /// Local processor clock timestamp in Unix epoch milliseconds when read (decimal string in JSON).
300    #[serde(with = "u128_decimal_string")]
301    pub now_ms: u128,
302    /// Normalized elements currently carried in the registry entry.
303    pub elements: Vec<RegistryElementSnapshot>,
304}
305
306/// Optional concrete stage filter `(did, process_epoch, delegatee_public_key)` for `onionInvoke`.
307#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
308pub struct OnionEligibleStage {
309    /// Candidate stage node account [`Did`].
310    pub did: Did,
311    /// Optional concrete [`crate::onion::OnionProcessEpoch`] of the target process.
312    #[serde(default, skip_serializing_if = "Option::is_none")]
313    pub process_epoch: Option<crate::onion::OnionProcessEpoch>,
314    /// Optional concrete session [`PublicKey<33>`] of the target process.
315    #[serde(default, skip_serializing_if = "Option::is_none")]
316    pub delegatee_public_key: Option<PublicKey<33>>,
317}
318
319/// Request payload for the generic 1-stage `onionInvoke` local RPC primitive.
320#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
321pub struct OnionInvokeRpcRequest {
322    /// Closed `invoke<In, Out, L>` shape symbol.
323    pub shape: crate::onion::OnionInvokeShape,
324    /// Canonical open backend name `ω`.
325    pub backend: crate::onion::OnionBackendName,
326    /// Optional base64-encoded inline constants `ā′`.
327    #[serde(default, skip_serializing_if = "Option::is_none")]
328    pub constants_base64: Option<String>,
329    /// Base64-encoded fixed-width input frame (`0` bytes for `Unit`).
330    #[serde(default)]
331    pub input_base64: String,
332    /// Optional eligible stage DID allowlist.
333    #[serde(default, skip_serializing_if = "Option::is_none")]
334    pub eligible_dids: Option<Vec<Did>>,
335    /// Optional eligible concrete `(did, process_epoch)` stage allowlist.
336    #[serde(default, skip_serializing_if = "Option::is_none")]
337    pub eligible_stages: Option<Vec<OnionEligibleStage>>,
338    /// Optional caller timeout in milliseconds.
339    #[serde(default, skip_serializing_if = "Option::is_none")]
340    pub timeout_ms: Option<u64>,
341}
342
343/// Response payload returned by the generic `onionInvoke` local RPC primitive.
344#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
345pub struct OnionInvokeRpcResponse {
346    /// Account [`Did`] of the selected stage host.
347    pub stage_did: Did,
348    /// Process epoch (`OnionProcessEpoch`) of the selected stage host.
349    pub stage_process_epoch: crate::onion::OnionProcessEpoch,
350    /// Session delegatee public key (`PublicKey<33>`) of the selected stage host.
351    pub stage_delegatee_public_key: PublicKey<33>,
352    /// Base64-encoded fixed-width output frame returned by the stage.
353    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/// Asynchronous local RPC handler registered on a [`Provider`] by external service crates.
370#[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    /// Handle one JSON-RPC call invoked via [`Provider::request_internal`].
374    async fn call(&self, params: serde_json::Value) -> Result<serde_json::Value>;
375}
376
377/// General Provider holding the node processor, RPC dispatcher, and extension registry.
378#[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    /// External local RPC methods installed on this provider.
388    custom_rpc: Arc<Mutex<BTreeMap<String, Arc<dyn LocalRpcMethod>>>>,
389    /// The onion runtime installed in this provider's registry, shared by its clones; its lock
390    /// serializes the check-and-install, so the runtime is installed at most once.
391    onion_runtime: Arc<Mutex<Option<OnionRuntime>>>,
392    #[cfg(all(feature = "browser", target_family = "wasm"))]
393    onion_directory_endpoint: Arc<Mutex<Option<BrowserDirectoryEndpoint>>>,
394    /// The retained browser inbox and its recipient, shared by provider clones. Law: only a
395    /// constructor that opts in before processor build installs this state.
396    #[cfg(all(feature = "browser", target_family = "wasm"))]
397    browser_mail: Option<std::rc::Rc<browser::provider::mail::BrowserMail>>,
398    /// Best-effort `pagehide` departure listener for browser providers (#1057).
399    #[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/// Async signer, without Send required
411#[cfg(all(feature = "browser", target_family = "wasm"))]
412pub type AsyncSigner = Box<dyn Fn(String) -> Pin<Box<dyn Future<Output = Result<Vec<u8>>>>>>;
413
414/// Async signer, use for non-wasm envirement, Send is necessary
415#[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/// Signer can be async and sync
419#[allow(clippy::type_complexity)]
420pub enum Signer {
421    /// Sync signer
422    Sync(Box<dyn Fn(String) -> Result<Vec<u8>>>),
423    /// Async signer
424    Async(AsyncSigner),
425}
426
427/// The stores a provider is built over, each optional: an absent one takes the default its
428/// builder documents (an in-memory store, or none where the law admits no volatile one).
429#[derive(Default)]
430pub(crate) struct ProviderStores {
431    /// The DHT data store (element sides).
432    pub(crate) entry: Option<EntryStorage>,
433    /// The relay-inbox store.
434    pub(crate) relay: Option<EntryStorage>,
435    /// The store of the data namespace's remove sides (#920).
436    pub(crate) removals: Option<RemovalStorage>,
437    /// The peer measurement store.
438    pub(crate) measure: Option<MeasureStorage>,
439    /// The provisional-evidence store.
440    pub(crate) evidence: Option<EvidenceStorage>,
441    /// The onion entry-guard store.
442    pub(crate) guards: Option<OnionEntryGuardStorage>,
443    /// The transaction replay store.
444    pub(crate) replay: Option<ReplayStorage>,
445    /// The release witnesses of the file stores above, none for a store with no directory.
446    pub(crate) released: StoresReleased,
447}
448
449#[allow(dead_code)]
450impl Provider {
451    /// Create provider from processor directly
452    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    /// Return a reference to the underlying [`Processor`] driving this provider.
475    pub const fn processor(&self) -> &Arc<Processor> {
476        &self.processor
477    }
478
479    /// Register an external [`LocalRpcMethod`] reachable through [`Self::request_internal`] (and
480    /// C FFI / browser RPC dispatch).
481    ///
482    /// Rejects empty method names, any built-in node/JSON-RPC method name, and duplicate
483    /// registrations on the same [`Provider`].
484    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    /// Fetch raw normalized elements of DHT registry `topic` together with CRDT dot timestamps,
512    /// local `network_id`, and local clock `now_ms`.
513    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    /// Evaluate a generic 1-stage Kleisli `invoke` pipeline over a guard-closed Sphinx loop,
540    /// optionally restricted to `eligible_dids` and/or concrete `(did, process_epoch)`
541    /// `eligible_stages`.
542    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    /// The shared protocol registry. The [`Backend`] serving core's application inbox clones
623    /// this, so registration (via the provider) and dispatch see the same table.
624    pub fn extensions(&self) -> crate::extension::ext::Extensions {
625        self.extensions.clone()
626    }
627
628    /// This provider's onion runtime, installed in its registry on first use: the data plane
629    /// with the processor's role, and for an exit the worlds of its offer the platform
630    /// interprets (`onion::runtime`).
631    ///
632    /// Idempotent within this provider's registry, which its clones share: the check and the
633    /// install run under the slot's lock, so concurrent callers install once and share the
634    /// runtime. Another provider over the same processor has its own registry.
635    ///
636    /// # Errors
637    ///
638    /// [`Error::Lock`] for a poisoned slot, or the failure of [`OnionRuntime::install`].
639    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    /// Install the onion runtime when the processor's role registers `relay`, so a node never
650    /// advertises a relay it does not run; a runtime installed before is kept.
651    ///
652    /// # Errors
653    ///
654    /// As for [`Self::onion_runtime`].
655    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    /// Cross-platform handle for registering intermediate `invoke` backends and evaluating
664    /// multi-stage Kleisli pipelines on this provider's onion runtime (#834 Phase 2b).
665    pub fn onion_pipeline(&self) -> Result<crate::onion::OnionPipelineHandle> {
666        self.onion_runtime()
667            .map(crate::onion::OnionPipelineHandle::new)
668    }
669
670    /// The drop counters the [`Backend`] serving this provider's application inbox records in.
671    pub(crate) fn dispatch_drops(&self) -> Arc<DispatchDrops> {
672        Arc::clone(&self.dispatch_drops)
673    }
674
675    /// The application envelopes the [`Backend`] dropped instead of dispatching, by reason.
676    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    /// Drain all retained inbound E2E handshake and stream-frame events.
685    #[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    /// Return the active delegation signing horizon of this node.
702    #[cfg(not(all(feature = "browser", target_family = "wasm")))]
703    pub fn signing_horizon(&self) -> DelegationHorizon {
704        self.processor.signing_horizon()
705    }
706
707    /// Renew this node's active session key in process before its signing horizon expires.
708    #[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    /// The capability handle — overlay `send` / `did` / self-addressed `inject`. (Authenticated
715    /// `dispatch` is router-only; `pub(crate)` so it never reaches public callers.)
716    pub(crate) fn core(&self) -> crate::extension::ext::Core {
717        self.extensions.core()
718    }
719
720    /// Register a pure [`Protocol`](crate::extension::ext::Protocol) together with its
721    /// [`Interpret`](crate::extension::ext::Interpret) shell under the protocol's namespace.
722    /// Errors if the namespace is already taken.
723    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    /// Send a namespaced payload to a peer. This is the uniform upper-layer send — a core
736    /// capability, identical on native and browser.
737    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    /// Return local measurement counters for a peer, if observed.
747    pub async fn peer_measurement(&self, did: Did) -> Option<PeerMeasurement> {
748        self.processor.peer_measurement(did).await
749    }
750
751    /// Return every retained local peer measurement.
752    pub async fn peer_measurements(&self) -> Vec<PeerMeasurement> {
753        self.processor.peer_measurements().await
754    }
755
756    /// Return one bounded page of canonical provisional service-receipt evidence.
757    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    /// Return aggregate provisional-evidence counters without account labels.
766    pub async fn provisional_evidence_counters(&self) -> EvidenceCounters {
767        self.processor.provisional_evidence_counters().await
768    }
769
770    /// Return aggregate final-destination origin-quota drops by lane and reason.
771    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    /// Resolves once every registration of this node is stored at its owners, as they reported
780    /// it ([`Processor::registrations_published`], #866).
781    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    /// Best-effort voluntary departure (#1057): hand off live relay carriers to remaining
790    /// members and send `Leave { successor_list }` to this node's predecessor and successor head
791    /// before transports close.
792    #[cfg(not(all(feature = "browser", target_family = "wasm")))]
793    pub async fn leave(&self) -> Result<()> {
794        self.leave_internal().await
795    }
796
797    /// Close this node and release every store it holds, so that the stores can be opened
798    /// again in this process: an in-process re-init (#1085).
799    ///
800    /// Law (close): the steps run in this order, each once the one before it has ended.
801    ///
802    /// ```text
803    ///   (a) stop     every node task is told to end; every listener generation ends
804    ///   (b) drain    no node task is live (the one-spawn law of `crate::tasks`)
805    ///   (c) network  every connection is closed, and no new one is admitted (#1098)
806    ///   (d) flush    the measurements are persisted
807    ///   (e) release  no node task is live again; the last clone of the node drops, and with
808    ///                it every store
809    /// ```
810    ///
811    /// Steps (c) and (d) are [`Processor::close`]. A node task spawned after (b), during (c) or
812    /// (d) (by a callback of the closing network, say), starts with the stop already fired: it
813    /// ends at its first suspension point, or winds down within its bound. (e) drains again
814    /// before the release, so no such task holds the node into it.
815    ///
816    /// Post: `Ok` means every store the node was built over is released and its directory
817    /// unlocked (the release law of `rings_core::storage::file`), so an open of those stores in
818    /// this process succeeds. `Err(Error::ProviderStillShared { released })` means another clone
819    /// of the node, a `Provider` or the [`Processor`] it shares, is still held. Steps (a) to (d)
820    /// have run, so the node is stopped and its network closed. Its stores are released only
821    /// when the last clone drops, and `released` resolves then. Any other `Err` is the first
822    /// failure of step (c) or (d); step (e) has run all the same, so the stores are released.
823    /// On the shared path a failure of (c) or (d) is logged, since `released` is what the
824    /// caller needs next.
825    ///
826    /// Bound: no step waits on a timer of its own: each is woken by the end it awaits. (a) and
827    /// (b) last one suspension of each node task. A task winding down at the stop (a relay
828    /// resetting its socket and sending its session's close) adds a send, bounded by the send
829    /// timeout, and a listener generation adds its measurement flush. (c) is the swarm's close
830    /// of its connections. (e) also awaits the tasks the core detached that still hold a part
831    /// of the node. Each of those either ends with the dropped node (an inbound actor, the
832    /// outbound workers, whose channels close with it), is bounded by its own timeout (a
833    /// handshake, a payload send), or is a replay transition or flush, which ends after its
834    /// write.
835    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        // Atomic: `Some` only for the last strong clone, which a `Weak` upgrade cannot race.
881        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    /// Create a provider instance with storage name
908    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    /// Build over `stores`, installing the chosen mail heartbeat before the processor exists.
916    /// Law: `None` publishes no mail descriptor; an offer is already schedule-validated.
917    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    /// Create a new provider instanice with everything in detail
979    /// Ice_servers should obey forrmat: `"[turn|strun]://<Address>:<Port>;..."`
980    /// Account is hex string
981    /// Account should format as same as account_type declared
982    /// Account_type is lowercase string, possible input are: `eip191`, `ed25519`, `bip137`, for more information,
983    /// please check [rings_core::ecc]
984    /// Signer should accept a String and returns bytes.
985    /// Signer should function as same as account_type declared, Eg: eip191 or secp256k1 or ed25519.
986    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    /// Serve the swarm's application inbox with the extension [`Backend`] on a detached task,
1042    /// so inbound custom messages are decoded as
1043    /// [`Envelope`](crate::extension::ext::Envelope)s and routed to their namespace's protocol.
1044    /// Call once, after registering every protocol whose messages may already be on their way
1045    /// (relay mail included): from the claim on, an envelope of a namespace not yet registered
1046    /// is dropped, counted. The inbox is claimed once, so a second call fails with
1047    /// `ApplicationInboxClaimed`. Serving lasts until the node is closed ([`Provider::close`]):
1048    /// the service is a node task (#1085). Use
1049    /// [`application_service`](Provider::application_service) for one under a stop of the
1050    /// caller's.
1051    /// Spawn the application-inbox consumer over this provider's protocol registry.
1052    pub fn set_backend(&self) -> Result<()> {
1053        self.serve_application(None)
1054    }
1055
1056    /// Spawn the application-inbox consumer with an explicit [`BackendObserver`].
1057    pub fn set_backend_with_observer(&self, observer: Arc<dyn BackendObserver>) -> Result<()> {
1058        self.serve_application(Some(observer))
1059    }
1060
1061    /// [`Self::set_backend`] with `observer` handed the peer facts and unrouted E2E messages.
1062    pub(crate) fn serve_application(
1063        &self,
1064        observer: Option<Arc<dyn BackendObserver>>,
1065    ) -> Result<()> {
1066        let tasks = self.processor.tasks();
1067        // Acquired before the inbox is claimed, so a missing runtime claims nothing.
1068        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    /// Claim the swarm's application inbox now and return the future that serves it with the
1077    /// extension [`Backend`] over this provider's protocol registry, handing peer facts and
1078    /// unrouted E2E messages to `observer`, until the swarm is gone or `stop` is requested.
1079    ///
1080    /// ```text
1081    ///   application_service(o, s) = claim inbox  ;  pure (serve_o(inbox, s))
1082    ///   serve_o                    = Backend::new(self).observed_by(o).serve
1083    /// ```
1084    ///
1085    /// The claim is eager, so data that arrives before the caller spawns the future waits in
1086    /// the inbox instead of being discarded unclaimed; the caller owns only the spawner and the
1087    /// stop token. As with [`set_backend`](Provider::set_backend), register protocols first:
1088    /// an envelope of a namespace not yet registered when it is read is dropped, counted. The
1089    /// inbox is claimed once (see
1090    /// [`Swarm::application_inbox`](rings_core::swarm::Swarm::application_inbox)), so a second
1091    /// call fails.
1092    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    /// Request local rpc interface
1111    /// the internal rpc interface is provide by rings_rpc
1112    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(), &params);
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    /// A request function implementation for native provider
1188    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    /// Listen for messages until this future is dropped or aborted.
1201    ///
1202    /// This is a long-running task; do not await completion as a readiness signal. Listening
1203    /// publishes the processor's registrations, so a role that registers `relay` first installs
1204    /// its onion runtime (`install_relay_onion_runtime`).
1205    pub async fn listen(&self) -> Result<()> {
1206        self.install_relay_onion_runtime()?;
1207        self.processor.listen().await;
1208        Ok(())
1209    }
1210
1211    /// Listen for messages until `stop` requests cooperative shutdown.
1212    ///
1213    /// This is a long-running task; do not await completion as a readiness signal. Like
1214    /// [`Self::listen`], it first installs the onion runtime of a role that registers `relay`.
1215    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    /// The native handle of this provider's onion runtime. The runtime is installed in this
1222    /// provider's registry on first use, once for all its clones, and shared afterwards.
1223    ///
1224    /// # Errors
1225    ///
1226    /// [`Error::Lock`] for a poisoned runtime slot, or a registry or runtime failure of the
1227    /// install.
1228    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}