rings-node 1.0.0-pre.8

Rings is a browser-native, structured peer-to-peer network: browser tabs and native daemons find each other by DID and talk over WebRTC, routed by a Chord DHT.
Documentation
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
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
//! General Provider, this module provide Provider implementation for FFI and WASM

use std::collections::BTreeMap;
use std::future::Future;
use std::pin::Pin;
use std::str::FromStr;
use std::sync::atomic::AtomicU64;
use std::sync::atomic::Ordering;
use std::sync::Arc;
use std::sync::Mutex;

use async_trait::async_trait;
use rings_core::delegation::DelegateeKey;
use rings_core::delegation::DelegationBuilder;
use rings_core::dht::Did;
use rings_core::dht::EntryStorage;
use rings_core::dht::RemovalStorage;
use rings_core::ecc::PublicKey;
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_core::swarm::application::ApplicationData;
use rings_core::swarm::application::ApplicationMessage;
use rings_rpc::protos::rings_node_handler::InternalRpcHandler;
use rings_runtime::MaybeSendSync;
use serde::Deserialize;
use serde::Serialize;

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;
#[cfg(not(all(feature = "browser", target_family = "wasm")))]
use crate::processor::DelegationHorizon;
use crate::processor::Processor;
use crate::processor::ProcessorBuilder;
use crate::processor::ProcessorConfig;
use crate::release::StoresReleased;

const CLOSE_DRAIN_TIMEOUT: std::time::Duration = std::time::Duration::from_secs(5);

#[cfg(all(feature = "browser", target_family = "wasm"))]
pub mod browser;

async fn await_close_phase<F>(
    phase_fut: F,
    timeout: std::time::Duration,
    phase: &'static str,
) -> bool
where
    F: Future<Output = ()>,
{
    let deadline = rings_runtime::sleep(timeout);
    futures::pin_mut!(phase_fut, deadline);
    match futures::future::select(phase_fut, deadline).await {
        futures::future::Either::Left(((), _)) => true,
        futures::future::Either::Right((timer, _)) => {
            match timer {
                Ok(()) => tracing::warn!(
                    phase,
                    timeout_ms = u64::try_from(timeout.as_millis()).unwrap_or(u64::MAX),
                    "provider close timed out waiting for shutdown phase"
                ),
                Err(error) => tracing::warn!(
                    phase,
                    ?error,
                    "provider close timer unavailable while waiting for shutdown phase"
                ),
            }
            false
        }
    }
}
#[cfg(feature = "ffi")]
pub mod ffi;

/// Maximum E2E events retained in a provider's bounded [`E2eInbox`] before further events drop.
const E2E_EVENT_CAPACITY: usize = 4096;

/// One inbound E2E handshake or stream-frame event retained by [`Provider`].
#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
pub struct E2eEvent {
    /// Event kind (`"handshakeRequest"`, `"handshakeResponse"`, or `"streamFrame"`).
    pub kind: String,
    /// Verified sender DID.
    pub from: String,
    /// Sender / responder compressed secp256k1 public key when present.
    pub public_key: Option<String>,
    /// Per-frame ECIES ephemeral secp256k1 public key for `"streamFrame"` events.
    pub ephemeral_public_key: Option<String>,
    /// Stream UUID for `"streamFrame"` events.
    pub stream_id: Option<String>,
    /// Stream sequence number for `"streamFrame"` events.
    pub sequence: Option<u64>,
    /// Whether this frame terminates the stream.
    pub is_final: Option<bool>,
    /// Legacy block count reported for `"streamFrame"` events.
    pub ciphertext_blocks: Option<usize>,
    /// Base64-encoded ciphertext payload for `"streamFrame"` events.
    pub ciphertext: Option<String>,
}

/// Snapshot returned when draining retained E2E events from [`Provider`].
#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
pub struct TakeE2eEventsResponse {
    /// Events retained since the previous drain.
    pub events: Vec<E2eEvent>,
    /// Cumulative events dropped since provider creation because the bounded inbox was full.
    pub dropped: u64,
}

