Skip to main content

Swarm

Struct Swarm 

Source
pub struct Swarm { /* private fields */ }
Expand description

The transport and dht management.

Implementations§

Source§

impl Swarm

Source

pub fn scoped_storage(&self, stop: StopToken) -> ScopedStorage<'_>

The DHT operations of this swarm, whose rerouting waits end once stop is requested.

Source§

impl Swarm

Source

pub fn did(&self) -> Did

Get did of self.

Source

pub fn delegator_pubkey(&self) -> Result<PublicKey<33>, Error>

Get the local account public key used for E2E public-key negotiation.

Source

pub fn delegator_verification_pubkey( &self, ) -> Result<VerificationPublicKey, Error>

Get the typed account verification public key.

Source

pub fn delegatee_key(&self) -> DelegateeKey

Return the session key this swarm currently signs with.

Source

pub fn set_delegatee_key( &self, delegatee_key: DelegateeKey, ) -> Result<(), Error>

Replace the session key this swarm signs with, when it authorizes the same account DID.

Source

pub fn prepare_delegatee_key_rotation( &self, delegatee_key: &DelegateeKey, ) -> Result<SwarmRotationCommit<'_>, Error>

Non-mutating validation phase of two-phase session-key rotation (#1291): verify that delegatee_key authorizes this node’s account DID, carries a valid delegator signature, and strictly advances the signing horizon relative to the currently committed key while holding rotation exclusion until SwarmRotationCommit::commit (or drop) completes.

Source

pub fn network_id(&self) -> u32

Get this swarm’s network id.

Source

pub fn clock(&self) -> &Arc<dyn Clock> ⓘ

Return the SharedClock capability bound to this swarm.

Source

pub fn rng(&self) -> &SharedRng

Return the SharedRng capability bound to this swarm.

Source

pub fn storage_redundancy(&self) -> u16

Get the storage redundancy for this swarm’s DHT protocol mode.

Source

pub fn storage_fetch_mark(&self) -> StorageFetchMark

The mark a fetcher reads before storage_fetch, to learn from Self::storage_fetch_answered_since when its fetch was answered.

Source

pub fn storage_fetch_answered_since( &self, entry_key: Did, mark: StorageFetchMark, ) -> Result<bool, Error>

Whether storage_fetch of entry_key cached a found entry the cache then serves, locally or from a reply, after mark was read. A fetch of the key that starts meanwhile does not reset it. A late reply to an earlier fetch also counts, and the entry it caches is still a reply received after the mark.

This is the fetch’s reply marker. A reader cannot tell a reply by comparing cached values, since a cached value is projected at the clock of each read and changes, with no reply, when one of its elements crosses its horizon.

Post: false once no fetch of entry_key is retained.

Source

pub fn dht_virtual_nodes(&self) -> u16

Get the storage virtual-node positions for this swarm’s DHT protocol mode.

Source

pub fn dht_protocol_mode(&self) -> DhtProtocolMode

Get this swarm’s full DHT protocol mode descriptor.

Source

pub fn dht(&self) -> Arc<PeerRing> ⓘ

Get DHT(Distributed Hash Table) of self.

Source

pub fn transport(&self) -> &Arc<dyn DynTransportInterface + Sync + Send> ⓘ

Return the injected trait-based SharedTransport backing this swarm.

Source

pub fn admitted_edges(&self) -> usize

How many edges this node has admitted now: peers admitted and not retired (edges).

Source

pub fn edges_changed(&self) -> EdgesChanged ⓘ

Resolves at the next admission or retirement of an edge after this call (edges).

Source

pub fn application_inbox(&self) -> Result<ApplicationInbox, Error>

Claim the application inbox: everything core hands the application, in order (#935).

Claimed once; a second claim is refused as ApplicationInboxClaimed. Until it is claimed, application data addressed to this node is discarded and peer facts are kept; once it is dropped, everything is discarded. Core never waits on the reader except for room on the application data lanes.

Source

pub fn set_admission_delegation( &self, namespace_prefix: Vec<u8>, limit: MessageLimit, )

Record the message limit of application payloads starting with namespace_prefix: MessageLimit::Delegated to the namespace, or MessageLimit::Enforced by core.

The application registers its namespaces in advance and core matches the prefix on its admission path, without calling the application. The match is exact when the application’s namespace encoding is prefix-free. Delegation is trusted local configuration: a delegating namespace must enforce its own per-neighbour admission.

Source

pub fn set_replay_delegation( &self, namespace_prefix: Vec<u8>, window: ReplayWindow, )

Record the replay window of application payloads starting with namespace_prefix, from the authenticated neighbour that originated them: ReplayWindow::Link, a volatile window of the link they arrived on, or ReplayWindow::Durable (#1081).

Registered in advance and matched by core on its admission path, as Self::set_admission_delegation is. Delegated replay is trusted local configuration: a declaring namespace must act on each of its payloads at most once by its own replay key (Obligation R of durable-records).

Source

pub fn delegates_admission(&self, application_payload: &[u8]) -> bool

Whether an application payload belongs to a namespace registered as delegating through Swarm::set_admission_delegation.

Source

pub fn delegates_replay(&self, application_payload: &[u8]) -> bool

Whether an application payload belongs to a namespace registered as delegating its replay through Swarm::set_replay_delegation.

Source

pub fn stabilizer(&self) -> Stabilizer

Create Stabilizer for swarm; its inbox-delivery intent is interpreted here, toward the application inbox.

Source

pub async fn disconnect(&self, peer: Did) -> Result<(), Error>

Disconnect a connection. There are three steps:

  1. remove from DHT;
  2. remove from Transport;
  3. close the connection;
Source

pub async fn leave(&self) -> Result<(), Error>

Best-effort voluntary departure (#1057): hand off live relay carriers to remaining members through the ack-gated hand-off and send Leave { successor_list } to this node’s predecessor and successor head before transports close.

Source

pub async fn close(&self) -> Result<(), Error>

Close this swarm: it opens no connection from now on, and every connection it has, admitted or still handshaking, is disconnected and physically closed before this returns (the close law of SwarmTransport::close, #1098).

Each peer sees its connection close at once, as on Self::disconnect, instead of waiting for an ICE timeout. Call it before dropping a swarm that stops in a process that goes on: dropping it frees the swarm (#1093), but a peer connection that was never closed keeps its sockets bound. A closed swarm refuses every new connection with Error::SwarmClosed; closing again is a no-op.

Source

pub async fn connect(&self, peer: Did) -> Result<(), Error>

Start a non-routable handshake with a peer.

The peer becomes visible through the connection inspection APIs only after its data channel opens and the swarm admits it to the DHT.

Source

pub async fn send_message( &self, data: ApplicationData, destination: Did, ) -> Result<Uuid, Error>

Send application data to destination, routed by Chord.

Only ApplicationData crosses the boundary outbound, as inbound: an application cannot originate core’s own protocol messages. data is sent as Message::from(data), which the receiving core projects back to data (project ∘ from = Some).

Source

pub async fn send_direct_message( &self, data: ApplicationData, destination: Did, ) -> Result<Uuid, Error>

Send application data directly to an already connected peer, without a Chord lookup.

This preserves an application protocol’s explicit next-hop selection. Callers must ensure the destination has an active direct transport connection.

Source

pub fn peers(&self) -> Vec<ConnectionInspect>

List active, routable peers and their connection status.

The status is the connection’s raw WebRTC state. A peer is routable once its data channel is open in Connecting or Connected, so a listed peer may still read Connecting: a browser can open the data channel before it reports connected.

Source

pub fn peer_dids(&self) -> Vec<Did>

List DIDs with active, routable transport connections.

Source

pub fn has_unadmitted_connection(&self, peer: Did) -> Result<bool, Error>

Whether the transport holds an unadmitted handshake to peer (pending or admitting), whichever side started it. A new offer to such a peer is refused as AlreadyConnected while the handshake is inside the pending timeout; a stale one is expired by the reservation instead.

Source

pub fn is_peer_admitted(&self, peer: Did) -> Result<bool, Error>

Whether peer is admitted: its connection record is active. Ready or recovering, its transport is the swarm’s to heal or retire. Law: an admission is announced as SwarmEvent::PeerAdmitted in the transition that activates the record, so is_peer_admitted(p) ⟹ that admission was announced and the record’s retirement will be, as SwarmEvent::PeerRetired.

Source

pub fn application_credit(&self, peer: Did) -> Option<LaneCreditView>

A read-only view of the send credit of the Application lane of peer’s sendable connection generation, or None without one (#913). Application data travels on that lane, so an application that shapes its own emission paces it on this view: the view reserves nothing and holds the connection weakly, so reading it never changes what core may send.

Source

pub fn connection_registry_capacity(&self) -> Result<usize, Error>

𝓡, the capacity of the connection registry (#723): the most connection records, in any phase, the swarm holds at once, 2 × (finger slots + successors + 1). It bounds the admitted peers, so an application keying state by admitted link can size it by 𝓡.

Source

pub async fn cancel_pending_connection_attempt( &self, attempt: ConnectionAttempt, ) -> Result<bool, Error>

Cancel the handshake attempt iff it is still pending, that is, no data channel has opened on it; one that is admitting, admitted or superseded meanwhile is left alone. Returns whether it was cancelled.

Source

pub async fn abandon_connection_attempt(&self, attempt: ConnectionAttempt)

Unconditionally abandon connection generation attempt when its outbound handshake step was never transmitted to the remote peer, retiring Pending, Admitting, and prematurely Active generations of attempt while leaving any peer-superseded generation untouched.

Source

pub async fn lookup_successor(&self, key: Did) -> Result<SuccessorLookup, Error>

Take the local step of a successor lookup for key, and route the lookup when the local topology cannot decide it.

Law: in a ring every present node is the successor of its own identifier, so a lookup for key answers key exactly when key is in the overlay, as far as the answering node’s successor list is current. The local step decides Local(head) when key lies in the local successor interval (n, head], and Local(n) when this node has no successor; otherwise the request FindSuccessorSend { did: key, strict: false } is sent to the hop that same step chose, never to key itself even when key is a direct peer (key would answer with its own successor), and the answer, a FindSuccessorReport under the request’s transaction, resolves the returned SuccessorReport. The handle is registered before the request is sent, so its report always finds it; dropping it withdraws the lookup. The step and the hop come from one topology snapshot.

Source

pub async fn peer_measurement(&self, peer: Did) -> Option<PeerMeasurement>

Return local measurement counters for peer, if observed.

Source

pub async fn peer_measurements(&self) -> Vec<PeerMeasurement>

Return every retained local peer measurement.

Source

pub async fn peer_measurements_page( &self, after: Option<Did>, limit: NonZero<usize>, ) -> PeerMeasurementPage

Return one bounded page of retained local peer measurements.

Source

pub async fn inspect(&self) -> SwarmInspect

Check the status of swarm

Source

pub async fn mailbox_storage_inspect( &self, ) -> Result<MailboxStorageInspect, Error>

Return aggregate live relay-inbox state without identifiers or payloads.

Source

pub fn transaction_replay_counters(&self) -> ReplayCounters

Return destination-scoped transaction replay counters.

Source

pub fn origin_quota_counters(&self) -> OriginQuotaCounters

Return aggregate final-destination origin-quota drop counters by logical lane and reason.

Source§

impl Swarm

Source

pub async fn create_offer(&self, peer: Did) -> Result<MessagePayload, Error>

Create an outbound transport connection offer for peer, wrapped in a signed MessagePayload.

Source

pub async fn offer_connection_step( &self, peer: Did, ) -> Result<(ConnectionAttempt, Option<MessagePayload>), Error>

Reserve an out-of-band connection generation for peer and execute step 0 of its handshake, returning (attempt, None) when a 0-step transport completes locally without emitting any signaling message, or (attempt, Some(payload)) when an outbound step 0 ConnectNodeSend payload is produced (#1291).

Source

pub async fn offer_connection( &self, peer: Did, ) -> Result<(ConnectionAttempt, MessagePayload), Error>

Reserve a connection generation for peer and create its 2-step out-of-band offer, returning the attempt that names the generation so the caller can accept the answer for it or cancel it without touching a handshake the peer started meanwhile.

The caller owns the offer and carries it out of band, so the attempt never sends it over the DHT as a counter-offer (#947). It prevails over a crossing overlay offer, which is refused; of a crossing out-of-band offer, one from a larger DID is refused and one from a smaller DID takes the slot (Law (Tie-break)). Transports that complete in 0 or 1 steps return rings_transport::error::Error::UnsupportedOperation here (use Self::offer_connection_step or Self::connect).

Source

pub async fn answer_offer_step( &self, offer_payload: MessagePayload, ) -> Result<OfferReply<Option<MessagePayload>, MessagePayload>, Error>

Verify and apply an out-of-band ConnectNodeSend handshake step, returning OfferReply::Answer(None) when a final inbound step completes the handshake without an outbound reply, OfferReply::Answer(Some(payload)) when a reply ConnectNodeReport is produced, or OfferReply::CounterOffer(payload) when this node’s prevailing offer wins.

Source

pub async fn answer_offer( &self, offer_payload: MessagePayload, ) -> Result<OfferReply<MessagePayload, MessagePayload>, Error>

Answer the offer of remote connection. This function will verify the answer payload and will wrap the answer inside a payload with verification.

The offer is carried out of band, so it prevails over this node’s own sent overlay offer to the same peer, which is released (Law (Tie-break)), and the reply is OfferReply::Answer, a final ConnectNodeReport for the peer’s accept_answer: a counter-offer would leave the peer to deliver its answer through this node’s accept_answer, which a node’s public HTTP API does not serve. Nodes of 0.34.2 and earlier reply with OfferReply::CounterOffer when their sent overlay offer prevails on the DID tie-break (#947): that offer, a ConnectNodeSend, which the caller hands to the peer’s answer_offer; the peer abandons its own offer and answers this one, and that answer goes to the replying node’s accept_answer. Crossing no edge, the offer opens a replay stream on this node’s local share.

Source

pub async fn accept_answer_step( &self, answer_payload: MessagePayload, ) -> Result<Option<MessagePayload>, Error>

Verify a remote ConnectNodeReport handshake step and apply it to the pending initiator handshake (#1291), returning Ok(None) when a final report completes the handshake or Ok(Some(payload)) containing the next signed even ConnectNodeSend continuation step for >= 3-step out-of-band handshakes.

Source

pub async fn accept_answer_step_for( &self, attempt: ConnectionAttempt, answer_payload: MessagePayload, ) -> Result<Option<MessagePayload>, Error>

Verify a remote ConnectNodeReport handshake step and apply it to the exact initiator generation attempt reserved by Swarm::offer_connection_step (#1291), returning Ok(None) when a final report completes the handshake or Ok(Some(payload)) containing the next signed even ConnectNodeSend continuation step.

Source

pub async fn accept_answer( &self, answer_payload: MessagePayload, ) -> Result<(), Error>

Verify a remote connection answer payload and apply it to the pending handshake, returning Ok(()) once the handshake completes.

Source

pub async fn accept_answer_for( &self, attempt: ConnectionAttempt, answer_payload: MessagePayload, ) -> Result<(), Error>

Accept the answer of remote connection for the generation attempt reserved by Swarm::offer_connection; refused as ConnectionAttemptSuperseded when the peer’s slot now holds another generation, so the answer is never applied to a handshake the peer started.

Trait Implementations§

Source§

impl ChordStorageInterface for Swarm

Source§

fn storage_fetch<'life0, 'async_trait>( &'life0 self, entry_key: Did, ) -> Pin<Box<dyn Future<Output = Result<(), Error>> + Send + 'async_trait>>
where 'life0: 'async_trait, Swarm: 'async_trait,

ScopedStorage::storage_fetch under a stop that never fires.

Source§

fn storage_store<'life0, 'async_trait>( &'life0 self, entry: Entry, ) -> Pin<Box<dyn Future<Output = Result<(), Error>> + Send + 'async_trait>>
where 'life0: 'async_trait, Swarm: 'async_trait,

ScopedStorage::storage_store under a stop that never fires.

Source§

fn storage_append_data<'life0, 'life1, 'async_trait>( &'life0 self, topic: &'life1 str, data: Bytes, ) -> Pin<Box<dyn Future<Output = Result<(), Error>> + Send + 'async_trait>>
where 'life0: 'async_trait, 'life1: 'async_trait, Swarm: 'async_trait,

ScopedStorage::storage_append_data under a stop that never fires.

Source§

fn storage_extend<'life0, 'life1, 'async_trait>( &'life0 self, topic: &'life1 str, data: Vec<Bytes>, lifetime_ms: u64, ) -> Pin<Box<dyn Future<Output = Result<(), Error>> + Send + 'async_trait>>
where 'life0: 'async_trait, 'life1: 'async_trait, Swarm: 'async_trait,

ScopedStorage::storage_extend under a stop that never fires.

Source§

fn storage_tombstone_data<'life0, 'life1, 'async_trait>( &'life0 self, topic: &'life1 str, data: Bytes, ) -> Pin<Box<dyn Future<Output = Result<(), Error>> + Send + 'async_trait>>
where 'life0: 'async_trait, 'life1: 'async_trait, Swarm: 'async_trait,

ScopedStorage::storage_tombstone_data under a stop that never fires.

Source§

impl ChordStorageInterfaceCacheChecker for Swarm

Source§

fn storage_check_cache<'life0, 'async_trait>( &'life0 self, entry_key: Did, ) -> Pin<Box<dyn Future<Output = Option<Entry>> + Send + 'async_trait>>
where 'life0: 'async_trait, Swarm: 'async_trait,

Check local cache

Auto Trait Implementations§

§

impl !RefUnwindSafe for Swarm

§

impl !UnwindSafe for Swarm

§

impl Forget for Swarm

§

impl Freeze for Swarm

§

impl Move for Swarm

§

impl Send for Swarm

§

impl Sync for Swarm

§

impl Unpin for Swarm

§

impl UnsafeUnpin for Swarm

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> ArchivePointee for T

Source§

type ArchivedMetadata = ()

The archived version of the pointer metadata for this type.
Source§

fn pointer_metadata( _: &<T as ArchivePointee>::ArchivedMetadata, ) -> <T as Pointee>::Metadata

Converts some archived metadata to the pointer metadata for itself.
Source§

impl<'a, T, E> AsTaggedExplicit<'a, E> for T
where T: 'a,

Source§

fn explicit(self, class: Class, tag: u32) -> TaggedParser<'a, Explicit, Self, E>

Source§

impl<'a, T, E> AsTaggedImplicit<'a, E> for T
where T: 'a,

Source§

fn implicit( self, class: Class, constructed: bool, tag: u32, ) -> TaggedParser<'a, Implicit, Self, E>

Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> ErasedDestructor for T
where T: 'static,

Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<A, B, T> HttpServerConnExec<A, B> for T
where B: Body,

Source§

impl<T> Instrument for T

Source§

fn instrument(self, span: Span) -> Instrumented<Self> ⓘ

Instruments this type with the provided Span, returning an Instrumented wrapper. Read more
Source§

fn in_current_span(self) -> Instrumented<Self> ⓘ

Instruments this type with the current Span, returning an Instrumented wrapper. Read more
Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T> IntoEither for T

Source§

fn into_either(self, into_left: bool) -> Either<Self, Self> ⓘ

Converts self into a Left variant of Either<Self, Self> if into_left is true. Converts self into a Right variant of Either<Self, Self> otherwise. Read more
Source§

fn into_either_with<F>(self, into_left: F) -> Either<Self, Self> ⓘ
where F: FnOnce(&Self) -> bool,

Converts self into a Left variant of Either<Self, Self> if into_left(&self) returns true. Converts self into a Right variant of Either<Self, Self> otherwise. Read more
Source§

impl<T> LayoutRaw for T

Source§

fn layout_raw(_: <T as Pointee>::Metadata) -> Result<Layout, LayoutError>

Returns the layout of the type.
Source§

impl<T> MaybeSend for T
where T: Send + ?Sized,

Source§

impl<T> MaybeSendSync for T
where T: Send + Sync + ?Sized,

Source§

impl<T, N1, N2> Niching<NichedOption<T, N1>> for N2
where T: SharedNiching<N1, N2>, N1: Niching<T>, N2: Niching<T>,

Source§

unsafe fn is_niched(niched: *const NichedOption<T, N1>) -> bool

Returns whether the given value has been niched. Read more
Source§

fn resolve_niched(out: Place<NichedOption<T, N1>>)

Writes data to out indicating that a T is niched.
Source§

impl<T> Pointee for T

Source§

type Metadata = ()

The metadata type for pointers and references to this type.
Source§

impl<T> PolicyExt for T
where T: ?Sized,

Source§

fn and<P, B, E>(self, other: P) -> And<T, P>
where T: Sized + Policy<B, E>, P: Policy<B, E>,

Create a new Policy that returns Action::Follow only if self and other return Action::Follow. Read more
Source§

fn or<P, B, E>(self, other: P) -> Or<T, P>
where T: Sized + Policy<B, E>, P: Policy<B, E>,

Create a new Policy that returns Action::Follow if either self or other returns Action::Follow. Read more
Source§

impl<T> Same for T

Source§

type Output = T

Should always be Self
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = !

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, !>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
Source§

impl<V, T> VZip<V> for T
where V: MultiLane<T>,

Source§

fn vzip(self) -> V

Source§

impl<T> WithSubscriber for T

Source§

fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self> ⓘ
where S: Into<Dispatch>,

Attaches the provided Subscriber to this type, returning a WithDispatch wrapper. Read more
Source§

fn with_current_subscriber(self) -> WithDispatch<Self> ⓘ

Attaches the current default Subscriber to this type, returning a WithDispatch wrapper. Read more