rings-node 1.0.0-pre.6

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.
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
//! Processor of rings-node rpc server.

use std::collections::BTreeSet;
use std::num::NonZeroUsize;
use std::str::FromStr;
use std::sync::Arc;
use std::time::Duration;

use bytes::Bytes;
use futures::future::join_all;
use rings_core::chunk::ReassemblyLimits;
use rings_core::dht::Did;
use rings_core::dht::EntryStorage;
use rings_core::dht::DEFAULT_FINGER_TABLE_SIZE;
use rings_core::inspect::DHTInspect;
use rings_core::lifecycle::StopSource;
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::MeasureImpl;
use rings_core::measure::PeerMeasurement;
use rings_core::measure::PeerMeasurementPage;
use rings_core::measure::PeerQuality;
use rings_core::message::DhtProtocolMode;
use rings_core::message::OriginQuotaConfig;
use rings_core::message::OriginQuotaCounters;
use rings_core::message::ReplayStorage;
use rings_core::storage::MemStorage;
use rings_core::swarm::storage_api::StoreQuorum;
use rings_core::swarm::storage_api::StoreReceipt;
use rings_core::swarm::Swarm;
use rings_core::swarm::SwarmBuilder;
#[cfg(all(test, feature = "node"))]
use rings_core::utils::get_epoch_ms;
use rings_core::utils::SharedClock;
use rings_core::utils::SharedRng;
use rings_rpc::protos::rings_node::*;
use rings_runtime::sleep;
use rings_transport::webrtc_config::WebrtcUdpPortRange;
use serde::Deserialize;
use serde::Serialize;

#[cfg(all(test, feature = "node"))]
use crate::descriptor::RegistryElement;
use crate::error::Error;
use crate::error::Result;
use crate::measure::PeriodicMeasure;
use crate::observability::HealthSnapshot;
use crate::observability::MailboxSnapshot;
use crate::observability::Observability;
use crate::observability::OperatorSnapshot;
use crate::observability::PeerRatingSnapshot;
use crate::observability::SessionKeySnapshot;
use crate::observability::OPERATOR_SCHEMA_VERSION;
use crate::observability::PEER_RATING_CAPACITY;
use crate::onion::circuit::OnionIdleFloor;
use crate::onion::default_advertise_onion_exit;
use crate::onion::default_advertise_onion_relay;
use crate::onion::default_onion_exit_heartbeat_interval_secs;
use crate::onion::default_onion_exit_policy;
use crate::onion::default_onion_exit_services;
use crate::onion::default_onion_exit_ttl_secs;
use crate::onion::directory;
use crate::onion::directory::OnionDirectoryReader;
use crate::onion::proxy::OnionProxyProtocol;
use crate::onion::proxy::OnionProxyRoute;
use crate::onion::proxy::OnionProxyTarget;
use crate::onion::OnionEntryGuardStorage;
use crate::onion::OnionEntryGuards;
use crate::onion::OnionExitDescriptor;
use crate::onion::OnionExitOffer;
use crate::onion::OnionExitPolicy;
use crate::onion::OnionExitRegistration;
use crate::onion::OnionProcessEpoch;
use crate::onion::OnionProcessEpochCell;
use crate::onion::OnionRole;
use crate::onion::OnionServiceName;
use crate::onion::ONION_EXITS_TOPIC;
use crate::online::OnlineNodeDescriptor;
use crate::online::OnlineNodeType;
use crate::online::ONLINE_NODES_TOPIC;
use crate::prelude::entry;
use crate::prelude::wasm_export;
use crate::prelude::ChordStorageInterface;
use crate::prelude::ChordStorageInterfaceCacheChecker;
use crate::prelude::DelegateeKey;
use crate::registration::default_advertise_presence;
use crate::registration::default_online_node_heartbeat_interval_secs;
use crate::registration::default_online_node_ttl_secs;
use crate::registration::default_online_node_type;
use crate::registration::early_publish_armed;
use crate::registration::republish_due;
use crate::registration::validate_registration_timing;
use crate::registration::OnlineNodeRegistration;
use crate::registration::RegistrationContext;
use crate::registration::RegistrationReadiness;
use crate::registration::RegistrationTask;
use crate::release::StoresReleased;
use crate::tasks::NodeTasks;

const MEASUREMENT_FLUSH_TIMEOUT: Duration = Duration::from_secs(5);

mod builder;
mod config;
/// Handshakes: by DID over the overlay, and over a peer's HTTP endpoint.
pub(crate) mod handshake;
mod horizon;
mod messaging;
mod registration_daemon;

pub use builder::ProcessorBuilder;
#[cfg(feature = "node")]
pub(crate) use config::parse_webrtc_udp_port_range;
pub use config::ProcessorConfig;
pub use config::ProcessorConfigSerialized;
pub(crate) use handshake::HandshakeFailure;
pub(crate) use handshake::HandshakePeer;
pub use handshake::OfferReplyKind;
pub use horizon::DelegationHorizon;
pub(crate) use horizon::SessionKeyRing;
pub use horizon::SigningState;
pub use horizon::SIGNING_HORIZON_LEAD_MS;
pub(crate) use registration_daemon::sleep_unless_stopped;