/// JSON/JS-safe snapshot of this node's active delegation signing horizon.
#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
pub struct SigningHorizonSnapshot {
    /// Delegation expiry timestamp in Unix epoch milliseconds (decimal string).
    pub expires_at_ms: String,
    /// First millisecond at which outbound frames can no longer be signed (decimal string).
    pub horizon_ms: String,
    /// Milliseconds remaining before `horizon_ms` at snapshot time (decimal string).
    pub remaining_ms: String,
    /// Whether this node can sign outbound frames at snapshot time.
    pub signs_now: bool,
}

#[derive(Default)]
pub(crate) struct E2eInbox {
    events: Mutex<Vec<E2eEvent>>,
    dropped: AtomicU64,
}

impl E2eInbox {
    pub(crate) fn take(&self) -> Result<TakeE2eEventsResponse> {
        let mut events = self.events.lock().map_err(|_| Error::Lock)?;
        Ok(TakeE2eEventsResponse {
            events: std::mem::take(&mut *events),
            dropped: self.dropped.load(Ordering::Relaxed),
        })
    }

    fn push(&self, event: E2eEvent) -> Result<()> {
        let mut events = self.events.lock().map_err(|_| Error::Lock)?;
        if events.len() < E2E_EVENT_CAPACITY {
            events.push(event);
        } else {
            let dropped = self
                .dropped
                .fetch_add(1, Ordering::Relaxed)
                .saturating_add(1);
            tracing::debug!(dropped, "provider E2E event inbox full; event dropped");
        }
        Ok(())
    }
}

impl BackendObserver for E2eInbox {
    fn e2e_message(&self, message: &ApplicationMessage) {
        match e2e_event_from_message(message)
            .and_then(|event| event.map_or(Ok(()), |e| self.push(e)))
        {
            Ok(()) => {}
            Err(error) => tracing::warn!(error = ?error, "provider E2E event not retained"),
        }
    }
}

struct CompositeBackendObserver {
    e2e_inbox: Arc<E2eInbox>,
    extra: Option<Arc<dyn BackendObserver>>,
}

impl BackendObserver for CompositeBackendObserver {
    fn link_fact(&self, fact: crate::extension::ext::LinkFact) {
        if let Some(extra) = self.extra.as_deref() {
            extra.link_fact(fact);
        }
    }

    fn e2e_message(&self, message: &ApplicationMessage) {
        self.e2e_inbox.e2e_message(message);
        if let Some(extra) = self.extra.as_deref() {
            extra.e2e_message(message);
        }
    }

    fn custom_envelope(&self, from: Did, bytes: &[u8]) {
        if let Some(extra) = self.extra.as_deref() {
            extra.custom_envelope(from, bytes);
        }
    }
}

fn e2e_event_from_message(message: &ApplicationMessage) -> Result<Option<E2eEvent>> {
    let from = message.from.to_string();
    Ok(Some(match &message.data {
        ApplicationData::E2eHandshakeRequest(request) => E2eEvent {
            kind: "handshakeRequest".to_owned(),
            from,
            public_key: Some(public_key_json_string(request.requester_public_key)?),
            ephemeral_public_key: None,
            stream_id: None,
            sequence: None,
            is_final: None,
            ciphertext_blocks: None,
            ciphertext: None,
        },
        ApplicationData::E2eHandshakeResponse(response) => E2eEvent {
            kind: "handshakeResponse".to_owned(),
            from,
            public_key: Some(public_key_json_string(response.responder_public_key)?),
            ephemeral_public_key: None,
            stream_id: None,
            sequence: None,
            is_final: None,
            ciphertext_blocks: None,
            ciphertext: None,
        },
        ApplicationData::E2eStreamFrame(frame) => E2eEvent {
            kind: "streamFrame".to_owned(),
            from,
            public_key: Some(public_key_json_string(frame.sender_public_key)?),
            ephemeral_public_key: Some(public_key_json_string(frame.ephemeral_public_key)?),
            stream_id: Some(frame.stream_id.to_string()),
            sequence: Some(frame.sequence),
            is_final: Some(frame.is_final),
            ciphertext_blocks: Some(frame.ciphertext_blocks()),
            ciphertext: Some(base64::encode(&frame.ciphertext)),
        },
        _ => return Ok(None),
    }))
}

