rings_core/swarm/mod.rs
1#![deny(missing_docs)]
2
3//! This mod is the main entrance of swarm.
4
5pub mod application;
6mod builder;
7/// The transport callback of a connection: its inbound pipeline and lifecycle handling.
8pub(crate) mod callback;
9mod detached;
10/// The admitted edges of a node, read and awaited (#855).
11pub mod edges;
12pub(crate) mod inbox;
13/// Non-blocking observation hooks for operator telemetry.
14pub mod observer;
15pub(crate) mod session_link;
16/// The Swarm's storage API, at the application boundary.
17pub mod storage_api;
18pub(crate) mod transport;
19
20use std::num::NonZeroUsize;
21use std::sync::Arc;
22
23pub use builder::SwarmBuilder;
24/// The read-only view of one lane's send credit that [`Swarm::application_credit`] returns: the
25/// transport's type, re-exported so an application reads it through core alone.
26pub use rings_transport::core::transport::LaneCreditView;
27/// The instant from which a node can sign no frame with its own delegation (#1063).
28pub use session_link::signing_horizon_ms;
29
30use self::callback::SwarmTransportCallback;
31use crate::delegation::DelegateeKey;
32use crate::dht::Chord;
33use crate::dht::Did;
34use crate::dht::PeerRing;
35use crate::dht::PeerRingAction;
36use crate::dht::Stabilizer;
37use crate::ecc::PublicKey;
38use crate::ecc::VerificationPublicKey;
39use crate::error::Error;
40use crate::error::Result;
41use crate::inspect::ConnectionInspect;
42use crate::inspect::MailboxStorageInspect;
43use crate::inspect::SwarmInspect;
44use crate::measure::PeerMeasurement;
45use crate::measure::PeerMeasurementPage;
46use crate::message::DhtProtocolMode;
47use crate::message::FindSuccessorReportHandler;
48use crate::message::FindSuccessorSend;
49use crate::message::FindSuccessorThen;
50use crate::message::Message;
51use crate::message::MessageCategory;
52use crate::message::MessageLimit;
53use crate::message::MessagePayload;
54use crate::message::MessageVerificationExt;
55use crate::message::OriginQuotaCounters;
56use crate::message::PayloadSender;
57use crate::message::Principal;
58use crate::message::ReplayCounters;
59use crate::message::ReplayWindow;
60use crate::swarm::application::ApplicationData;
61use crate::swarm::application::ApplicationInbox;
62use crate::swarm::application::SuccessorReport;
63use crate::swarm::edges::EdgesChanged;
64use crate::swarm::inbox::SwarmInboxDelivery;
65use crate::swarm::observer::LookupCorrelation;
66use crate::swarm::observer::LookupKind;
67use crate::swarm::observer::LookupOutcome;
68use crate::swarm::transport::CounterOffer;
69use crate::swarm::transport::CreatedAnswer;
70use crate::swarm::transport::InitiatorReplyOutcome;
71use crate::swarm::transport::OfferOwner;
72pub use crate::swarm::transport::OfferReply;
73use crate::swarm::transport::PendingConnectionAttempt;
74use crate::swarm::transport::SwarmTransport;
75use crate::utils::SharedClock;
76use crate::utils::SharedRng;
77
78/// How a successor lookup was decided: from the local topology, or routed, with the handle its
79/// report resolves.
80#[derive(Debug)]
81pub enum SuccessorLookup {
82 /// The successor of the key as the local topology knows it.
83 Local(Did),
84 /// The lookup was routed through the hop the local step chose; its report resolves this
85 /// handle.
86 Routed(SuccessorReport),
87}
88
89/// An opaque handle to one connection generation this node reserved by offering; accepted or
90/// cancelled only through the swarm that issued it.
91#[derive(Clone, Copy, Debug, Eq, PartialEq)]
92pub struct ConnectionAttempt(PendingConnectionAttempt);
93
94impl ConnectionAttempt {
95 /// The peer this generation was reserved for.
96 pub fn peer(&self) -> Did {
97 self.0.peer()
98 }
99}
100
101/// The node's storage answer clock as a fetcher read it before its fetch
102/// ([`Swarm::storage_fetch_mark`]). Marks are ordered by when they were read.
103#[derive(Clone, Copy, Debug, Eq, Ord, PartialEq, PartialOrd)]
104pub struct StorageFetchMark(u64);
105
106/// The transport and dht management.
107pub struct Swarm {
108 /// Reference of DHT.
109 pub(crate) dht: Arc<PeerRing>,
110 /// Swarm transport.
111 pub(crate) transport: Arc<SwarmTransport>,
112}
113
114impl Swarm {
115 /// Get did of self.
116 pub fn did(&self) -> Did {
117 self.dht.did
118 }
119
120 /// Get the local account public key used for E2E public-key negotiation.
121 pub fn delegator_pubkey(&self) -> Result<PublicKey<33>> {
122 self.transport.delegation().delegator_pubkey()
123 }
124
125 /// Get the typed account verification public key.
126 pub fn delegator_verification_pubkey(&self) -> Result<VerificationPublicKey> {
127 self.transport.delegation().delegator_verification_pubkey()
128 }
129
130 /// Return the session key this swarm currently signs with.
131 pub fn delegatee_key(&self) -> DelegateeKey {
132 self.transport.delegatee_key()
133 }
134
135 /// Replace the session key this swarm signs with, when it authorizes the same account DID.
136 pub fn set_delegatee_key(&self, delegatee_key: DelegateeKey) -> Result<()> {
137 self.transport.set_delegatee_key(delegatee_key)
138 }
139
140 /// Non-mutating validation phase of two-phase session-key rotation (#1291): verify that
141 /// `delegatee_key` authorizes this node's account DID, carries a valid delegator signature,
142 /// and strictly advances the signing horizon relative to the currently committed key while
143 /// holding rotation exclusion until [`SwarmRotationCommit::commit`] (or drop) completes.
144 pub fn prepare_delegatee_key_rotation(
145 &self,
146 delegatee_key: &DelegateeKey,
147 ) -> Result<SwarmRotationCommit<'_>> {
148 let rotation_guard = self.transport.lock_delegatee_rotation();
149 self.transport.validate_next_delegatee_key(delegatee_key)?;
150 Ok(SwarmRotationCommit {
151 swarm: self,
152 _rotation_guard: rotation_guard,
153 next_key: delegatee_key.clone(),
154 })
155 }
156
157 /// Get this swarm's network id.
158 pub fn network_id(&self) -> u32 {
159 self.transport.network_id
160 }
161
162 /// Return the [`SharedClock`] capability bound to this swarm.
163 pub fn clock(&self) -> &SharedClock {
164 self.transport.clock()
165 }
166
167 /// Return the [`SharedRng`] capability bound to this swarm.
168 pub fn rng(&self) -> &SharedRng {
169 self.transport.rng()
170 }
171
172 /// Get the storage redundancy for this swarm's DHT protocol mode.
173 pub fn storage_redundancy(&self) -> u16 {
174 self.transport.storage_redundancy()
175 }
176
177 /// The mark a fetcher reads before `storage_fetch`, to learn from
178 /// [`Self::storage_fetch_answered_since`] when its fetch was answered.
179 pub fn storage_fetch_mark(&self) -> StorageFetchMark {
180 StorageFetchMark(self.transport.storage_lookup_mark())
181 }
182
183 /// Whether `storage_fetch` of `entry_key` cached a found entry the cache then serves,
184 /// locally or from a reply, after `mark` was read. A fetch of the key that starts meanwhile does not reset it. A
185 /// late reply to an earlier fetch also counts, and the entry it caches is still a reply
186 /// received after the mark.
187 ///
188 /// This is the fetch's reply marker. A reader cannot tell a reply by comparing cached values,
189 /// since a cached value is projected at the clock of each read and changes, with no reply,
190 /// when one of its elements crosses its horizon.
191 ///
192 /// Post: `false` once no fetch of `entry_key` is retained.
193 pub fn storage_fetch_answered_since(
194 &self,
195 entry_key: Did,
196 mark: StorageFetchMark,
197 ) -> Result<bool> {
198 self.transport.storage_lookup_answered_since(
199 entry_key,
200 self.transport.storage_redundancy(),
201 mark.0,
202 )
203 }
204
205 /// Get the storage virtual-node positions for this swarm's DHT protocol mode.
206 pub fn dht_virtual_nodes(&self) -> u16 {
207 self.transport.dht_virtual_nodes()
208 }
209
210 /// Get this swarm's full DHT protocol mode descriptor.
211 pub fn dht_protocol_mode(&self) -> DhtProtocolMode {
212 self.transport.dht_protocol_mode()
213 }
214
215 /// Get DHT(Distributed Hash Table) of self.
216 pub fn dht(&self) -> Arc<PeerRing> {
217 self.dht.clone()
218 }
219
220 /// Return the injected trait-based [`SharedTransport`](rings_transport::core::transport::SharedTransport)
221 /// backing this swarm.
222 pub fn transport(&self) -> &rings_transport::core::transport::SharedTransport {
223 self.transport.transport()
224 }
225
226 /// How many edges this node has admitted now: peers admitted and not retired
227 /// ([`edges`]).
228 pub fn admitted_edges(&self) -> usize {
229 self.dht.edges().count()
230 }
231
232 /// Resolves at the next admission or retirement of an edge after this call ([`edges`]).
233 pub fn edges_changed(&self) -> EdgesChanged {
234 EdgesChanged(self.dht.edges().changed())
235 }
236
237 /// The transport callback of a connection this swarm starts: its inbound pipeline and
238 /// lifecycle handling.
239 fn transport_callback(&self) -> SwarmTransportCallback {
240 SwarmTransportCallback::new(self.transport.clone())
241 }
242
243 /// Claim the application inbox: everything core hands the application, in order (#935).
244 ///
245 /// Claimed once; a second claim is refused as `ApplicationInboxClaimed`. Until it is
246 /// claimed, application data addressed to this node is discarded and peer facts are kept;
247 /// once it is dropped, everything is discarded. Core never waits on the reader except for
248 /// room on the application data lanes.
249 pub fn application_inbox(&self) -> Result<ApplicationInbox> {
250 self.transport.application().outlet.claim()
251 }
252
253 /// Record the message limit of application payloads starting with `namespace_prefix`:
254 /// [`MessageLimit::Delegated`] to the namespace, or [`MessageLimit::Enforced`] by core.
255 ///
256 /// The application registers its namespaces in advance and core matches the prefix on its
257 /// admission path, without calling the application. The match is exact when the
258 /// application's namespace encoding is prefix-free. Delegation is trusted local
259 /// configuration: a delegating namespace must enforce its own per-neighbour admission.
260 pub fn set_admission_delegation(&self, namespace_prefix: Vec<u8>, limit: MessageLimit) {
261 self.transport
262 .application()
263 .delegations
264 .set(namespace_prefix, limit == MessageLimit::Delegated);
265 }
266
267 /// Record the replay window of application payloads starting with `namespace_prefix`, from
268 /// the authenticated neighbour that originated them: [`ReplayWindow::Link`], a volatile
269 /// window of the link they arrived on, or [`ReplayWindow::Durable`] (#1081).
270 ///
271 /// Registered in advance and matched by core on its admission path, as
272 /// [`Self::set_admission_delegation`] is. Delegated replay is trusted local configuration: a
273 /// declaring namespace must act on each of its payloads at most once by its own replay key
274 /// (Obligation R of durable-records).
275 pub fn set_replay_delegation(&self, namespace_prefix: Vec<u8>, window: ReplayWindow) {
276 self.transport
277 .application()
278 .replay_delegations
279 .set(namespace_prefix, window == ReplayWindow::Link);
280 }
281
282 /// Whether an application payload belongs to a namespace registered as delegating through
283 /// [`Swarm::set_admission_delegation`].
284 pub fn delegates_admission(&self, application_payload: &[u8]) -> bool {
285 self.transport
286 .application()
287 .delegations
288 .delegates(application_payload)
289 }
290
291 /// Whether an application payload belongs to a namespace registered as delegating its
292 /// replay through [`Swarm::set_replay_delegation`].
293 pub fn delegates_replay(&self, application_payload: &[u8]) -> bool {
294 self.transport
295 .application()
296 .replay_delegations
297 .delegates(application_payload)
298 }
299
300 /// Create [Stabilizer] for swarm; its inbox-delivery intent is interpreted here, toward
301 /// the application inbox.
302 pub fn stabilizer(&self) -> Stabilizer {
303 Stabilizer::new(
304 self.transport.clone(),
305 Arc::new(SwarmInboxDelivery::new(self.transport.clone())),
306 )
307 }
308
309 /// Disconnect a connection. There are three steps:
310 /// 1) remove from DHT;
311 /// 2) remove from Transport;
312 /// 3) close the connection;
313 pub async fn disconnect(&self, peer: Did) -> Result<()> {
314 self.transport.disconnect(peer).await
315 }
316
317 /// Best-effort voluntary departure (#1057): hand off live relay carriers to remaining
318 /// members through the ack-gated hand-off and send `Leave { successor_list }` to this node's
319 /// predecessor and successor head before transports close.
320 pub async fn leave(&self) -> Result<()> {
321 self.transport.leave().await
322 }
323
324 /// Close this swarm: it opens no connection from now on, and every connection it has,
325 /// admitted or still handshaking, is disconnected and physically closed before this returns
326 /// (the close law of `SwarmTransport::close`, #1098).
327 ///
328 /// Each peer sees its connection close at once, as on [`Self::disconnect`], instead of
329 /// waiting for an ICE timeout. Call it before dropping a swarm that stops in a process that
330 /// goes on: dropping it frees the swarm (#1093), but a peer connection that was never closed
331 /// keeps its sockets bound. A closed swarm refuses every new connection with
332 /// [`Error::SwarmClosed`]; closing again is a no-op.
333 pub async fn close(&self) -> Result<()> {
334 self.transport.close().await
335 }
336
337 /// Start a non-routable handshake with a peer.
338 ///
339 /// The peer becomes visible through the connection inspection APIs only
340 /// after its data channel opens and the swarm admits it to the DHT.
341 pub async fn connect(&self, peer: Did) -> Result<()> {
342 if peer == self.did() {
343 return Err(Error::ShouldNotConnectSelf);
344 }
345 self.transport
346 .connect(peer, self.transport_callback())
347 .await
348 }
349
350 /// Send application `data` to `destination`, routed by Chord.
351 ///
352 /// Only [`ApplicationData`] crosses the boundary outbound, as inbound: an application cannot
353 /// originate core's own protocol messages. `data` is sent as `Message::from(data)`, which
354 /// the receiving core projects back to `data` (`project ∘ from = Some`).
355 pub async fn send_message(
356 &self,
357 data: ApplicationData,
358 destination: Did,
359 ) -> Result<uuid::Uuid> {
360 self.transport
361 .application_egress()
362 .send_message(Message::from(data), destination)
363 .await
364 }
365
366 /// Send application `data` directly to an already connected peer, without a Chord lookup.
367 ///
368 /// This preserves an application protocol's explicit next-hop selection. Callers must
369 /// ensure the destination has an active direct transport connection.
370 pub async fn send_direct_message(
371 &self,
372 data: ApplicationData,
373 destination: Did,
374 ) -> Result<uuid::Uuid> {
375 self.transport
376 .application_egress()
377 .send_direct_message(Message::from(data), destination)
378 .await
379 }
380
381 /// Test builds: send core's own `message` under the application discipline, routed by
382 /// Chord, as no application can. Witnesses that drive a protocol message end to end use it.
383 #[cfg(all(test, not(target_family = "wasm")))]
384 pub(crate) async fn send_core_message_for_test(
385 &self,
386 message: Message,
387 destination: Did,
388 ) -> Result<uuid::Uuid> {
389 self.transport
390 .application_egress()
391 .send_message(message, destination)
392 .await
393 }
394
395 /// Test builds: [`Self::send_core_message_for_test`] directly to a connected peer.
396 #[cfg(test)]
397 pub(crate) async fn send_direct_core_message_for_test(
398 &self,
399 message: Message,
400 destination: Did,
401 ) -> Result<uuid::Uuid> {
402 self.transport
403 .application_egress()
404 .send_direct_message(message, destination)
405 .await
406 }
407
408 /// List active, routable peers and their connection status.
409 ///
410 /// The status is the connection's raw WebRTC state. A peer is routable once its data
411 /// channel is open in `Connecting` or `Connected`, so a listed peer may still read
412 /// `Connecting`: a browser can open the data channel before it reports `connected`.
413 pub fn peers(&self) -> Vec<ConnectionInspect> {
414 self.transport
415 .get_connections()
416 .iter()
417 .map(|(did, c)| ConnectionInspect {
418 did: did.to_string(),
419 state: format!("{:?}", c.connection_state()),
420 })
421 .collect()
422 }
423
424 /// List DIDs with active, routable transport connections.
425 pub fn peer_dids(&self) -> Vec<Did> {
426 self.transport.get_connection_ids()
427 }
428
429 /// Whether the transport holds an unadmitted handshake to `peer` (pending or admitting),
430 /// whichever side started it. A new offer to such a peer is refused as `AlreadyConnected`
431 /// while the handshake is inside the pending timeout; a stale one is expired by the
432 /// reservation instead.
433 pub fn has_unadmitted_connection(&self, peer: Did) -> Result<bool> {
434 Ok(self.transport.unadmitted_attempt(peer)?.is_some())
435 }
436
437 /// Whether `peer` is admitted: its connection record is active. Ready or recovering, its
438 /// transport is the swarm's to heal or retire. Law: an admission is announced as
439 /// [`SwarmEvent::PeerAdmitted`](application::SwarmEvent::PeerAdmitted) in the transition
440 /// that activates the record, so `is_peer_admitted(p) ⟹` that admission was announced and
441 /// the record's retirement will be, as
442 /// [`SwarmEvent::PeerRetired`](application::SwarmEvent::PeerRetired).
443 pub fn is_peer_admitted(&self, peer: Did) -> Result<bool> {
444 Ok(self.transport.active_attempt(peer)?.is_some())
445 }
446
447 /// A read-only view of the send credit of the Application lane of `peer`'s sendable
448 /// connection generation, or `None` without one (#913). Application data travels on that
449 /// lane, so an application that shapes its own emission paces it on this view: the view
450 /// reserves nothing and holds the connection weakly, so reading it never changes what core
451 /// may send.
452 pub fn application_credit(&self, peer: Did) -> Option<LaneCreditView> {
453 self.transport.get_connection(peer).map(|connection| {
454 connection.send_credit_view(MessageCategory::Application.channel_lane())
455 })
456 }
457
458 /// `𝓡`, the capacity of the connection registry (#723): the most connection records, in
459 /// any phase, the swarm holds at once, `2 × (finger slots + successors + 1)`. It bounds the
460 /// admitted peers, so an application keying state by admitted link can size it by `𝓡`.
461 pub fn connection_registry_capacity(&self) -> Result<usize> {
462 self.transport.connection_registry_capacity()
463 }
464
465 /// Cancel the handshake `attempt` iff it is still pending, that is, no data channel has
466 /// opened on it; one that is admitting, admitted or superseded meanwhile is left alone.
467 /// Returns whether it was cancelled.
468 pub async fn cancel_pending_connection_attempt(
469 &self,
470 attempt: ConnectionAttempt,
471 ) -> Result<bool> {
472 self.transport.cancel_pending_connection(attempt.0).await
473 }
474
475 /// Unconditionally abandon connection generation `attempt` when its outbound handshake step was
476 /// never transmitted to the remote peer, retiring `Pending`, `Admitting`, and prematurely
477 /// `Active` generations of `attempt` while leaving any peer-superseded generation untouched.
478 pub async fn abandon_connection_attempt(&self, attempt: ConnectionAttempt) {
479 self.transport
480 .abandon_pending_connection(attempt.0, "abandoning unsent connection attempt")
481 .await;
482 }
483
484 /// Take the local step of a successor lookup for `key`, and route the lookup when the
485 /// local topology cannot decide it.
486 ///
487 /// Law: in a ring every present node is the successor of its own identifier, so a lookup
488 /// for `key` answers `key` exactly when `key` is in the overlay, as far as the answering
489 /// node's successor list is current. The local step decides `Local(head)` when `key` lies
490 /// in the local successor interval `(n, head]`, and `Local(n)` when this node has no
491 /// successor; otherwise the request `FindSuccessorSend { did: key, strict: false }` is sent
492 /// to the hop that same step chose, never to `key` itself even when `key` is a direct peer
493 /// (`key` would answer with its own successor), and the answer, a `FindSuccessorReport`
494 /// under the request's transaction, resolves the returned [`SuccessorReport`]. The handle is
495 /// registered before the request is sent, so its report always finds it; dropping it
496 /// withdraws the lookup. The step and the hop come from one topology snapshot.
497 pub async fn lookup_successor(&self, key: Did) -> Result<SuccessorLookup> {
498 let next = match self.dht.find_successor(key)? {
499 PeerRingAction::Some(successor) => {
500 let bridged_via =
501 if successor != key && successor != self.dht.did && key != self.dht.did {
502 let state = self.dht.topology_state()?;
503 let target_dist = crate::dht::topology::dist(state.local, key);
504 let head_dist = crate::dht::topology::dist(state.local, successor);
505 state
506 .bridged
507 .iter()
508 .filter(|(&peer, &via)| {
509 peer != state.local
510 && via != state.local
511 && state.references(via)
512 && !state.references(peer)
513 && self.transport.get_connection(via).is_some()
514 })
515 .filter_map(|(&peer, &via)| {
516 let peer_dist = crate::dht::topology::dist(state.local, peer);
517 (target_dist <= peer_dist && peer_dist < head_dist)
518 .then_some((peer_dist, via))
519 })
520 .min_by(|(dist_a, _), (dist_b, _)| dist_a.cmp(dist_b))
521 .map(|(_, via)| via)
522 } else {
523 None
524 };
525 if let Some(via) = bridged_via {
526 via
527 } else {
528 let correlation = LookupCorrelation::StorageResource(key);
529 self.transport
530 .observer()
531 .lookup_started(LookupKind::Successor, correlation);
532 self.transport.observer().lookup_finished(
533 LookupKind::Successor,
534 correlation,
535 LookupOutcome::Succeeded,
536 );
537 return Ok(SuccessorLookup::Local(successor));
538 }
539 }
540 PeerRingAction::RemoteAction(next, _) => next,
541 action => return Err(Error::PeerRingUnexpectedAction(Box::new(action))),
542 };
543 let request = Message::FindSuccessorSend(FindSuccessorSend {
544 did: key,
545 strict: false,
546 then: FindSuccessorThen::Report(FindSuccessorReportHandler::None),
547 });
548 let egress = self.transport.application_egress();
549 let payload = egress.originate(request, key, Some(next)).await?;
550 let report = self
551 .transport
552 .application()
553 .lookups
554 .register(payload.transaction.tx_id);
555 egress.send_payload(payload).await?;
556 Ok(SuccessorLookup::Routed(report))
557 }
558
559 /// Return local measurement counters for `peer`, if observed.
560 pub async fn peer_measurement(&self, peer: Did) -> Option<PeerMeasurement> {
561 self.transport.peer_measurement(peer).await
562 }
563
564 /// Return every retained local peer measurement.
565 pub async fn peer_measurements(&self) -> Vec<PeerMeasurement> {
566 self.transport.peer_measurements().await
567 }
568
569 /// Return one bounded page of retained local peer measurements.
570 pub async fn peer_measurements_page(
571 &self,
572 after: Option<Did>,
573 limit: NonZeroUsize,
574 ) -> PeerMeasurementPage {
575 self.transport.peer_measurements_page(after, limit).await
576 }
577
578 /// Check the status of swarm
579 pub async fn inspect(&self) -> SwarmInspect {
580 SwarmInspect::inspect(self).await
581 }
582
583 /// Return aggregate live relay-inbox state without identifiers or payloads.
584 pub async fn mailbox_storage_inspect(&self) -> Result<MailboxStorageInspect> {
585 MailboxStorageInspect::inspect(&self.dht).await
586 }
587
588 /// Return destination-scoped transaction replay counters.
589 pub fn transaction_replay_counters(&self) -> ReplayCounters {
590 self.transport.replay_counters()
591 }
592
593 /// Return aggregate final-destination origin-quota drop counters by logical lane and reason.
594 pub fn origin_quota_counters(&self) -> OriginQuotaCounters {
595 self.transport.origin_quota_counters()
596 }
597}
598
599impl Swarm {
600 /// Create an outbound transport connection offer for `peer`, wrapped in a signed
601 /// [`MessagePayload`].
602 pub async fn create_offer(&self, peer: Did) -> Result<MessagePayload> {
603 self.offer_connection(peer)
604 .await
605 .map(|(_, payload)| payload)
606 }
607
608 /// Reserve an out-of-band connection generation for `peer` and execute step `0` of its
609 /// handshake, returning `(attempt, None)` when a 0-step transport completes locally without
610 /// emitting any signaling message, or `(attempt, Some(payload))` when an outbound step `0`
611 /// `ConnectNodeSend` payload is produced (#1291).
612 pub async fn offer_connection_step(
613 &self,
614 peer: Did,
615 ) -> Result<(ConnectionAttempt, Option<MessagePayload>)> {
616 let (attempt, initial_step) = self
617 .transport
618 .prepare_connection_offer_owned_by(
619 peer,
620 self.transport_callback(),
621 OfferOwner::External,
622 )
623 .await?;
624 let offer_msg = match initial_step {
625 transport::InitialOfferStep::Completed => {
626 return Ok((ConnectionAttempt(attempt), None))
627 }
628 transport::InitialOfferStep::Send(offer_msg) => offer_msg,
629 };
630
631 // This payload has fake next_hop.
632 // The invoker should fix it before sending.
633 let payload = self
634 .transport
635 .settle_handshake_step(
636 attempt,
637 "wrapping connection offer",
638 self.transport.application_egress().originate(
639 Message::ConnectNodeSend(offer_msg.clone()),
640 peer,
641 Some(self.did()),
642 ),
643 )
644 .await?;
645 if let Err(error) =
646 self.transport
647 .mark_offer_sent(attempt, &offer_msg, payload.transaction.tx_id)
648 {
649 return Err(self
650 .transport
651 .classify_step_failure(attempt, error, "marking connection offer sent")
652 .await?);
653 }
654
655 Ok((ConnectionAttempt(attempt), Some(payload)))
656 }
657
658 /// Reserve a connection generation for `peer` and create its 2-step out-of-band offer,
659 /// returning the attempt that names the generation so the caller can accept the answer for it
660 /// or cancel it without touching a handshake the peer started meanwhile.
661 ///
662 /// The caller owns the offer and carries it out of band, so the attempt never sends it
663 /// over the DHT as a counter-offer (#947). It prevails over a crossing overlay offer, which
664 /// is refused; of a crossing out-of-band offer, one from a larger DID is refused and one from
665 /// a smaller DID takes the slot (`Law (Tie-break)`). Transports that complete in 0 or 1 steps
666 /// return [`rings_transport::error::Error::UnsupportedOperation`] here (use
667 /// [`Self::offer_connection_step`] or [`Self::connect`]).
668 pub async fn offer_connection(&self, peer: Did) -> Result<(ConnectionAttempt, MessagePayload)> {
669 let (attempt, initial_step) = self
670 .transport
671 .prepare_connection_offer_owned_by(
672 peer,
673 self.transport_callback(),
674 OfferOwner::External,
675 )
676 .await?;
677 let offer_msg = match initial_step {
678 transport::InitialOfferStep::Send(offer_msg) if !offer_msg.final_step => offer_msg,
679 transport::InitialOfferStep::Completed | transport::InitialOfferStep::Send(_) => {
680 let err = Error::Transport(rings_transport::error::Error::UnsupportedOperation(
681 "out-of-band offer_connection requires a non-final initial offer; use offer_connection_step or Swarm::connect"
682 .to_string(),
683 ));
684 return Err(self
685 .transport
686 .classify_step_failure(attempt, err, "creating out-of-band connection offer")
687 .await?);
688 }
689 };
690
691 // This payload has fake next_hop.
692 // The invoker should fix it before sending.
693 let payload = self
694 .transport
695 .settle_handshake_step(
696 attempt,
697 "wrapping connection offer",
698 self.transport.application_egress().originate(
699 Message::ConnectNodeSend(offer_msg.clone()),
700 peer,
701 Some(self.did()),
702 ),
703 )
704 .await?;
705 if let Err(error) =
706 self.transport
707 .mark_offer_sent(attempt, &offer_msg, payload.transaction.tx_id)
708 {
709 return Err(self
710 .transport
711 .classify_step_failure(attempt, error, "marking connection offer sent")
712 .await?);
713 }
714
715 Ok((ConnectionAttempt(attempt), payload))
716 }
717
718 /// Verify and apply an out-of-band `ConnectNodeSend` handshake step, returning
719 /// `OfferReply::Answer(None)` when a final inbound step completes the handshake without an
720 /// outbound reply, `OfferReply::Answer(Some(payload))` when a reply `ConnectNodeReport` is
721 /// produced, or `OfferReply::CounterOffer(payload)` when this node's prevailing offer wins.
722 pub async fn answer_offer_step(
723 &self,
724 offer_payload: MessagePayload,
725 ) -> Result<OfferReply<Option<MessagePayload>, MessagePayload>> {
726 if !offer_payload
727 .verify_transaction_and_payload_at(self.network_id(), self.transport.now_ms())
728 {
729 return Err(Error::VerifySignatureFailed);
730 }
731
732 let Message::ConnectNodeSend(msg) = offer_payload.transaction.data()? else {
733 return Err(Error::InvalidMessage(
734 "Should be ConnectNodeSend".to_string(),
735 ));
736 };
737 if offer_payload.transaction.destination != self.did() {
738 return Err(Error::InvalidMessage(
739 "ConnectNodeSend destination does not match this node".to_string(),
740 ));
741 }
742 self.transport
743 .admit_final_transaction(
744 &offer_payload.transaction,
745 MessageCategory::DhtControl.into(),
746 Principal::Local,
747 )
748 .await?;
749
750 let peer = offer_payload.transaction.origin();
751 match self
752 .transport
753 .answer_remote_connection(peer, self.transport_callback(), &msg)
754 .await?
755 {
756 OfferReply::Answer(Some(CreatedAnswer { attempt, report })) => self
757 .transport
758 .settle_handshake_step(
759 attempt,
760 "wrapping connection answer",
761 self.transport.application_egress().originate(
762 Message::ConnectNodeReport(report),
763 peer,
764 Some(self.did()),
765 ),
766 )
767 .await
768 .map(|payload| OfferReply::Answer(Some(payload))),
769 OfferReply::Answer(None) => Ok(OfferReply::Answer(None)),
770 OfferReply::CounterOffer(CounterOffer { offer, .. }) => self
771 .transport
772 .application_egress()
773 .originate(Message::ConnectNodeSend(offer), peer, Some(self.did()))
774 .await
775 .map(OfferReply::CounterOffer),
776 }
777 }
778
779 /// Answer the offer of remote connection. This function will verify the answer payload and
780 /// will wrap the answer inside a payload with verification.
781 ///
782 /// The offer is carried out of band, so it prevails over this node's own sent overlay offer
783 /// to the same peer, which is released (`Law (Tie-break)`), and the reply is
784 /// [`OfferReply::Answer`], a final `ConnectNodeReport` for the peer's `accept_answer`: a
785 /// counter-offer would leave the peer to deliver its answer through this node's
786 /// `accept_answer`, which a node's public HTTP API does not serve. Nodes of 0.34.2 and
787 /// earlier reply with [`OfferReply::CounterOffer`] when their sent overlay offer prevails on
788 /// the DID tie-break (#947): that offer, a `ConnectNodeSend`, which the caller hands to the
789 /// peer's `answer_offer`; the peer abandons its own offer and answers this one, and that
790 /// answer goes to the replying node's `accept_answer`. Crossing no edge, the offer opens a
791 /// replay stream on this node's local share.
792 pub async fn answer_offer(
793 &self,
794 offer_payload: MessagePayload,
795 ) -> Result<OfferReply<MessagePayload, MessagePayload>> {
796 if !offer_payload
797 .verify_transaction_and_payload_at(self.network_id(), self.transport.now_ms())
798 {
799 return Err(Error::VerifySignatureFailed);
800 }
801
802 let Message::ConnectNodeSend(msg) = offer_payload.transaction.data()? else {
803 return Err(Error::InvalidMessage(
804 "Should be ConnectNodeSend".to_string(),
805 ));
806 };
807 if offer_payload.transaction.destination != self.did() {
808 return Err(Error::InvalidMessage(
809 "ConnectNodeSend destination does not match this node".to_string(),
810 ));
811 }
812 if msg.step_index != 0 || msg.final_step {
813 return Err(Error::Transport(
814 rings_transport::error::Error::UnsupportedOperation(
815 "out-of-band answer_offer requires a non-final step-0 ConnectNodeSend; use answer_offer_step"
816 .to_string(),
817 ),
818 ));
819 }
820 self.transport
821 .admit_final_transaction(
822 &offer_payload.transaction,
823 MessageCategory::DhtControl.into(),
824 Principal::Local,
825 )
826 .await?;
827
828 let peer = offer_payload.transaction.origin();
829 // The reply payload has a fake next_hop; the invoker fixes it before sending.
830 match self
831 .transport
832 .answer_remote_connection(peer, self.transport_callback(), &msg)
833 .await?
834 {
835 OfferReply::Answer(Some(CreatedAnswer { attempt, report })) if report.final_step => {
836 self.transport
837 .settle_handshake_step(
838 attempt,
839 "wrapping connection answer",
840 self.transport.application_egress().originate(
841 Message::ConnectNodeReport(report),
842 peer,
843 Some(self.did()),
844 ),
845 )
846 .await
847 .map(OfferReply::Answer)
848 }
849 OfferReply::Answer(Some(CreatedAnswer { attempt, .. })) => {
850 let err = Error::Transport(rings_transport::error::Error::UnsupportedOperation(
851 "out-of-band answer_offer requires a 2-step transport; use answer_offer_step or Swarm::connect"
852 .to_string(),
853 ));
854 Err(self
855 .transport
856 .classify_step_failure(attempt, err, "answering out-of-band offer")
857 .await?)
858 }
859 OfferReply::Answer(None) => {
860 if let Some(attempt) = self.transport.unadmitted_attempt(peer)? {
861 self.transport
862 .abandon_pending_connection(attempt, "answering out-of-band offer")
863 .await;
864 }
865 Err(Error::Transport(
866 rings_transport::error::Error::UnsupportedOperation(
867 "out-of-band answer_offer completed without a reply payload; use answer_offer_step"
868 .to_string(),
869 ),
870 ))
871 }
872 OfferReply::CounterOffer(CounterOffer { offer, .. }) => self
873 .transport
874 .application_egress()
875 .originate(Message::ConnectNodeSend(offer), peer, Some(self.did()))
876 .await
877 .map(OfferReply::CounterOffer),
878 }
879 }
880
881 /// Verify a remote `ConnectNodeReport` handshake step and apply it to the pending initiator
882 /// handshake (#1291), returning `Ok(None)` when a final report completes the handshake or
883 /// `Ok(Some(payload))` containing the next signed even `ConnectNodeSend` continuation step for
884 /// `>= 3`-step out-of-band handshakes.
885 pub async fn accept_answer_step(
886 &self,
887 answer_payload: MessagePayload,
888 ) -> Result<Option<MessagePayload>> {
889 self.accept_answer_step_with(None, answer_payload).await
890 }
891
892 /// Verify a remote `ConnectNodeReport` handshake step and apply it to the exact initiator
893 /// generation `attempt` reserved by [`Swarm::offer_connection_step`] (#1291), returning
894 /// `Ok(None)` when a final report completes the handshake or `Ok(Some(payload))` containing
895 /// the next signed even `ConnectNodeSend` continuation step.
896 pub async fn accept_answer_step_for(
897 &self,
898 attempt: ConnectionAttempt,
899 answer_payload: MessagePayload,
900 ) -> Result<Option<MessagePayload>> {
901 self.accept_answer_step_with(Some(attempt.0), answer_payload)
902 .await
903 }
904
905 async fn accept_answer_step_with(
906 &self,
907 expected: Option<PendingConnectionAttempt>,
908 answer_payload: MessagePayload,
909 ) -> Result<Option<MessagePayload>> {
910 if !answer_payload
911 .verify_transaction_and_payload_at(self.network_id(), self.transport.now_ms())
912 {
913 return Err(Error::VerifySignatureFailed);
914 }
915
916 let Message::ConnectNodeReport(ref msg) = answer_payload.transaction.data()? else {
917 return Err(Error::InvalidMessage(
918 "Should be ConnectNodeReport".to_string(),
919 ));
920 };
921 if answer_payload.transaction.destination != self.did() {
922 return Err(Error::InvalidMessage(
923 "ConnectNodeReport destination does not match this node".to_string(),
924 ));
925 }
926 self.transport
927 .admit_final_transaction(
928 &answer_payload.transaction,
929 MessageCategory::DhtControl.into(),
930 Principal::Local,
931 )
932 .await?;
933
934 let peer = answer_payload.transaction.signer();
935 match self
936 .transport
937 .accept_remote_connection(peer, msg, expected, None)
938 .await?
939 {
940 InitiatorReplyOutcome::Completed => Ok(None),
941 InitiatorReplyOutcome::Continue {
942 attempt,
943 offer: next_offer,
944 } => {
945 let payload = self
946 .transport
947 .settle_handshake_step(
948 attempt,
949 "wrapping continuation connection offer",
950 self.transport.application_egress().originate(
951 Message::ConnectNodeSend(next_offer.clone()),
952 peer,
953 Some(self.did()),
954 ),
955 )
956 .await?;
957 if let Err(error) =
958 self.transport
959 .mark_offer_sent(attempt, &next_offer, payload.transaction.tx_id)
960 {
961 return Err(self
962 .transport
963 .classify_step_failure(
964 attempt,
965 error,
966 "marking continuation connection offer sent",
967 )
968 .await?);
969 }
970 Ok(Some(payload))
971 }
972 }
973 }
974
975 /// Verify a remote connection answer payload and apply it to the pending handshake, returning
976 /// `Ok(())` once the handshake completes.
977 pub async fn accept_answer(&self, answer_payload: MessagePayload) -> Result<()> {
978 self.accept_answer_with(None, answer_payload).await
979 }
980
981 /// Accept the answer of remote connection for the generation `attempt` reserved by
982 /// [`Swarm::offer_connection`]; refused as `ConnectionAttemptSuperseded` when the peer's slot
983 /// now holds another generation, so the answer is never applied to a handshake the peer
984 /// started.
985 pub async fn accept_answer_for(
986 &self,
987 attempt: ConnectionAttempt,
988 answer_payload: MessagePayload,
989 ) -> Result<()> {
990 self.accept_answer_with(Some(attempt.0), answer_payload)
991 .await
992 }
993
994 /// Verify the answer payload and apply it to the pending generation, or to `expected` only.
995 /// Carried out of band, the answer opens a replay stream on this node's local share.
996 async fn accept_answer_with(
997 &self,
998 expected: Option<PendingConnectionAttempt>,
999 answer_payload: MessagePayload,
1000 ) -> Result<()> {
1001 if !answer_payload
1002 .verify_transaction_and_payload_at(self.network_id(), self.transport.now_ms())
1003 {
1004 return Err(Error::VerifySignatureFailed);
1005 }
1006
1007 let Message::ConnectNodeReport(ref msg) = answer_payload.transaction.data()? else {
1008 return Err(Error::InvalidMessage(
1009 "Should be ConnectNodeReport".to_string(),
1010 ));
1011 };
1012 if answer_payload.transaction.destination != self.did() {
1013 return Err(Error::InvalidMessage(
1014 "ConnectNodeReport destination does not match this node".to_string(),
1015 ));
1016 }
1017 if !msg.final_step {
1018 return Err(Error::InvalidMessage(
1019 "out-of-band accept_answer requires a final ConnectNodeReport; use accept_answer_step"
1020 .to_string(),
1021 ));
1022 }
1023 self.transport
1024 .admit_final_transaction(
1025 &answer_payload.transaction,
1026 MessageCategory::DhtControl.into(),
1027 Principal::Local,
1028 )
1029 .await?;
1030
1031 let peer = answer_payload.transaction.signer();
1032 match self
1033 .transport
1034 .accept_remote_connection(peer, msg, expected, None)
1035 .await?
1036 {
1037 InitiatorReplyOutcome::Completed => Ok(()),
1038 InitiatorReplyOutcome::Continue { .. } => Err(Error::InvalidMessage(
1039 "out-of-band accept_answer received non-final multi-step ConnectNodeReport"
1040 .to_string(),
1041 )),
1042 }
1043 }
1044}
1045
1046/// Proof token returned by [`Swarm::prepare_delegatee_key_rotation`] after validating account DID,
1047/// delegator signature, and strict signing-horizon monotonicity (#1291).
1048///
1049/// Holds rotation exclusion across Phase 1 -> durable persistence -> [`Self::commit`], so neither
1050/// [`Swarm::set_delegatee_key`] nor another [`Swarm::prepare_delegatee_key_rotation`] can interleave
1051/// and regress the signing horizon before Phase 2 commits.
1052#[must_use = "dropping SwarmRotationCommit without calling .commit() discards the prepared key rotation"]
1053pub struct SwarmRotationCommit<'a> {
1054 swarm: &'a Swarm,
1055 _rotation_guard: std::sync::MutexGuard<'a, ()>,
1056 next_key: DelegateeKey,
1057}
1058
1059impl SwarmRotationCommit<'_> {
1060 /// Infallibly install the pre-validated [`DelegateeKey`] into the bound [`Swarm`].
1061 pub fn commit(self) {
1062 self.swarm
1063 .transport
1064 .commit_delegatee_key_unchecked(self.next_key);
1065 }
1066}