/// The pause between two reads of the fetch cache while a DHT fetch waits for its reply.
const DHT_LOOKUP_CACHE_POLL_INTERVAL: Duration = Duration::from_millis(50);
/// The number of fetch-cache reads a DHT fetch makes before it gives up on a reply.
const DHT_LOOKUP_CACHE_POLL_ATTEMPTS: u32 = 40;

/// Whether the fetch-cache read numbered `attempt` (from 0) is a DHT fetch's last one.
const fn is_final_lookup_poll(attempt: u32) -> bool {
    attempt.saturating_add(1) >= DHT_LOOKUP_CACHE_POLL_ATTEMPTS
}

/// Processor for rings-node rpc server.
///
/// Cloning shares the same node handle; publishes from any clone are serialized
/// against each other.
#[derive(Clone)]
pub struct Processor {
    /// a swarm instance
    pub swarm: Arc<Swarm>,
    /// Live delegatee key and retained unexpired previous keys, shared across clones (#1153).
    session_keys: Arc<SessionKeyRing>,
    /// The process epoch `e_n` carried by every onion symbol this process registers (#834 D2):
    /// drawn fresh at process start, renewed only by the onion admission state.
    onion_process_epoch: OnionProcessEpochCell,
    onion_entry_guards: Arc<OnionEntryGuards>,
    stabilize_interval: Duration,
    online_node_registration: OnlineNodeRegistration,
    measure: Option<Arc<PeriodicMeasure>>,
    /// The release witnesses of the file stores this processor is built over (#1085).
    stores_released: StoresReleased,
    /// The stop and the task set of this node (`crate::tasks`), shared by every clone.
    tasks: NodeTasks,
    /// Serializes listener generations across every clone and wrapper of this processor.
    /// Ownership includes graceful maintenance shutdown and measurement flushing.
    listener_lifecycle_lock: Arc<futures::lock::Mutex<()>>,
    /// Onion symbols this process registers (#834 D2).
    onion_role: OnionRole<OnionExitOffer>,
    /// The cover floor of this node's idle onion links (#880).
    onion_idle_floor: OnionIdleFloor,
    registration_tasks: Vec<Arc<dyn RegistrationTask>>,
    /// Whether each registration task is stored at its owners (#866), in task order.
    registration_readiness: Arc<RegistrationReadiness>,
    /// Process-local bounded recorder backing the authenticated operator surface.
    observability: Arc<Observability>,
    /// Optional HTTP(S) proxy for remote JSON-RPC endpoints on native targets.
    remote_rpc_proxy: Option<crate::remote_endpoint::RemoteRpcProxy>,
}

impl Drop for Processor {
    fn drop(&mut self) {
        self.tasks.stop();
    }
}

/// The node error of a DHT operation run under a registration stop: a rerouting wait ended by
/// the stop is the registration's cooperative stop, anything else an entry error.
pub(crate) fn stoppable_storage_error(error: rings_core::error::Error) -> Error {
    match error {
        rings_core::error::Error::ReroutingStopped => Error::RegistrationStopped,
        error => Error::EntryError(error),
    }
}

impl Processor {
    /// Get current did
    pub fn did(&self) -> Did {
        self.swarm.did()
    }

    /// Return the [`SharedClock`] capability bound to this processor.
    pub fn clock(&self) -> &SharedClock {
        self.swarm.clock()
    }

    /// Return the [`SharedRng`] capability bound to this processor.
    pub fn rng(&self) -> &SharedRng {
        self.swarm.rng()
    }

    pub(crate) fn delegatee_key(&self) -> DelegateeKey {
        self.session_keys.current()
    }

    /// Return the active session key followed by any retained previous keys that have not yet
    /// expired at `now_ms`, so envelopes sealed to a prior key before descriptor republication
    /// settles can still be opened (#1153).
    pub(crate) fn decryption_keys_at(&self, now_ms: u128) -> Vec<DelegateeKey> {
        self.session_keys.decryption_keys_at(now_ms)
    }

    /// Mint, validate, persist, and install a replacement session key at `now_ms` through
    /// [`SessionKeyRing::renew_with`], updating the swarm transport on success (#1153).
    pub(crate) fn renew_delegatee_key_with<M, P>(
        &self,
        now_ms: u128,
        mint: M,
        persist: P,
    ) -> Result<DelegationHorizon>
    where
        M: FnOnce(&DelegateeKey) -> Result<DelegateeKey>,
        P: FnOnce(&DelegateeKey) -> Result<()>,
    {
        let (_next, horizon) = self.session_keys.renew_with(now_ms, mint, |next| {
            persist(next)?;
            self.swarm
                .set_delegatee_key(next.clone())
                .map_err(Error::CoreError)
        })?;
        Ok(horizon)
    }