fn public_key_json_string(public_key: PublicKey<33>) -> Result<String> {
    let value = serde_json::to_value(public_key)?;
    value.as_str().map(str::to_owned).ok_or(Error::InvalidData)
}

mod u128_decimal_string {
    use serde::de::Error as _;
    use serde::Deserialize;
    use serde::Deserializer;
    use serde::Serializer;

    #[derive(Deserialize)]
    #[serde(untagged)]
    enum StringOrU64 {
        Str(String),
        Num(u64),
    }

    pub(super) fn serialize<S: Serializer>(value: &u128, serializer: S) -> Result<S::Ok, S::Error> {
        serializer.serialize_str(&value.to_string())
    }

    pub(super) fn deserialize<'de, D: Deserializer<'de>>(
        deserializer: D,
    ) -> Result<u128, D::Error> {
        match StringOrU64::deserialize(deserializer)? {
            StringOrU64::Str(raw) => raw.parse::<u128>().map_err(D::Error::custom),
            StringOrU64::Num(num) => Ok(u128::from(num)),
        }
    }
}

/// One raw element observed in a DHT registry carrier (`lookupRegistry`).
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct RegistryElementSnapshot {
    /// Base64-encoded `rings_codec` element bytes.
    pub data_base64: String,
    /// CRDT dot logical timestamp `τ*` in Unix epoch milliseconds (decimal string in JSON).
    #[serde(with = "u128_decimal_string")]
    pub heartbeat_at_ms: u128,
}

/// Response returned by the generic `lookupRegistry` local RPC primitive.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct LookupRegistryResponse {
    /// Queried DHT registry topic string.
    pub topic: String,
    /// Local overlay network identifier.
    pub network_id: u32,
    /// Local processor clock timestamp in Unix epoch milliseconds when read (decimal string in JSON).
    #[serde(with = "u128_decimal_string")]
    pub now_ms: u128,
    /// Normalized elements currently carried in the registry entry.
    pub elements: Vec<RegistryElementSnapshot>,
}

/// Optional concrete stage filter `(did, process_epoch, delegatee_public_key)` for `onionInvoke`.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct OnionEligibleStage {
    /// Candidate stage node account [`Did`].
    pub did: Did,
    /// Optional concrete [`crate::onion::OnionProcessEpoch`] of the target process.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub process_epoch: Option<crate::onion::OnionProcessEpoch>,
    /// Optional concrete session [`PublicKey<33>`] of the target process.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub delegatee_public_key: Option<PublicKey<33>>,
}

/// Request payload for the generic 1-stage `onionInvoke` local RPC primitive.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct OnionInvokeRpcRequest {
    /// Closed `invoke<In, Out, L>` shape symbol.
    pub shape: crate::onion::OnionInvokeShape,
    /// Canonical open backend name `ω`.
    pub backend: crate::onion::OnionBackendName,
    /// Optional base64-encoded inline constants `ā′`.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub constants_base64: Option<String>,
    /// Base64-encoded fixed-width input frame (`0` bytes for `Unit`).
    #[serde(default)]
    pub input_base64: String,
    /// Optional eligible stage DID allowlist.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub eligible_dids: Option<Vec<Did>>,
    /// Optional eligible concrete `(did, process_epoch)` stage allowlist.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub eligible_stages: Option<Vec<OnionEligibleStage>>,
    /// Optional caller timeout in milliseconds.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub timeout_ms: Option<u64>,
}

