1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
//! General Provider, this module provide Provider implementation for FFI and WASM
use std::future::Future;
use std::pin::Pin;
use std::sync::Arc;
use std::sync::Mutex;
use rings_core::delegation::DelegationBuilder;
use rings_core::dht::Did;
use rings_core::dht::EntryStorage;
use rings_core::dht::RemovalStorage;
use rings_core::lifecycle::StopToken;
use rings_core::measure::EvidenceCounters;
use rings_core::measure::EvidenceDigest;
use rings_core::measure::EvidenceError;
use rings_core::measure::EvidencePage;
use rings_core::measure::PeerMeasurement;
use rings_core::message::ReplayStorage;
use rings_core::storage::MemStorage;
use rings_rpc::protos::rings_node_handler::InternalRpcHandler;
use crate::error::Error;
use crate::error::Result;
use crate::extension::Backend;
use crate::extension::BackendObserver;
use crate::extension::DispatchDropCounters;
use crate::extension::DispatchDrops;
use crate::mail::registration::MailOffer;
use crate::measure::EvidenceCollectorIdentity;
use crate::measure::EvidenceStorage;
use crate::measure::MeasureStorage;
use crate::measure::PeriodicMeasure;
use crate::measure::UnavailableEvidenceStorage;
#[cfg(feature = "node")]
use crate::onion::native::NativeOnionCircuitHandle;
use crate::onion::runtime::OnionRuntime;
use crate::onion::OnionEntryGuardStorage;
use crate::prelude::wasm_export;
use crate::processor::Processor;
use crate::processor::ProcessorBuilder;
use crate::processor::ProcessorConfig;
use crate::release::StoresReleased;
#[cfg(all(feature = "browser", target_family = "wasm"))]
pub mod browser;
#[cfg(feature = "ffi")]
pub mod ffi;
/// General Provider, which holding reference of Processor
/// Provider should be obey memory layout of CLang
/// Provider should be export for wasm-bindgen
#[derive(Clone)]
#[allow(dead_code)]
#[repr(C)]
#[wasm_export]
pub struct Provider {
processor: Arc<Processor>,
handler: InternalRpcHandler,
extensions: crate::extension::ext::Extensions,
dispatch_drops: Arc<DispatchDrops>,
/// The onion runtime installed in this provider's registry, shared by its clones; its lock
/// serializes the check-and-install, so the runtime is installed at most once.
onion_runtime: Arc<Mutex<Option<OnionRuntime>>>,
#[cfg(all(feature = "browser", target_family = "wasm"))]
onion_directory_endpoint: Arc<Mutex<Option<BrowserDirectoryEndpoint>>>,
/// The retained browser inbox and its recipient, shared by provider clones. Law: only a
/// constructor that opts in before processor build installs this state.
#[cfg(all(feature = "browser", target_family = "wasm"))]
browser_mail: Option<std::rc::Rc<browser::provider::mail::BrowserMail>>,
}
#[cfg(all(feature = "browser", target_family = "wasm"))]
#[derive(Clone)]
pub(crate) struct BrowserDirectoryEndpoint {
pub(crate) url: String,
pub(crate) api_token: Option<Arc<str>>,
}
/// Async signer, without Send required
#[cfg(all(feature = "browser", target_family = "wasm"))]
pub type AsyncSigner = Box<dyn Fn(String) -> Pin<Box<dyn Future<Output = Vec<u8>>>>>;
/// Async signer, use for non-wasm envirement, Send is necessary
#[cfg(not(all(feature = "browser", target_family = "wasm")))]
pub type AsyncSigner = Box<dyn Fn(String) -> Pin<Box<dyn Future<Output = Vec<u8>> + Send>>>;
/// Signer can be async and sync
#[allow(clippy::type_complexity)]
pub enum Signer {
/// Sync signer
Sync(Box<dyn Fn(String) -> Vec<u8>>),
/// Async signer
Async(AsyncSigner),
}
/// The stores a provider is built over, each optional: an absent one takes the default its
/// builder documents (an in-memory store, or none where the law admits no volatile one).
#[derive(Default)]
pub(crate) struct ProviderStores {
/// The DHT data store (element sides).
pub(crate) entry: Option<EntryStorage>,
/// The relay-inbox store.
pub(crate) relay: Option<EntryStorage>,
/// The store of the data namespace's remove sides (#920).
pub(crate) removals: Option<RemovalStorage>,
/// The peer measurement store.
pub(crate) measure: Option<MeasureStorage>,
/// The provisional-evidence store.
pub(crate) evidence: Option<EvidenceStorage>,
/// The onion entry-guard store.
pub(crate) guards: Option<OnionEntryGuardStorage>,
/// The transaction replay store.
pub(crate) replay: Option<ReplayStorage>,
/// The release witnesses of the file stores above, none for a store with no directory.
pub(crate) released: StoresReleased,
}
#[allow(dead_code)]
impl Provider {
/// Create provider from processor directly
pub fn from_processor(processor: Arc<Processor>) -> Self {
let extensions = crate::extension::ext::Extensions::new(processor.clone());
Self {
processor,
handler: InternalRpcHandler,
extensions,
dispatch_drops: Arc::default(),
onion_runtime: Arc::new(Mutex::new(None)),
#[cfg(all(feature = "browser", target_family = "wasm"))]
onion_directory_endpoint: Arc::new(Mutex::new(None)),
#[cfg(all(feature = "browser", target_family = "wasm"))]
browser_mail: None,
}
}
/// The shared protocol registry. The [`Backend`] serving core's application inbox clones
/// this, so registration (via the provider) and dispatch see the same table.
pub fn extensions(&self) -> crate::extension::ext::Extensions {
self.extensions.clone()
}
/// This provider's onion runtime, installed in its registry on first use: the data plane
/// with the processor's role, and for an exit the worlds of its offer the platform
/// interprets (`onion::runtime`).
///
/// Idempotent within this provider's registry, which its clones share: the check and the
/// install run under the slot's lock, so concurrent callers install once and share the
/// runtime. Another provider over the same processor has its own registry.
///
/// # Errors
///
/// [`Error::Lock`] for a poisoned slot, or the failure of [`OnionRuntime::install`].
pub(crate) fn onion_runtime(&self) -> Result<OnionRuntime> {
let mut slot = self.onion_runtime.lock().map_err(|_| Error::Lock)?;
if let Some(runtime) = slot.as_ref() {
return Ok(runtime.clone());
}
let runtime = OnionRuntime::install(&self.extensions())?;
*slot = Some(runtime.clone());
Ok(runtime)
}
/// Install the onion runtime when the processor's role registers `relay`, so a node never
/// advertises a relay it does not run; a runtime installed before is kept.
///
/// # Errors
///
/// As for [`Self::onion_runtime`].
pub(crate) fn install_relay_onion_runtime(&self) -> Result<()> {
if self.processor.onion_role().registers_relay() {
self.onion_runtime().map(drop)
} else {
Ok(())
}
}
/// The drop counters the [`Backend`] serving this provider's application inbox records in.
pub(crate) fn dispatch_drops(&self) -> Arc<DispatchDrops> {
Arc::clone(&self.dispatch_drops)
}
/// The application envelopes the [`Backend`] dropped instead of dispatching, by reason.
pub fn dispatch_drop_counters(&self) -> DispatchDropCounters {
self.dispatch_drops.counters()
}
/// The capability handle — overlay `send` / `did` / self-addressed `inject`. (Authenticated
/// `dispatch` is router-only; `pub(crate)` so it never reaches public callers.)
pub(crate) fn core(&self) -> crate::extension::ext::Core {
self.extensions.core()
}
/// Register a pure [`Protocol`](crate::extension::ext::Protocol) together with its
/// [`Interpret`](crate::extension::ext::Interpret) shell under the protocol's namespace.
/// Errors if the namespace is already taken.
pub fn register_protocol<P, I>(&self, protocol: P, interpret: I) -> Result<()>
where
P: crate::extension::ext::Protocol + rings_runtime::MaybeSendSync + 'static,
P::State: rings_runtime::MaybeSendSync + 'static,
P::Effect: rings_runtime::MaybeSendSync,
I: crate::extension::ext::Interpret<Effect = P::Effect>
+ rings_runtime::MaybeSendSync
+ 'static,
{
self.extensions.register(protocol, interpret)
}
/// Send a namespaced payload to a peer. This is the uniform upper-layer send — a core
/// capability, identical on native and browser.
pub async fn send(
&self,
to: rings_core::dht::Did,
namespace: &str,
payload: bytes::Bytes,
) -> Result<()> {
self.core().send(to, namespace, payload).await
}
/// Return local measurement counters for a peer, if observed.
pub async fn peer_measurement(&self, did: Did) -> Option<PeerMeasurement> {
self.processor.peer_measurement(did).await
}
/// Return every retained local peer measurement.
pub async fn peer_measurements(&self) -> Vec<PeerMeasurement> {
self.processor.peer_measurements().await
}
/// Return one bounded page of canonical provisional service-receipt evidence.
pub async fn provisional_evidence_page(
&self,
after: Option<EvidenceDigest>,
limit: std::num::NonZeroUsize,
) -> std::result::Result<EvidencePage<Did>, EvidenceError> {
self.processor.provisional_evidence_page(after, limit).await
}
/// Return aggregate provisional-evidence counters without account labels.
pub async fn provisional_evidence_counters(&self) -> EvidenceCounters {
self.processor.provisional_evidence_counters().await
}
/// Return aggregate final-destination origin-quota drops by lane and reason.
pub fn origin_quota_counters(&self) -> rings_core::message::OriginQuotaCounters {
self.processor.origin_quota_counters()
}
pub(crate) async fn flush_measurements(&self) -> Result<()> {
self.processor.flush_measurements().await
}
/// Resolves once every registration of this node is stored at its owners, as they reported
/// it ([`Processor::registrations_published`], #866).
pub async fn registrations_published(&self) {
self.processor.registrations_published().await
}
/// Close this node and release every store it holds, so that the stores can be opened
/// again in this process: an in-process re-init (#1085).
///
/// Law (close): the steps run in this order, each once the one before it has ended.
///
/// ```text
/// (a) stop every node task is told to end; every listener generation ends
/// (b) drain no node task is live (the one-spawn law of `crate::tasks`)
/// (c) network every connection is closed, and no new one is admitted (#1098)
/// (d) flush the measurements are persisted
/// (e) release no node task is live again; the last clone of the node drops, and with
/// it every store
/// ```
///
/// Steps (c) and (d) are [`Processor::close`]. A node task spawned after (b), during (c) or
/// (d) (by a callback of the closing network, say), starts with the stop already fired: it
/// ends at its first suspension point, or winds down within its bound. (e) drains again
/// before the release, so no such task holds the node into it.
///
/// Post: `Ok` means every store the node was built over is released and its directory
/// unlocked (the release law of `rings_core::storage::file`), so an open of those stores in
/// this process succeeds. `Err(Error::ProviderStillShared { released })` means another clone
/// of the node, a `Provider` or the [`Processor`] it shares, is still held. Steps (a) to (d)
/// have run, so the node is stopped and its network closed. Its stores are released only
/// when the last clone drops, and `released` resolves then. Any other `Err` is the first
/// failure of step (c) or (d); step (e) has run all the same, so the stores are released.
/// On the shared path a failure of (c) or (d) is logged, since `released` is what the
/// caller needs next.
///
/// Bound: no step waits on a timer of its own: each is woken by the end it awaits. (a) and
/// (b) last one suspension of each node task. A task winding down at the stop (a relay
/// resetting its socket and sending its session's close) adds a send, bounded by the send
/// timeout, and a listener generation adds its measurement flush. (c) is the swarm's close
/// of its connections. (e) also awaits the tasks the core detached that still hold a part
/// of the node. Each of those either ends with the dropped node (an inbound actor, the
/// outbound workers, whose channels close with it), is bounded by its own timeout (a
/// handshake, a payload send), or is a replay transition or flush, which ends after its
/// write.
pub async fn close(self) -> Result<()> {
let tasks = self.processor.tasks().clone();
tasks.stop();
self.processor.await_listener_generations().await;
tasks.drained().await;
let closed = self.processor.close().await;
tasks.drained().await;
let released = self.processor.stores_released();
let Self {
processor,
handler,
extensions,
dispatch_drops,
onion_runtime,
#[cfg(all(feature = "browser", target_family = "wasm"))]
onion_directory_endpoint,
#[cfg(all(feature = "browser", target_family = "wasm"))]
browser_mail,
} = self;
drop((handler, extensions, dispatch_drops, onion_runtime));
#[cfg(all(feature = "browser", target_family = "wasm"))]
drop((onion_directory_endpoint, browser_mail));
// Atomic: `Some` only for the last strong clone, which a `Weak` upgrade cannot race.
match Arc::into_inner(processor) {
Some(processor) => {
drop(processor);
released.await;
closed
}
None => {
if let Err(error) = closed {
tracing::warn!(%error, "a shared node failed to close its network");
}
Err(Error::ProviderStillShared { released })
}
}
}
/// Create a provider instance with storage name
pub(crate) async fn new_provider_with_storage_internal(
config: ProcessorConfig,
stores: ProviderStores,
) -> Result<Provider> {
Self::new_provider_with_storage_and_mail_internal(config, stores, None).await
}
/// Build over `stores`, installing the chosen mail heartbeat before the processor exists.
/// Law: `None` publishes no mail descriptor; an offer is already schedule-validated.
async fn new_provider_with_storage_and_mail_internal(
config: ProcessorConfig,
stores: ProviderStores,
mail_offer: Option<MailOffer>,
) -> Result<Provider> {
let ProviderStores {
entry: entry_storage,
relay: relay_storage,
removals: removal_storage,
measure: measure_storage,
evidence: evidence_storage,
guards: onion_entry_guard_storage,
replay: replay_storage,
released,
} = stores;
let entry_storage = entry_storage.unwrap_or_else(|| Box::new(MemStorage::new()));
let measure_storage = measure_storage.unwrap_or_else(|| Box::new(MemStorage::new()));
let evidence_storage = evidence_storage
.unwrap_or_else(|| Box::new(UnavailableEvidenceStorage) as EvidenceStorage);
let onion_entry_guard_storage =
onion_entry_guard_storage.unwrap_or_else(|| Box::new(MemStorage::new()));
let collector = EvidenceCollectorIdentity::new(
config.network_id(),
config.delegatee_key().delegator_did(),
);
let measure = PeriodicMeasure::new_with_evidence_storage(
measure_storage,
evidence_storage,
collector,
)
.await?;
let processor_builder = ProcessorBuilder::from_config(&config)?
.storage(entry_storage)
.onion_entry_guard_storage(onion_entry_guard_storage)
.measure(measure)
.stores_released(released);
let processor_builder = match replay_storage {
Some(replay_storage) => processor_builder.replay_storage(replay_storage),
None => processor_builder,
};
let processor_builder = match relay_storage {
Some(relay_storage) => processor_builder.relay_storage(relay_storage),
None => processor_builder,
};
let processor_builder = match removal_storage {
Some(removal_storage) => processor_builder.removal_storage(removal_storage),
None => processor_builder,
};
let processor_builder = match mail_offer {
Some(offer) => processor_builder.receive_mail(offer),
None => processor_builder,
};
let processor = Arc::new(processor_builder.build()?);
let extensions = crate::extension::ext::Extensions::new(processor.clone());
Ok(Provider {
processor,
handler: InternalRpcHandler,
extensions,
dispatch_drops: Arc::default(),
onion_runtime: Arc::new(Mutex::new(None)),
#[cfg(all(feature = "browser", target_family = "wasm"))]
onion_directory_endpoint: Arc::new(Mutex::new(None)),
#[cfg(all(feature = "browser", target_family = "wasm"))]
browser_mail: None,
})
}
/// Create a new provider instanice with everything in detail
/// Ice_servers should obey forrmat: `"[turn|strun]://<Address>:<Port>;..."`
/// Account is hex string
/// Account should format as same as account_type declared
/// Account_type is lowercase string, possible input are: `eip191`, `ed25519`, `bip137`, for more information,
/// please check [rings_core::ecc]
/// Signer should accept a String and returns bytes.
/// Signer should function as same as account_type declared, Eg: eip191 or secp256k1 or ed25519.
pub(crate) async fn new_provider_internal(
network_id: u32,
ice_servers: String,
stabilize_interval: u64,
account: String,
account_type: String,
signer: Signer,
stores: ProviderStores,
) -> Result<Provider> {
Self::new_provider_internal_with_config(
network_id,
ice_servers,
stabilize_interval,
account,
account_type,
signer,
stores,
core::convert::identity,
)
.await
}
#[allow(clippy::too_many_arguments)]
pub(crate) async fn new_provider_internal_with_config(
network_id: u32,
ice_servers: String,
stabilize_interval: u64,
account: String,
account_type: String,
signer: Signer,
stores: ProviderStores,
configure: impl FnOnce(ProcessorConfig) -> ProcessorConfig,
) -> Result<Provider> {
let mut sk_builder = DelegationBuilder::new(account, account_type);
let proof = sk_builder.unsigned_proof();
let sig = match signer {
Signer::Sync(s) => s(proof),
Signer::Async(s) => s(proof).await,
};
sk_builder = sk_builder.set_delegator_signature(sig.to_vec());
let delegatee_key = sk_builder.build().map_err(Error::InternalError)?;
let config =
ProcessorConfig::new(network_id, ice_servers, delegatee_key, stabilize_interval);
let config = configure(config);
Self::new_provider_with_storage_internal(config, stores).await
}
/// Serve the swarm's application inbox with the extension [`Backend`] on a detached task,
/// so inbound custom messages are decoded as
/// [`Envelope`](crate::extension::ext::Envelope)s and routed to their namespace's protocol.
/// Call once, after registering every protocol whose messages may already be on their way
/// (relay mail included): from the claim on, an envelope of a namespace not yet registered
/// is dropped, counted. The inbox is claimed once, so a second call fails with
/// `ApplicationInboxClaimed`. Serving lasts until the node is closed ([`Provider::close`]):
/// the service is a node task (#1085). Use
/// [`application_service`](Provider::application_service) for one under a stop of the
/// caller's.
pub fn set_backend(&self) -> Result<()> {
self.serve_application(None)
}
/// [`Self::set_backend`] with `observer` handed the peer facts and unrouted E2E messages.
pub(crate) fn serve_application(
&self,
observer: Option<Arc<dyn BackendObserver>>,
) -> Result<()> {
let tasks = self.processor.tasks();
// Acquired before the inbox is claimed, so a missing runtime claims nothing.
let spawner = tasks.spawner().map_err(|_| {
Error::ExtensionError("no runtime to serve the application inbox".to_owned())
})?;
let service = self.application_service(observer, tasks.stop_token())?;
spawner.spawn(service);
Ok(())
}
/// Claim the swarm's application inbox now and return the future that serves it with the
/// extension [`Backend`] over this provider's protocol registry, handing peer facts and
/// unrouted E2E messages to `observer`, until the swarm is gone or `stop` is requested.
///
/// ```text
/// application_service(o, s) = claim inbox ; pure (serve_o(inbox, s))
/// serve_o = Backend::new(self).observed_by(o).serve
/// ```
///
/// The claim is eager, so data that arrives before the caller spawns the future waits in
/// the inbox instead of being discarded unclaimed; the caller owns only the spawner and the
/// stop token. As with [`set_backend`](Provider::set_backend), register protocols first:
/// an envelope of a namespace not yet registered when it is read is dropped, counted. The
/// inbox is claimed once (see
/// [`Swarm::application_inbox`](rings_core::swarm::Swarm::application_inbox)), so a second
/// call fails.
pub fn application_service(
&self,
observer: Option<Arc<dyn BackendObserver>>,
stop: StopToken,
) -> Result<impl Future<Output = ()> + 'static> {
let inbox = self
.processor
.swarm
.application_inbox()
.map_err(Error::InternalError)?;
let backend = Backend::new(Arc::new(self.clone()));
let backend = match observer {
Some(observer) => backend.observed_by(observer),
None => backend,
};
Ok(backend.serve(inbox, stop))
}
/// Request local rpc interface
/// the internal rpc interface is provide by rings_rpc
pub async fn request_internal(
&self,
method: String,
params: serde_json::Value,
) -> Result<serde_json::Value> {
tracing::debug!("request {}", method);
#[cfg(all(feature = "browser", target_family = "wasm"))]
let onion_directory_endpoint = onion_directory_endpoint_from_rpc(method.as_str(), ¶ms);
let result = self
.handler
.handle_request(self.processor.clone(), method, params)
.await
.map_err(Error::InternalRpcError)?;
#[cfg(all(feature = "browser", target_family = "wasm"))]
if let Some(endpoint) = onion_directory_endpoint {
self.set_onion_directory_endpoint(Some(endpoint))?;
}
Ok(result)
}
}
#[cfg(feature = "node")]
impl Provider {
/// A request function implementation for native provider
pub async fn request<T>(
&self,
method: rings_rpc::method::Method,
params: T,
) -> Result<serde_json::Value>
where
T: serde::Serialize,
{
let params = serde_json::to_value(params)?;
self.request_internal(method.to_string(), params).await
}
/// Listen for messages until this future is dropped or aborted.
///
/// This is a long-running task; do not await completion as a readiness signal. Listening
/// publishes the processor's registrations, so a role that registers `relay` first installs
/// its onion runtime (`install_relay_onion_runtime`).
pub async fn listen(&self) -> Result<()> {
self.install_relay_onion_runtime()?;
self.processor.listen().await;
Ok(())
}
/// Listen for messages until `stop` requests cooperative shutdown.
///
/// This is a long-running task; do not await completion as a readiness signal. Like
/// [`Self::listen`], it first installs the onion runtime of a role that registers `relay`.
pub async fn listen_with(&self, stop: StopToken) -> Result<()> {
self.install_relay_onion_runtime()?;
self.processor.listen_with(stop).await;
Ok(())
}
/// The native handle of this provider's onion runtime. The runtime is installed in this
/// provider's registry on first use, once for all its clones, and shared afterwards.
///
/// # Errors
///
/// [`Error::Lock`] for a poisoned runtime slot, or a registry or runtime failure of the
/// install.
pub fn onion_circuit(&self) -> Result<NativeOnionCircuitHandle> {
self.onion_runtime().map(NativeOnionCircuitHandle::new)
}
}
#[cfg(all(feature = "browser", target_family = "wasm"))]
fn onion_directory_endpoint_from_rpc(
method: &str,
params: &serde_json::Value,
) -> Option<BrowserDirectoryEndpoint> {
if !matches!(method, "connectPeerViaHttp" | "ConnectPeerViaHttp") {
return None;
}
let url = params
.get("url")
.and_then(serde_json::Value::as_str)
.map(str::trim)
.filter(|url| !url.is_empty())
.map(ToOwned::to_owned)?;
let api_token = params
.get("api_token")
.and_then(serde_json::Value::as_str)
.map(Arc::<str>::from);
Some(BrowserDirectoryEndpoint { url, api_token })
}
#[cfg(all(feature = "browser", target_family = "wasm"))]
impl Provider {
pub(crate) fn set_onion_directory_endpoint(
&self,
endpoint: Option<BrowserDirectoryEndpoint>,
) -> Result<()> {
let mut slot = self
.onion_directory_endpoint
.lock()
.map_err(|_| Error::Lock)?;
*slot = endpoint;
Ok(())
}
pub(crate) fn onion_directory_endpoint(&self) -> Result<Option<BrowserDirectoryEndpoint>> {
self.onion_directory_endpoint
.lock()
.map(|slot| slot.clone())
.map_err(|_| Error::Lock)
}
}