    /// Replace this node's active session key in process at `now_ms`, retaining the previous key
    /// until its delegation expires and updating the swarm transport (#1153).
    ///
    /// Laws:
    /// - **Monotone horizon**: `h' > h`. A renewal never shortens the signing horizon.
    /// - **No unsigned gap**: `next` authorizes `self.did()`, verifies at `now_ms`, and is before
    ///   `h'`.
    pub fn renew_delegatee_key(
        &self,
        next: DelegateeKey,
        now_ms: u128,
    ) -> Result<DelegationHorizon> {
        self.renew_delegatee_key_with(now_ms, |_| Ok(next), |_| Ok(()))
    }

    /// The signing horizon of this node's own delegation: from it on, the node can send
    /// nothing unless it renews or restarts with a fresh delegation (#1063, #1153). A native
    /// daemon renews at `h - lead` when configured with a delegator key and ends at `h`
    /// otherwise; a browser or FFI embedder reads it here, or as `overlay_ready = false`, and
    /// acts itself.
    pub fn signing_horizon(&self) -> DelegationHorizon {
        self.session_keys.horizon()
    }

    /// The stop and the task set of this node (`crate::tasks`).
    pub(crate) fn tasks(&self) -> &NodeTasks {
        &self.tasks
    }

    /// The release witnesses of the file stores this processor is built over (#1085).
    pub(crate) fn stores_released(&self) -> StoresReleased {
        self.stores_released.clone()
    }

    #[cfg(all(feature = "browser", target_family = "wasm"))]
    pub(crate) fn onion_entry_guards(&self) -> &OnionEntryGuards {
        self.onion_entry_guards.as_ref()
    }

    pub(crate) fn onion_entry_guards_arc(&self) -> Arc<OnionEntryGuards> {
        Arc::clone(&self.onion_entry_guards)
    }

    /// Return the onion symbols this process registers (#834 D2).
    pub const fn onion_role(&self) -> &OnionRole<OnionExitOffer> {
        &self.onion_role
    }

    /// Return the cover floor of this node's idle onion links (#880).
    pub(crate) const fn onion_idle_floor(&self) -> OnionIdleFloor {
        self.onion_idle_floor
    }

    /// Return the cell of this process's onion epoch `e_n` (#834 D2), shared with the onion
    /// admission state and the registrations.
    pub(crate) fn onion_process_epoch(&self) -> OnionProcessEpochCell {
        self.onion_process_epoch.clone()
    }