/// Response payload returned by the generic `onionInvoke` local RPC primitive.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct OnionInvokeRpcResponse {
    /// Account [`Did`] of the selected stage host.
    pub stage_did: Did,
    /// Process epoch (`OnionProcessEpoch`) of the selected stage host.
    pub stage_process_epoch: crate::onion::OnionProcessEpoch,
    /// Session delegatee public key (`PublicKey<33>`) of the selected stage host.
    pub stage_delegatee_public_key: PublicKey<33>,
    /// Base64-encoded fixed-width output frame returned by the stage.
    pub output_base64: String,
}

fn is_builtin_local_rpc_method(method: &str) -> bool {
    matches!(
        method,
        "takeE2eEvents"
            | "dispatchDropCounters"
            | "signingHorizon"
            | "renewDelegateeKey"
            | "lookupRegistry"
            | "onionInvoke"
            | "ConnectPeerViaHttp"
    ) || rings_rpc::method::Method::try_from(method).is_ok()
}

/// Asynchronous local RPC handler registered on a [`Provider`] by external service crates.
#[cfg_attr(all(feature = "browser", target_family = "wasm"), async_trait(?Send))]
#[cfg_attr(not(all(feature = "browser", target_family = "wasm")), async_trait)]
pub trait LocalRpcMethod: MaybeSendSync {
    /// Handle one JSON-RPC call invoked via [`Provider::request_internal`].
    async fn call(&self, params: serde_json::Value) -> Result<serde_json::Value>;
}

/// General Provider holding the node processor, RPC dispatcher, and extension registry.
#[derive(Clone)]
#[allow(dead_code)]
#[wasm_export]
pub struct Provider {
    processor: Arc<Processor>,
    handler: InternalRpcHandler,
    extensions: crate::extension::ext::Extensions,
    dispatch_drops: Arc<DispatchDrops>,
    e2e_inbox: Arc<E2eInbox>,
    /// External local RPC methods installed on this provider.
    custom_rpc: Arc<Mutex<BTreeMap<String, Arc<dyn LocalRpcMethod>>>>,
    /// 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>>,
    /// Best-effort `pagehide` departure listener for browser providers (#1057).
    #[cfg(all(feature = "browser", target_family = "wasm"))]
    pagehide: Option<std::rc::Rc<browser::provider::listener::PagehideListener>>,
}

#[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 = Result<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 = Result<Vec<u8>>> + Send>>>;

/// Signer can be async and sync
#[allow(clippy::type_complexity)]
pub enum Signer {
    /// Sync signer
    Sync(Box<dyn Fn(String) -> Result<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_weak(&processor);
        #[cfg(all(feature = "browser", target_family = "wasm"))]
        let pagehide = browser::provider::listener::PagehideListener::register(&processor)
            .map(std::rc::Rc::new);
        Self {
            processor,
            handler: InternalRpcHandler,
            extensions,
            dispatch_drops: Arc::default(),
            e2e_inbox: Arc::default(),
            custom_rpc: Arc::new(Mutex::new(BTreeMap::new())),
            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,
            #[cfg(all(feature = "browser", target_family = "wasm"))]
            pagehide,
        }
    }

    /// Return a reference to the underlying [`Processor`] driving this provider.
    pub const fn processor(&self) -> &Arc<Processor> {
        &self.processor
    }