    fn registration_context(&self) -> RegistrationContext<'_> {
        RegistrationContext::new(self)
    }

    /// This node's online descriptor under a lease issued at `now_ms` that is fresh for 90 s
    /// and ends with it, not yet heard.
    #[cfg(all(test, feature = "node"))]
    fn online_node_descriptor_at(&self, now_ms: u128) -> Result<OnlineNodeDescriptor> {
        self.online_node_registration.descriptor_at(
            &self.registration_context(),
            crate::registration::LeaseTerms {
                fresh_for_ms: 90_000,
                expires_at_ms: now_ms + 90_000,
            },
        )
    }

    /// The registry entry under `topic` whose elements are `descriptors`.
    #[cfg(all(test, feature = "node"))]
    pub(crate) fn registry_entry<D: RegistryElement>(
        topic: &str,
        descriptors: Vec<D>,
    ) -> Result<entry::Entry> {
        let data = descriptors
            .into_iter()
            .map(|descriptor| descriptor.to_element().map_err(Error::CoreError))
            .collect::<Result<Vec<_>>>()?;

        Ok(entry::Entry::new(
            entry::Entry::gen_did(topic)?,
            data,
            entry::EntryKind::Data,
        ))
    }

    /// Publish this node's signed online descriptor to the online-node registry.
    pub async fn publish_online_node_descriptor(&self) -> Result<OnlineNodeDescriptor> {
        self.online_node_registration
            .publish_descriptor(&self.registration_context())
            .await
    }

    /// List signed online-node descriptors from the registry.
    ///
    /// The registry carrier is the join of every reply this node has observed (#864), with its
    /// own writes applied (#982): it ascends in the lattice order while cached and live, so this
    /// node lists what it registered itself whichever owner its lookup reaches, but a descriptor
    /// still leaves it on a tombstone, on an overwrite's reset floor, or at the element cap. Rerouted as [`Self::storage_fetch`] documents.
    pub async fn lookup_online_nodes(
        &self,
        include_expired: bool,
    ) -> Result<Vec<OnlineNodeDescriptor>> {
        let entry_key = entry::Entry::gen_did(ONLINE_NODES_TOPIC)?;

        let Some(entry) = self.fetch_storage_entry(entry_key).await? else {
            return Ok(vec![]);
        };

        let descriptors = OnlineNodeRegistration::descriptors_from_entry(&entry)
            .into_iter()
            .filter(|descriptor| descriptor.matches_dht_protocol(self.swarm.dht_protocol_mode()));

        Ok(OnlineNodeDescriptor::latest_valid_by_did(
            descriptors,
            self.clock().now_ms(),
            self.swarm.network_id(),
            include_expired,
        ))
    }

    /// List signed onion-exit descriptors from the application-layer exit registry.
    ///
    /// Like [`Self::lookup_online_nodes`], the carrier read is the join of the observed replies
    /// (#864) with this node's own writes applied (#982). Rerouted as [`Self::storage_fetch`]
    /// documents.
    pub async fn lookup_onion_exits(
        &self,
        service: &str,
        include_expired: bool,
    ) -> Result<Vec<OnionExitDescriptor>> {
        let entry_key = entry::Entry::gen_did(ONION_EXITS_TOPIC)?;
        let service = service.trim();

        let Some(entry) = self.fetch_storage_entry(entry_key).await? else {
            return Ok(vec![]);
        };

        Ok(self.select_onion_exits_from_entry(&entry, service, include_expired))
    }

    /// List signed intermediate `invoke` descriptors from [`crate::onion::ONION_INVOKES_TOPIC`],
    /// optionally filtered by `shape` and/or canonical `backend` name.
    pub async fn lookup_onion_invokes(
        &self,
        shape: Option<crate::onion::OnionInvokeShape>,
        backend: &str,
        include_expired: bool,
    ) -> Result<Vec<crate::onion::OnionInvokeDescriptor>> {
        let entry_key = entry::Entry::gen_did(crate::onion::ONION_INVOKES_TOPIC)?;
        let backend = backend.trim();
        let Some(entry) = self.fetch_storage_entry(entry_key).await? else {
            return Ok(vec![]);
        };
        Ok(
            crate::onion::OnionInvokeDescriptor::latest_valid_by_symbol_did(
                crate::onion::OnionInvokeRegistration::descriptors_from_entry(&entry),
                self.clock().now_ms(),
                self.swarm.network_id(),
                include_expired,
            )
            .into_iter()
            .filter(|desc| shape.is_none_or(|wanted| desc.shape == wanted))
            .filter(|desc| backend.is_empty() || desc.backend.as_str() == backend)
            .collect(),
        )
    }

    /// Build a guard-closed multi-hop route for an intermediate `invoke` Kleisli pipeline.
    pub async fn build_onion_pipeline_route(
        &self,
        pipeline: &crate::onion::OnionInvokePipeline,
    ) -> Result<crate::onion::OnionPipelineRoute> {
        crate::onion::directory::build_onion_pipeline_route(self, pipeline).await
    }

    /// Select the newest live exit registration per `(DID, service)` of `entry` offering
    /// `service` (every service when empty).
    fn select_onion_exits_from_entry(
        &self,
        entry: &entry::Entry,
        service: &str,
        include_expired: bool,
    ) -> Vec<OnionExitDescriptor> {
        OnionExitDescriptor::latest_valid_by_service_did(
            OnionExitRegistration::descriptors_from_entry(entry),
            self.clock().now_ms(),
            self.swarm.network_id(),
            include_expired,
        )
        .into_iter()
        .filter(|descriptor| service.is_empty() || descriptor.offers_service(service))
        .collect()
    }

    pub(crate) async fn fetch_storage_entry(&self, entry_key: Did) -> Result<Option<entry::Entry>> {
        let stop = StopToken::never();
        self.fetch_storage_entry_with_stop(entry_key, &stop).await
    }

    /// Fetch `entry_key` and read the cache once the fetch is answered, stopping early on
    /// `stop`; the cache holds the join of every reply observed (#864), with this node's own
    /// writes applied (#982).
    ///
    /// A reply is recognised by the fetch's reply marker
    /// ([`Swarm::storage_fetch_answered_since`] the mark read before the fetch), not by the
    /// cache holding a value: the cache may hold a value from before this fetch, and a cached
    /// value is projected at the clock of each read, so it changes with no reply when an element
    /// crosses its horizon.
    ///
    /// A failed fetch is the empty read ([`Self::answer_failed_fetch`]). This serves the
    /// directory lookups and the registration publisher alike: a publisher whose fetch fails
    /// chooses what to tombstone from its cached observation instead of abandoning the attempt,
    /// and its own replaced values are still caught by its record of what it published.
    ///
    /// Post: the cache read after the reply, or, if none arrives within the fetch-poll budget,
    /// the cache read at its end.
    pub(crate) async fn fetch_storage_entry_with_stop(
        &self,
        entry_key: Did,
        stop: &StopToken,
    ) -> Result<Option<entry::Entry>> {
        if stop.should_stop() {
            return Err(Error::RegistrationStopped);
        }
        let mark = self.swarm.storage_fetch_mark();
        match self
            .swarm
            .scoped_storage(stop.clone())
            .storage_fetch(entry_key)
            .await
            .map_err(stoppable_storage_error)
        {
            Ok(()) => {}
            // A stop is the caller's cooperative stop, not a failed read.
            Err(Error::RegistrationStopped) => return Err(Error::RegistrationStopped),
            Err(error) => return self.answer_failed_fetch(entry_key, error).await,
        }
        for attempt in 0..DHT_LOOKUP_CACHE_POLL_ATTEMPTS {
            if stop.should_stop() {
                return Err(Error::RegistrationStopped);
            }
            let answered = self
                .swarm
                .storage_fetch_answered_since(entry_key, mark)
                .map_err(Error::EntryError)?;
            if answered || is_final_lookup_poll(attempt) {
                break;
            }
            if !sleep_unless_stopped(DHT_LOOKUP_CACHE_POLL_INTERVAL, stop, &StopToken::never())
                .await?
            {
                return Err(Error::RegistrationStopped);
            }
        }
        Ok(self.storage_check_cache(entry_key).await)
    }

    /// Answer a fetch of `entry_key` that failed with `error` as the empty read,
    /// `cache ⊔ ∅ = cache`: from the live cached carrier, and with `error` only when there is none.
    async fn answer_failed_fetch(
        &self,
        entry_key: Did,
        error: Error,
    ) -> Result<Option<entry::Entry>> {
        let cached = self.storage_check_cache(entry_key).await;
        if cached.is_some() {
            tracing::debug!(%entry_key, %error, "storage fetch failed; answering from the cache");
        }
        cached.map(Some).ok_or(error)
    }

    /// Build an onion proxy route for a client target through a target-agnostic proxy config.
    pub async fn build_onion_proxy_route(
        &self,
        proxy: OnionProxyProtocol,
        target: OnionProxyTarget,
    ) -> Result<OnionProxyRoute> {
        directory::build_onion_proxy_route(self, proxy, target).await
    }

    /// Run stabilization and node registration tasks until this future is dropped or aborted.
    ///
    /// This is a long-running task; do not await completion as a readiness signal. Concurrent
    /// calls on this processor queue, and each call retains ownership through cleanup.
    pub async fn listen(&self) {
        self.listen_with(StopToken::never()).await;
    }

    /// Run stabilization and node registration tasks until `stop` asks them to exit.
    ///
    /// Concurrent calls on this processor queue, including calls through any clone or
    /// provider wrapper. A stop requested while queued is observed after that call acquires
    /// ownership, so its cleanup cannot overlap the current generation.
    ///
    /// The shutdown is cooperative: it waits for the current stabilization or
    /// registration operation to finish before returning. This avoids dropping
    /// browser IndexedDB request futures while their JavaScript callbacks are
    /// still pending.
    pub async fn listen_with(&self, stop: StopToken) {
        self.listen_with_started(stop, || {}).await;
    }

    /// Run one serialized listener generation, notifying `on_started` only after it owns
    /// the processor lifecycle lock. Ownership remains held through cleanup and measurement
    /// flushing. Browser promises use this signal to preserve queued-start semantics while
    /// sharing ownership with native callers.
    pub(crate) async fn listen_with_started<F>(&self, stop: StopToken, on_started: F)
    where F: FnOnce() {
        let _listener_lifecycle_guard = self.listener_lifecycle_lock.lock().await;
        on_started();
        self.run_listener_generation_until(stop).await;
    }

    /// Run one listener generation until `stop` or the node's stop asks it to exit: each is
    /// forwarded to the one stop the generation observes, so it winds down cooperatively on
    /// either, and a close (#1085) ends it as the caller's stop does.
    async fn run_listener_generation_until(&self, stop: StopToken) {
        let generation = StopSource::new();
        let node = self.tasks.stop_token();
        let forward = async {
            let caller = stop.stopped();
            let node = node.stopped();
            futures::pin_mut!(caller, node);
            let _ = futures::future::select(caller, node).await;
            generation.request_stop();
        };
        let run = self.run_listener_generation(generation.token());
        futures::pin_mut!(forward, run);
        if let futures::future::Either::Left(((), run)) =
            futures::future::select(forward, run).await
        {
            run.await;
        }
    }

    /// Wait until no listener generation runs: the one running, if any, has ended with its
    /// cleanup and measurement flush.
    pub(crate) async fn await_listener_generations(&self) {
        drop(self.listener_lifecycle_lock.lock().await);
    }

    /// Run maintenance and registration loops for the generation holding the lifecycle lock.
    async fn run_listener_generation(&self, stop: StopToken) {
        let stabilizer = Arc::new(self.swarm.stabilizer());
        if self.registration_tasks.is_empty() {
            stabilizer.wait_with(self.stabilize_interval, stop).await;
        } else {
            let registration_stop_source = StopSource::new();
            let registration_stop = registration_stop_source.token();
            let stabilizer_stop = stop.clone();
            let stabilization = async {
                stabilizer
                    .wait_with(self.stabilize_interval, stabilizer_stop)
                    .await;
                registration_stop_source.request_stop();
            };
            let _ = futures::future::join(
                stabilization,
                self.registration_daemons_with(stop, registration_stop),
            )
            .await;
        }
        if let Err(error) = self.flush_measurements().await {
            tracing::error!(%error, "failed to flush measurements during graceful shutdown");
        }
    }

    /// Return the processor's listener lifecycle lock for lifecycle tests.
    #[cfg(test)]
    pub(crate) fn listener_lifecycle_lock_for_test(&self) -> Arc<futures::lock::Mutex<()>> {
        self.listener_lifecycle_lock.clone()
    }

    /// Flush all applied measurement updates with the graceful-shutdown deadline.
    pub async fn flush_measurements(&self) -> Result<()> {
        self.flush_measurements_with_timeout(MEASUREMENT_FLUSH_TIMEOUT)
            .await
    }

    pub(crate) async fn flush_measurements_with_timeout(&self, timeout: Duration) -> Result<()> {
        if let Some(measure) = &self.measure {
            measure.flush_with_timeout(timeout).await?;
        }
        Ok(())
    }

    #[cfg(all(test, rings_native))]
    pub(crate) async fn record_authenticated_measurement_for_test(
        &self,
        peer: Did,
    ) -> std::result::Result<(), rings_core::measure::MeasureError> {
        if let Some(measure) = &self.measure {
            rings_core::measure::Measure::record(
                measure.as_ref(),
                peer,
                rings_core::measure::Authentication::Authenticated,
                rings_core::measure::MeasurementEvent::Connected,
            )
            .await?;
        }
        Ok(())
    }

    /// Disconnect a peer with web3 did.
    pub async fn disconnect(&self, did: Did) -> Result<()> {
        self.swarm
            .disconnect(did)
            .await
            .map_err(Error::CloseConnectionError)
    }

    /// 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.
    pub async fn leave(&self) -> Result<()> {
        self.swarm
            .leave()
            .await
            .map_err(Error::CloseConnectionError)
    }

    /// Close this node's network: the swarm sends a best-effort departure (`Swarm::leave`,
    /// #1057), opens no connection from now on and closes every one it has (`Swarm::close`,
    /// #1098), then the applied measurements are flushed.
    ///
    /// These are steps (c) and (d) of [`Provider::close`](crate::provider::Provider::close)
    /// only: this stops no task and releases no store. A node that stops in a process that
    /// goes on is closed with `Provider::close`, which also stops the node's tasks and awaits
    /// the release of its stores (#1085). Each peer sees its connection close at once instead
    /// of waiting for an ICE timeout.
    ///
    /// Both steps run even if the first fails; the first failure is returned.
    pub async fn close(&self) -> Result<()> {
        self.close_with_timeout(MEASUREMENT_FLUSH_TIMEOUT).await
    }

    pub(crate) async fn close_with_timeout(&self, timeout: Duration) -> Result<()> {
        {
            let leave = self.leave();
            let deadline = rings_runtime::sleep(timeout);
            futures::pin_mut!(leave, deadline);
            if let futures::future::Either::Right((timer, _)) =
                futures::future::select(leave, deadline).await
            {
                match timer {
                    Ok(()) => tracing::warn!(
                        timeout_ms = u64::try_from(timeout.as_millis()).unwrap_or(u64::MAX),
                        "best-effort departure timed out during processor close"
                    ),
                    Err(error) => {
                        tracing::warn!(?error, "departure timer unavailable during processor close")
                    }
                }
            }
        }
        let closed = self
            .swarm
            .close()
            .await
            .map_err(Error::CloseConnectionError);
        let flushed = self.flush_measurements_with_timeout(timeout).await;
        closed.and(flushed)
    }

    /// check local cache of dht
    pub async fn storage_check_cache(&self, entry_key: Did) -> Option<entry::Entry> {
        self.swarm.storage_check_cache(entry_key).await
    }

    /// Fetch an entry from DHT storage
    ///
    /// # Rerouting
    ///
    /// Every DHT operation of this processor (fetch, store, append, tombstone, and the
    /// registry lookups and writes built on them) is rerouted as core's [`ChordStorageInterface`]
    /// documents (#859): refusals before acceptance are retried on events within a budget, and
    /// no placement is applied twice. A caller that must bound the wait drops the operation.
    pub async fn storage_fetch(&self, entry_key: Did) -> Result<()> {
        self.swarm
            .storage_fetch(entry_key)
            .await
            .map_err(Error::EntryError)
    }

    /// Store an entry on DHT storage, replacing its payloads.
    ///
    /// Each stored payload expires by the element lifetime rule of [`ChordStorageInterface`]
    /// unless it is written again. Its visibility is that interface's: once this returns `Ok`,
    /// this node reads the entry (read-your-writes, #982); another node reads it once an owner
    /// its lookup reaches holds it.
    ///
    /// Rerouted as [`Self::storage_fetch`] documents.
    pub async fn storage_store(&self, entry: entry::Entry) -> Result<()> {
        self.swarm
            .storage_store(entry)
            .await
            .map_err(Error::EntryError)
    }

    /// Append data to an entry on DHT storage.
    ///
    /// The appended element expires by the element lifetime rule of [`ChordStorageInterface`],
    /// even while other writes keep the topic alive, unless it is appended again.
    ///
    /// Rerouted as [`Self::storage_fetch`] documents.
    pub async fn storage_append_data(&self, topic: &str, data: Bytes) -> Result<()> {
        self.swarm
            .storage_append_data(topic, data)
            .await
            .map_err(Error::EntryError)
    }

    /// Append the elements `data` to the data topic `topic` as one delta, requesting the
    /// retention bound `now + lifetime_ms`, whose owners report it (core's
    /// [`storage_extend_reported`](rings_core::swarm::storage_api::ScopedStorage::storage_extend_reported)):
    /// the receipt resolves once their reports decide `quorum`.
    ///
    /// Rerouted as [`Self::storage_fetch`] documents, its rerouting waits ending at `stop`.
    pub async fn storage_extend_reported(
        &self,
        topic: &str,
        data: Vec<Bytes>,
        lifetime_ms: u64,
        quorum: StoreQuorum,
        stop: &StopToken,
    ) -> Result<StoreReceipt> {
        self.swarm
            .scoped_storage(stop.clone())
            .storage_extend_reported(topic, data, lifetime_ms, quorum)
            .await
            .map_err(Error::EntryError)
    }

    /// Append `text` to the data topic `topic` as one UTF-8 element: the encoding
    /// [`Self::fetch_text_elements`] decodes.
    pub(crate) async fn append_text_element(&self, topic: &str, text: String) -> Result<()> {
        self.storage_append_data(topic, Bytes::from(text)).await
    }

    /// The elements of the data topic `topic` past the first `skip`, decoded as UTF-8 text; an
    /// element that is not UTF-8 is omitted, and a topic not found has no elements.
    ///
    /// Law (read-your-writes, #982): on one node, `append_text_element(t, x)` returning `Ok`
    /// then `fetch_text_elements(t, 0)` contains `x` while the element is live and `t` cached.
    pub(crate) async fn fetch_text_elements(
        &self,
        topic: &str,
        skip: usize,
    ) -> Result<Vec<String>> {
        let Some(entry) = self
            .fetch_storage_entry(entry::Entry::gen_did(topic)?)
            .await?
        else {
            return Ok(vec![]);
        };
        Ok(entry
            .data
            .iter()
            .skip(skip)
            .filter_map(|element| String::from_utf8(element.to_vec()).ok())
            .collect())
    }

    /// Tombstone observed data in an entry on DHT storage.
    ///
    /// The removal covers every dot of `data` the storage owner holds, including earlier dots
    /// forgotten under a later one, and is collected once every add it covers has expired.
    ///
    /// Rerouted as [`Self::storage_fetch`] documents.
    pub async fn storage_tombstone_data(&self, topic: &str, data: Bytes) -> Result<()> {
        self.swarm
            .storage_tombstone_data(topic, data)
            .await
            .map_err(Error::EntryError)
    }

    /// Return local measurement counters for a peer, if observed.
    pub async fn peer_measurement(&self, did: Did) -> Option<PeerMeasurement> {
        self.swarm.peer_measurement(did).await
    }

    /// Return every retained local peer measurement.
    pub async fn peer_measurements(&self) -> Vec<PeerMeasurement> {
        let mut measurements = self.swarm.peer_measurements().await;
        measurements.sort_by_key(|measurement| measurement.did);
        measurements
    }

    /// Return one bounded page of retained local peer measurements.
    pub async fn peer_measurements_page(
        &self,
        after: Option<Did>,
        limit: NonZeroUsize,
    ) -> PeerMeasurementPage {
        self.swarm.peer_measurements_page(after, limit).await
    }

    /// Return one bounded page of locally collected provisional receipts.
    pub async fn provisional_evidence_page(
        &self,
        after: Option<EvidenceDigest>,
        limit: NonZeroUsize,
    ) -> std::result::Result<EvidencePage<Did>, EvidenceError> {
        let Some(measure) = &self.measure else {
            return Err(EvidenceError::StorageUnavailable);
        };
        rings_core::measure::Measure::provisional_evidence_page(measure.as_ref(), after, limit)
            .await
    }

    /// Return aggregate receipt admission and eviction counters without account labels.
    pub async fn provisional_evidence_counters(&self) -> EvidenceCounters {
        match &self.measure {
            Some(measure) => {
                rings_core::measure::Measure::provisional_evidence_counters(measure.as_ref()).await
            }
            None => EvidenceCounters::default(),
        }
    }

    /// Return aggregate final-destination origin-quota drops by lane and reason.
    pub fn origin_quota_counters(&self) -> OriginQuotaCounters {
        self.swarm.origin_quota_counters()
    }

    /// Register this node under the service name `name`.
    ///
    /// The registration is one appended element, so it expires by the element lifetime rule of
    /// [`ChordStorageInterface`] unless it is registered again.
    pub async fn register_service(&self, name: &str) -> Result<()> {
        self.append_text_element(name, self.did().to_string())
            .await
            .map_err(|error| match error {
                Error::EntryError(error) => Error::ServiceRegisterError(error),
                error => error,
            })
    }

    /// get node info
    pub async fn get_node_info(&self) -> Result<NodeInfoResponse> {
        Ok(NodeInfoResponse {
            version: crate::util::build_version(),
            swarm: Some(self.swarm.inspect().await.into()),
        })
    }

    /// Assemble the documented v1 operator snapshot without serializing stored entry payloads.
    pub async fn operator_snapshot(&self) -> Result<OperatorSnapshot> {
        let generated_at_ms = self.clock().now_ms();
        let runtime = self.observability.runtime_snapshot(generated_at_ms);
        let delegation = self.delegatee_key().delegation();
        let expires_at_ms = delegation.expires_at_ms();
        let (rotation_succeeded_total, rotation_failed_total) = self.session_keys.rotation_counts();
        let mailbox = self
            .swarm
            .mailbox_storage_inspect()
            .await
            .map_err(Error::InternalError)?;
        let admitted_peer_count = u64::try_from(self.swarm.peers().len()).unwrap_or(u64::MAX);
        let has_admitted_peer = admitted_peer_count > 0;
        let dht = DHTInspect::inspect(&self.swarm.dht());
        let has_successor = !dht.successors.is_empty();
        let has_predecessor = dht.predecessor.is_some();
        let mut peer_ratings = self.peer_measurements().await;
        peer_ratings.sort_unstable_by_key(|measurement| measurement.did);
        peer_ratings.truncate(PEER_RATING_CAPACITY);
        let peer_ratings = peer_ratings
            .into_iter()
            .map(|measurement| PeerRatingSnapshot {
                peer: measurement.did.to_string(),
                reliability: peer_quality_name(measurement.quality),
                credit_score: measurement.credit_score.as_f64(),
                sent: measurement.evidence.sent,
                failed_to_send: measurement.evidence.failed_to_send,
                received: measurement.evidence.received,
                failed_to_receive: measurement.evidence.failed_to_receive,
            })
            .collect();

        Ok(OperatorSnapshot {
            schema_version: OPERATOR_SCHEMA_VERSION,
            generated_at_ms,
            process_started_at_ms: self.observability.process_started_at_ms(),
            counter_scope: "node_local_process_lifetime",
            messages: runtime.messages,
            recent_messages: runtime.recent_messages,
            session_key: SessionKeySnapshot {
                valid: !delegation.is_expired_at(generated_at_ms),
                created_at_ms: delegation.created_at_ms(),
                expires_at_ms,
                remaining_ms: expires_at_ms.saturating_sub(generated_at_ms),
                rotation_succeeded_total,
                rotation_failed_total,
                runtime_rotation_supported: true,
            },
            mailboxes: MailboxSnapshot {
                registered: mailbox.registered,
                held_messages: mailbox.held_messages,
                stored_total: runtime.messages.stored,
            },
            dht_lookups: runtime.dht_lookups,
            peer_ratings,
            health: HealthSnapshot {
                process_api_healthy: true,
                admitted_peer_count,
                has_admitted_peer,
                has_successor,
                has_predecessor,
                overlay_ready: has_admitted_peer
                    && has_successor
                    && self.signing_horizon().signs_at(generated_at_ms),
            },
        })
    }
}

/// Stable text form of one advisory local peer-quality class.
const fn peer_quality_name(quality: PeerQuality) -> &'static str {
    match quality {
        PeerQuality::Healthy => "healthy",
        PeerQuality::Unknown => "unknown",
        PeerQuality::Degraded => "degraded",
    }
}

#[cfg_attr(all(feature = "browser", target_family = "wasm"), async_trait::async_trait(?Send))]
#[cfg_attr(
    not(all(feature = "browser", target_family = "wasm")),
    async_trait::async_trait
)]
impl OnionDirectoryReader for Processor {
    fn local_did(&self) -> Did {
        self.did()
    }

    fn dht_protocol_mode(&self) -> DhtProtocolMode {
        self.swarm.dht_protocol_mode()
    }

    async fn live_online_nodes(&self) -> Result<Vec<OnlineNodeDescriptor>> {
        self.lookup_online_nodes(false).await
    }

    async fn live_onion_exits(&self, service: &str) -> Result<Vec<OnionExitDescriptor>> {
        self.lookup_onion_exits(service, false).await
    }

    async fn live_onion_invokes(&self) -> Result<Vec<crate::onion::OnionInvokeDescriptor>> {
        self.lookup_onion_invokes(None, "", false).await
    }

    async fn peer_qualities(&self) -> Vec<(Did, PeerQuality)> {
        self.peer_measurements()
            .await
            .into_iter()
            .map(|measurement| (measurement.did, measurement.quality))
            .collect()
    }

    fn direct_peer_dids(&self) -> BTreeSet<Did> {
        let local = self.did();
        self.swarm
            .peer_dids()
            .into_iter()
            .filter(|did| *did != local)
            .collect()
    }

    fn onion_entry_guards(&self) -> &OnionEntryGuards {
        self.onion_entry_guards.as_ref()
    }

    fn now_ms(&self) -> u128 {
        self.clock().now_ms()
    }

    fn route_rng(&self) -> SharedRng {
        self.rng().clone()
    }
}

#[cfg(all(test, feature = "node"))]
mod tests;