    /// Register an external [`LocalRpcMethod`] reachable through [`Self::request_internal`] (and
    /// C FFI / browser RPC dispatch).
    ///
    /// Rejects empty method names, any built-in node/JSON-RPC method name, and duplicate
    /// registrations on the same [`Provider`].
    pub fn register_local_rpc_method(
        &self,
        method: impl Into<String>,
        handler: impl LocalRpcMethod + 'static,
    ) -> Result<()> {
        let name = method.into();
        let trimmed = name.trim();
        if trimmed.is_empty() || trimmed != name {
            return Err(Error::InvalidConfig(format!(
                "invalid local RPC method name {name:?}"
            )));
        }
        if is_builtin_local_rpc_method(&name) {
            return Err(Error::InvalidConfig(format!(
                "cannot override built-in RPC method {name:?}"
            )));
        }
        let mut table = self.custom_rpc.lock().map_err(|_| Error::Lock)?;
        if table.contains_key(&name) {
            return Err(Error::InvalidConfig(format!(
                "local RPC method {name:?} is already registered"
            )));
        }
        table.insert(name, Arc::new(handler));
        Ok(())
    }

    /// Fetch raw normalized elements of DHT registry `topic` together with CRDT dot timestamps,
    /// local `network_id`, and local clock `now_ms`.
    pub async fn lookup_registry_raw(&self, topic: &str) -> Result<LookupRegistryResponse> {
        let trimmed = topic.trim();
        if trimmed.is_empty() {
            return Err(Error::InvalidConfig(
                "registry topic must be non-empty".to_string(),
            ));
        }
        let now_ms = self.processor.clock().now_ms();
        let network_id = self.processor.swarm.network_id();
        let elements = match self.processor.fetch_topic_entry(trimmed).await? {
            Some(entry) => crate::descriptor::heard_elements(&entry)
                .map(|(bytes, heartbeat_at_ms)| RegistryElementSnapshot {
                    data_base64: base64::encode(bytes.as_ref()),
                    heartbeat_at_ms,
                })
                .collect(),
            None => Vec::new(),
        };
        Ok(LookupRegistryResponse {
            topic: trimmed.to_string(),
            network_id,
            now_ms,
            elements,
        })
    }

    /// Evaluate a generic 1-stage Kleisli `invoke` pipeline over a guard-closed Sphinx loop,
    /// optionally restricted to `eligible_dids` and/or concrete `(did, process_epoch)`
    /// `eligible_stages`.
    pub async fn onion_invoke_raw(
        &self,
        request: OnionInvokeRpcRequest,
    ) -> Result<OnionInvokeRpcResponse> {
        let constants = match request.constants_base64.as_deref() {
            Some(raw) if !raw.is_empty() => base64::decode(raw)
                .map_err(|e| Error::InvalidConfig(format!("invalid constants_base64: {e}")))?,
            _ => Vec::new(),
        };
        let input = if request.input_base64.is_empty() {
            Vec::new()
        } else {
            base64::decode(request.input_base64.as_str())
                .map_err(|e| Error::InvalidConfig(format!("invalid input_base64: {e}")))?
        };
        let stage = crate::onion::OnionInvokeStage::new(request.shape, request.backend, constants)?;
        let pipeline = stage.into_pipeline();

        let did_filter: Option<std::collections::BTreeSet<Did>> =
            request.eligible_dids.map(|dids| dids.into_iter().collect());
        let stage_filter = request.eligible_stages;
        let predicate = |desc: &crate::onion::OnionInvokeDescriptor| {
            let did_ok = did_filter
                .as_ref()
                .is_none_or(|allowed| allowed.contains(&desc.did));
            let stage_ok = stage_filter.as_ref().is_none_or(|allowed| {
                allowed.iter().any(|cand| {
                    cand.did == desc.did
                        && cand
                            .process_epoch
                            .is_none_or(|epoch| epoch == desc.process_epoch)
                        && cand
                            .delegatee_public_key
                            .is_none_or(|pk| pk == desc.delegatee_public_key)
                })
            });
            did_ok && stage_ok
        };

        #[cfg(all(feature = "browser", target_family = "wasm"))]
        let route = browser::provider::onion_proxy::build_browser_onion_pipeline_route_filtered(
            Arc::clone(&self.processor),
            self.onion_directory_endpoint()?,
            &pipeline,
            predicate,
        )
        .await?;

        #[cfg(not(all(feature = "browser", target_family = "wasm")))]
        let route = self
            .processor
            .build_onion_pipeline_route_filtered(&pipeline, predicate)
            .await?;

        let stage_desc = route.descriptors().first().ok_or_else(|| {
            Error::InvalidConfig("selected onion invoke route had no stage descriptor".to_string())
        })?;
        let stage_did = stage_desc.did;
        let stage_process_epoch = stage_desc.process_epoch;
        let stage_delegatee_public_key = stage_desc.delegatee_public_key;

        let handle = self.onion_pipeline()?;
        let timeout = request.timeout_ms.map(std::time::Duration::from_millis);
        let output = handle
            .invoke_pipeline_over_route_with_options(
                &route,
                &pipeline,
                pipeline.loop_class(),
                &input,
                timeout,
            )
            .await?;
        Ok(OnionInvokeRpcResponse {
            stage_did,
            stage_process_epoch,
            stage_delegatee_public_key,
            output_base64: base64::encode(&output),
        })
    }

    /// 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(())
        }
    }

    /// Cross-platform handle for registering intermediate `invoke` backends and evaluating
    /// multi-stage Kleisli pipelines on this provider's onion runtime (#834 Phase 2b).
    pub fn onion_pipeline(&self) -> Result<crate::onion::OnionPipelineHandle> {
        self.onion_runtime()
            .map(crate::onion::OnionPipelineHandle::new)
    }

    /// 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()
    }

    pub(crate) fn take_e2e_events_internal(&self) -> Result<TakeE2eEventsResponse> {
        self.e2e_inbox.take()
    }

    /// Drain all retained inbound E2E handshake and stream-frame events.
    #[cfg(not(all(feature = "browser", target_family = "wasm")))]
    pub fn take_e2e_events(&self) -> Result<TakeE2eEventsResponse> {
        self.take_e2e_events_internal()
    }

    pub(crate) fn signing_horizon_snapshot(&self) -> SigningHorizonSnapshot {
        let now_ms = self.processor.clock().now_ms();
        let horizon = self.processor.signing_horizon();
        SigningHorizonSnapshot {
            expires_at_ms: horizon.expires_at_ms().to_string(),
            horizon_ms: horizon.horizon_ms().to_string(),
            remaining_ms: horizon.horizon_ms().saturating_sub(now_ms).to_string(),
            signs_now: horizon.signs_at(now_ms),
        }
    }

    /// Return the active delegation signing horizon of this node.
    #[cfg(not(all(feature = "browser", target_family = "wasm")))]
    pub fn signing_horizon(&self) -> DelegationHorizon {
        self.processor.signing_horizon()
    }

    /// Renew this node's active session key in process before its signing horizon expires.
    #[cfg(not(all(feature = "browser", target_family = "wasm")))]
    pub fn renew_delegatee_key(&self, next: DelegateeKey) -> Result<DelegationHorizon> {
        self.processor
            .renew_delegatee_key(next, self.processor.clock().now_ms())
    }

    /// 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
    }

    pub(crate) async fn leave_internal(&self) -> Result<()> {
        self.processor.leave().await
    }

    /// Best-effort voluntary departure (#1057): hand off live relay carriers to remaining
    /// members and send `Leave { successor_list }` to this node's predecessor and successor head
    /// before transports close.
    #[cfg(not(all(feature = "browser", target_family = "wasm")))]
    pub async fn leave(&self) -> Result<()> {
        self.leave_internal().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<()> {
        self.close_with_drain_timeout(CLOSE_DRAIN_TIMEOUT).await
    }

    pub(crate) async fn close_with_drain_timeout(
        self,
        drain_timeout: std::time::Duration,
    ) -> Result<()> {
        let tasks = self.processor.tasks().clone();
        tasks.stop();
        await_close_phase(
            self.processor.await_listener_generations(),
            drain_timeout,
            "listener_generations",
        )
        .await;
        await_close_phase(tasks.drained(), drain_timeout, "tasks_before_network_close").await;
        let closed = self.processor.close_with_timeout(drain_timeout).await;
        await_close_phase(tasks.drained(), drain_timeout, "tasks_after_network_close").await;
        let released = self.processor.stores_released();
        let Self {
            processor,
            handler,
            extensions,
            dispatch_drops,
            e2e_inbox,
            custom_rpc,
            onion_runtime,
            #[cfg(all(feature = "browser", target_family = "wasm"))]
            onion_directory_endpoint,
            #[cfg(all(feature = "browser", target_family = "wasm"))]
            browser_mail,
            #[cfg(all(feature = "browser", target_family = "wasm"))]
            pagehide,
        } = self;
        drop((
            handler,
            extensions,
            dispatch_drops,
            e2e_inbox,
            custom_rpc,
            onion_runtime,
        ));
        #[cfg(all(feature = "browser", target_family = "wasm"))]
        drop((onion_directory_endpoint, browser_mail, pagehide));
        // Atomic: `Some` only for the last strong clone, which a `Weak` upgrade cannot race.
        match Arc::into_inner(processor) {
            Some(processor) => {
                drop(processor);
                if !await_close_phase(
                    std::future::IntoFuture::into_future(released.clone()),
                    drain_timeout,
                    "stores_released",
                )
                .await
                {
                    if let Err(error) = closed {
                        tracing::warn!(%error, "a closing node whose stores are still held failed to close its network");
                    }
                    return Err(Error::ProviderStillShared { released });
                }
                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_and_clock(
            measure_storage,
            evidence_storage,
            collector,
            config.clock().clone(),
        )
        .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()?);

        Ok(Self::from_processor(processor))
    }

    /// 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
    }

    pub(crate) async fn mint_delegatee_key(
        account: String,
        account_type: String,
        signer: Signer,
    ) -> Result<DelegateeKey> {
        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);
        sk_builder.build().map_err(Error::InternalError)
    }

    #[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 delegatee_key = Self::mint_delegatee_key(account, account_type, signer).await?;
        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.
    /// Spawn the application-inbox consumer over this provider's protocol registry.
    pub fn set_backend(&self) -> Result<()> {
        self.serve_application(None)
    }

    /// Spawn the application-inbox consumer with an explicit [`BackendObserver`].
    pub fn set_backend_with_observer(&self, observer: Arc<dyn BackendObserver>) -> Result<()> {
        self.serve_application(Some(observer))
    }

    /// [`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 composite_observer: Arc<dyn BackendObserver> = Arc::new(CompositeBackendObserver {
            e2e_inbox: Arc::clone(&self.e2e_inbox),
            extra: observer,
        });
        let backend = Backend::new(Arc::new(self.clone())).observed_by(composite_observer);
        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);
        match method.as_str() {
            "takeE2eEvents" => return Ok(serde_json::to_value(self.take_e2e_events_internal()?)?),
            "dispatchDropCounters" => {
                return Ok(serde_json::to_value(self.dispatch_drop_counters())?);
            }
            "signingHorizon" => return Ok(serde_json::to_value(self.signing_horizon_snapshot())?),
            "renewDelegateeKey" => {
                let raw_key = params
                    .get("delegatee_key")
                    .and_then(serde_json::Value::as_str)
                    .ok_or_else(|| {
                        Error::InternalRpcError(jsonrpc_core::Error::invalid_params(
                            "missing string field `delegatee_key`",
                        ))
                    })?;
                let next = DelegateeKey::from_str(raw_key)?;
                self.processor
                    .renew_delegatee_key(next, self.processor.clock().now_ms())?;
                return Ok(serde_json::to_value(self.signing_horizon_snapshot())?);
            }
            "lookupRegistry" => {
                let topic = params
                    .get("topic")
                    .and_then(serde_json::Value::as_str)
                    .ok_or_else(|| {
                        Error::InternalRpcError(jsonrpc_core::Error::invalid_params(
                            "missing string field `topic`",
                        ))
                    })?;
                let resp = self.lookup_registry_raw(topic).await?;
                return Ok(serde_json::to_value(resp)?);
            }
            "onionInvoke" => {
                let req: OnionInvokeRpcRequest = serde_json::from_value(params).map_err(|e| {
                    Error::InternalRpcError(jsonrpc_core::Error::invalid_params(format!(
                        "invalid onionInvoke params: {e}"
                    )))
                })?;
                let resp = self.onion_invoke_raw(req).await?;
                return Ok(serde_json::to_value(resp)?);
            }
            _ => {}
        }
        if !is_builtin_local_rpc_method(method.as_str()) {
            let custom_handler = {
                let table = self.custom_rpc.lock().map_err(|_| Error::Lock)?;
                table.get(method.as_str()).cloned()
            };
            if let Some(handler) = custom_handler {
                return handler.call(params).await;
            }
        }
        #[cfg(all(feature = "browser", target_family = "wasm"))]
        let onion_directory_endpoint = onion_directory_endpoint_from_rpc(method.as_str(), &params);
        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(str::trim)
        .filter(|token| !token.is_empty())
        .map(Arc::<str>::from)?;
    Some(BrowserDirectoryEndpoint {
        url,
        api_token: Some(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)
    }
}

#[cfg(all(test, feature = "node", not(target_family = "wasm")))]
mod local_rpc_tests {
    use std::sync::Arc;

    use async_trait::async_trait;
    use rings_core::delegation::DelegateeKey;
    use rings_core::ecc::SecretKey;
    use rings_core::storage::MemStorage;
    use serde_json::json;

    use super::LocalRpcMethod;
    use super::Provider;
    use crate::processor::ProcessorBuilder;
    use crate::processor::ProcessorConfig;

    struct EchoMethod;

    #[async_trait]
    impl LocalRpcMethod for EchoMethod {
        async fn call(&self, params: serde_json::Value) -> crate::error::Result<serde_json::Value> {
            Ok(params)
        }
    }

    fn test_provider() -> crate::error::Result<Provider> {
        let key = SecretKey::random();
        let delegatee_key = DelegateeKey::new_with_seckey(&key)?;
        let config =
            ProcessorConfig::new(1, String::new(), delegatee_key, 200).dht_virtual_nodes(0);
        let replay = Box::new(MemStorage::new());
        let processor = Arc::new(
            ProcessorBuilder::from_config(&config)?
                .advertise_presence(false)
                .replay_storage(replay)
                .build()?,
        );
        Ok(Provider::from_processor(processor))
    }

    #[tokio::test]
    async fn register_local_rpc_method_rejects_builtins_whitespace_and_duplicates(
    ) -> crate::error::Result<()> {
        let provider = test_provider()?;
        for invalid in [
            "",
            "   ",
            " customMethod",
            "customMethod ",
            "nodeDid",
            "connectPeerViaHttp",
            "ConnectPeerViaHttp",
            "takeE2eEvents",
            "dispatchDropCounters",
            "signingHorizon",
            "renewDelegateeKey",
            "lookupRegistry",
            "onionInvoke",
        ] {
            assert!(
                provider
                    .register_local_rpc_method(invalid, EchoMethod)
                    .is_err(),
                "expected {invalid:?} to be rejected"
            );
        }

        provider.register_local_rpc_method("ext.echo", EchoMethod)?;
        assert!(
            provider
                .register_local_rpc_method("ext.echo", EchoMethod)
                .is_err(),
            "duplicate custom RPC method must be rejected"
        );
        let echoed = provider
            .request_internal("ext.echo".to_string(), json!({"hello": "world"}))
            .await?;
        assert_eq!(echoed, json!({"hello": "world"}));
        provider.close().await?;
        Ok(())
    }
}