Skip to main content

rings_node/processor/
handshake.rs

1//! Handshakes of the processor: a connect by DID over the overlay, and a handshake over a peer's
2//! public HTTP API.
3
4use std::str::FromStr;
5
6use rings_core::dht::Did;
7use rings_core::error::Error as CoreError;
8use rings_core::message::Decoder;
9use rings_core::message::Encoded;
10use rings_core::message::Encoder;
11use rings_core::message::Message;
12use rings_core::message::MessagePayload;
13use rings_core::message::PeerWireVersion;
14use rings_core::swarm::ConnectionAttempt;
15use rings_rpc::protos::rings_node::AcceptAnswerRequest;
16use rings_rpc::protos::rings_node::AnswerOfferRequest;
17use rings_rpc::protos::rings_node::NodeDidRequest;
18use rings_rpc::protos::rings_node::NodeDidResponse;
19
20use super::Processor;
21use crate::error::Error;
22use crate::error::Result;
23use crate::remote_endpoint::remote_rpc_client;
24use crate::remote_endpoint::RemoteRpcEndpoint;
25/// Which node a handshake over HTTP must end up connected to.
26#[derive(Clone, Copy, Debug, Eq, PartialEq)]
27pub(crate) enum HandshakePeer {
28    /// Whatever DID the endpoint answers as.
29    Any,
30    /// Only this DID; any other answer is refused before an offer is created.
31    Pinned(Did),
32}
33
34/// The remote half of a handshake over HTTP: the peer's public `nodeDid` and `answerOffer`, and
35/// its `acceptAnswer` for a counter-offer this node answered, which only a peer of 0.34.2 or
36/// earlier sends.
37#[cfg_attr(rings_browser, async_trait::async_trait(?Send))]
38#[cfg_attr(rings_native, async_trait::async_trait)]
39pub(crate) trait RemoteHandshake {
40    /// The peer's public identity and wire version.
41    async fn node_did(&self) -> Result<NodeDidResponse>;
42
43    /// The peer's reply to `offer`: an answer, or its own prevailing offer (#947).
44    async fn answer_offer(&self, offer: &MessagePayload) -> Result<MessagePayload>;
45
46    /// Deliver `answer` to the peer's own offer.
47    async fn accept_answer(&self, answer: &MessagePayload) -> Result<()>;
48}
49
50#[cfg_attr(rings_browser, async_trait::async_trait(?Send))]
51#[cfg_attr(rings_native, async_trait::async_trait)]
52impl RemoteHandshake for rings_rpc::jsonrpc::Client {
53    async fn node_did(&self) -> Result<NodeDidResponse> {
54        rings_rpc::jsonrpc::Client::node_did(self, &NodeDidRequest {})
55            .await
56            .map_err(Error::from)
57    }
58
59    async fn answer_offer(&self, offer: &MessagePayload) -> Result<MessagePayload> {
60        let offer = offer.encode().map_err(|_| Error::EncodeError)?;
61        let reply = rings_rpc::jsonrpc::Client::answer_offer(self, &AnswerOfferRequest {
62            offer: offer.to_string(),
63        })
64        .await
65        .map_err(Error::from)?
66        .answer;
67        decode_handshake_payload(&Encoded::from(reply))
68    }
69
70    async fn accept_answer(&self, answer: &MessagePayload) -> Result<()> {
71        let answer = answer.encode().map_err(|_| Error::EncodeError)?;
72        rings_rpc::jsonrpc::Client::accept_answer(self, &AcceptAnswerRequest {
73            answer: answer.to_string(),
74        })
75        .await
76        .map_err(Error::from)?;
77        Ok(())
78    }
79}
80
81/// Whether the payload returned by `answerOffer` is an answer (`ConnectNodeReport`) or a
82/// counter-offer (`ConnectNodeSend`).
83#[derive(Clone, Copy, Debug, Eq, PartialEq)]
84pub enum OfferReplyKind {
85    /// A `ConnectNodeReport` answer for the offerer's `acceptAnswer`.
86    Answer,
87    /// A `ConnectNodeSend` counter-offer: the peer's own offer prevailed on the DID tie-break
88    /// (#947).
89    CounterOffer,
90}
91
92impl OfferReplyKind {
93    /// Classify a decoded handshake reply [`MessagePayload`].
94    pub(crate) fn from_payload(payload: &MessagePayload) -> Result<Self> {
95        match payload
96            .transaction
97            .data::<Message>()
98            .map_err(|_| Error::DecodeError)?
99        {
100            Message::ConnectNodeReport(_) => Ok(Self::Answer),
101            Message::ConnectNodeSend(_) => Ok(Self::CounterOffer),
102            _ => Err(Error::DecodeError),
103        }
104    }
105
106    /// Decode and classify an encoded `answerOffer` reply string.
107    pub fn from_encoded_reply(reply: &str) -> Result<Self> {
108        decode_handshake_payload(&Encoded::from(reply.to_owned()))
109            .and_then(|payload| Self::from_payload(&payload))
110    }
111}
112
113/// Decode an offer or an answer from its HTTP handshake string. A frame of another wire version
114/// is refused as [`Error::IncompatibleWireVersion`] (#1104); any other failure is
115/// [`Error::DecodeError`].
116pub(crate) fn decode_handshake_payload(encoded: &Encoded) -> Result<MessagePayload> {
117    MessagePayload::from_encoded(encoded)
118        .map_err(|error| Error::from_core_or(error, |_| Error::DecodeError))
119}
120
121/// Admit the wire version an endpoint's `nodeDid` reported before any offer is created
122/// (#1104): `Ok` iff it is this node's, and otherwise [`Error::IncompatibleWireVersion`]. An
123/// endpoint that reports none is a node before wire versioning.
124pub(crate) fn admit_endpoint_wire_version(reported: Option<u16>) -> Result<()> {
125    PeerWireVersion::reported(reported)
126        .admit()
127        .map_err(Error::IncompatibleWireVersion)
128}
129
130/// How an HTTP handshake exchange ended without failing.
131enum HttpExchange {
132    /// The peer answered and the answer was accepted for this node's generation.
133    Accepted,
134    /// The peer's own offer prevailed and was answered: the edge is the peer's handshake.
135    PeerHandshake,
136}
137
138/// Why a handshake over HTTP did not reach an accepted answer.
139#[derive(Debug)]
140pub(crate) enum HandshakeFailure {
141    /// The peer's slot is owned by another attempt (a handshake in flight, whichever side
142    /// started it): refused before any request when the local core already holds an unadmitted
143    /// handshake, or by the local core during the exchange. Nothing is wrong; a later attempt may
144    /// succeed.
145    InFlight {
146        /// The peer whose slot is owned.
147        peer: Did,
148    },
149    /// The handshake failed.
150    Failed(Error),
151}
152
153impl HandshakeFailure {
154    /// Whether `error` is a core refusal because another attempt owns the peer's slot: an offer
155    /// refused because the peer already holds a record, or an attempt superseded by the peer's
156    /// own offer (#947). `is_concurrent(e) ⟺ from_stage(p, s, e) = InFlight { p }`.
157    pub(crate) const fn is_concurrent(error: &CoreError) -> bool {
158        matches!(
159            error,
160            CoreError::AlreadyConnected | CoreError::ConnectionAttemptSuperseded { .. }
161        )
162    }
163
164    /// Sort a core refusal of one handshake stage: a concurrent refusal
165    /// ([`Self::is_concurrent`]) is `InFlight`; any other error is `Failed` under the stage's
166    /// wrapper.
167    fn from_stage(peer: Did, stage: fn(CoreError) -> Error, error: CoreError) -> Self {
168        if Self::is_concurrent(&error) {
169            Self::InFlight { peer }
170        } else {
171            Self::Failed(stage(error))
172        }
173    }
174}
175
176impl From<Error> for HandshakeFailure {
177    /// Every error that is not a core refusal of a handshake stage is a failure.
178    fn from(error: Error) -> Self {
179        Self::Failed(error)
180    }
181}
182
183impl From<HandshakeFailure> for Error {
184    /// A refusal is reported as `HandshakeInFlight`; a failure as itself.
185    fn from(failure: HandshakeFailure) -> Self {
186        match failure {
187            HandshakeFailure::InFlight { peer } => Error::HandshakeInFlight { peer },
188            HandshakeFailure::Failed(error) => error,
189        }
190    }
191}
192
193impl Processor {
194    /// Connect peer with web3 did.
195    /// There are 3 peers: PeerA, PeerB, PeerC.
196    /// 1. PeerA has a connection with PeerB.
197    /// 2. PeerC has a connection with PeerB.
198    /// 3. PeerC can connect PeerA with PeerA's web3 address.
199    ///
200    /// This operation is idempotent: if topology convergence already produced
201    /// the direct connection, the requested connection is satisfied.
202    pub async fn connect_with_did(&self, did: Did) -> Result<()> {
203        match self.swarm.connect(did).await {
204            Ok(()) | Err(rings_core::error::Error::AlreadyConnected) => Ok(()),
205            Err(error) => Err(Error::ConnectError(error)),
206        }
207    }
208
209    /// Handshake with the node behind `endpoint` over its public HTTP API: learn its DID, and
210    /// when `peer` is pinned refuse before any request if the local core already holds an
211    /// unadmitted handshake to it, and before any offer if the endpoint answers as another
212    /// node; then create, exchange and accept the offer. Returns the generation the offer
213    /// reserved once the answer is accepted; admission of the resulting transport completes
214    /// asynchronously and reaches the [`Backend`](crate::extension::Backend) as an item of the
215    /// core's `ApplicationInbox`. The answer is pinned to that
216    /// generation, so it is never applied to a handshake the peer started meanwhile; a failure
217    /// after the offer was created cancels the generation iff it is still pending.
218    ///
219    /// This node's offer, carried out of band, prevails over the peer's own sent overlay offer
220    /// to this node (`Law (Tie-break)`), so the peer answers it. A peer of 0.34.2 or earlier
221    /// replies instead with its overlay offer when that offer prevails on the DID tie-break
222    /// (#947). This node then answers it, which releases its own losing generation, and
223    /// delivers the answer with the peer's `acceptAnswer`; the edge is the peer's handshake,
224    /// still in flight, so the outcome is `InFlight`, and nothing is abandoned.
225    pub(crate) async fn connect_peer_via_http(
226        &self,
227        endpoint: &RemoteRpcEndpoint,
228        api_token: Option<&str>,
229        peer: HandshakePeer,
230    ) -> std::result::Result<ConnectionAttempt, HandshakeFailure> {
231        self.refuse_if_unadmitted(peer)?;
232        let client = remote_rpc_client(endpoint, api_token, self.remote_rpc_proxy.as_ref()).await?;
233        let attempt = self.connect_peer_over(&client, peer).await;
234        if let Err(HandshakeFailure::Failed(Error::HandshakePeerMismatch { expected, actual })) =
235            attempt.as_ref()
236        {
237            tracing::error!(
238                %endpoint,
239                %expected,
240                %actual,
241                "endpoint answered as another node; handshake refused"
242            );
243        }
244        attempt
245    }
246
247    /// Handshake with `remote`: refuse before any request when `peer` is pinned and the local
248    /// core already holds an unadmitted handshake to it, verify `nodeDid`'s wire version and
249    /// pinned DID before creating an offer, and complete [`Self::exchange_offer`].
250    pub(crate) async fn connect_peer_over(
251        &self,
252        remote: &impl RemoteHandshake,
253        peer: HandshakePeer,
254    ) -> std::result::Result<ConnectionAttempt, HandshakeFailure> {
255        self.refuse_if_unadmitted(peer)?;
256        let node = remote.node_did().await?;
257        admit_endpoint_wire_version(node.wire_version)?;
258        let answered = node.did;
259        let actual = Did::from_str(answered.as_str()).map_err(|_| Error::InvalidDid(answered))?;
260        if let HandshakePeer::Pinned(expected) = peer {
261            if actual != expected {
262                return Err(HandshakeFailure::Failed(Error::HandshakePeerMismatch {
263                    expected,
264                    actual,
265                }));
266            }
267        }
268        self.exchange_offer(remote, actual).await
269    }
270
271    /// Refuse with [`HandshakeFailure::InFlight`] when `peer` is pinned and the local core
272    /// already holds an unadmitted handshake to it.
273    fn refuse_if_unadmitted(
274        &self,
275        peer: HandshakePeer,
276    ) -> std::result::Result<(), HandshakeFailure> {
277        if let HandshakePeer::Pinned(pinned) = peer {
278            if self
279                .swarm
280                .has_unadmitted_connection(pinned)
281                .map_err(Error::ConnectError)?
282            {
283                return Err(HandshakeFailure::InFlight { peer: pinned });
284            }
285        }
286        Ok(())
287    }
288
289    /// Create an offer for `peer`, exchange it with `remote`, and complete the handshake; see
290    /// [`Self::connect_peer_via_http`].
291    pub(crate) async fn exchange_offer(
292        &self,
293        remote: &impl RemoteHandshake,
294        peer: Did,
295    ) -> std::result::Result<ConnectionAttempt, HandshakeFailure> {
296        let (attempt, maybe_offer) = self
297            .swarm
298            .offer_connection_step(peer)
299            .await
300            .map_err(|error| HandshakeFailure::from_stage(peer, Error::CreateOffer, error))?;
301        let Some(offer) = maybe_offer else {
302            // 0-step transport completed locally with no outbound signaling message.
303            return Ok(attempt);
304        };
305        if offer
306            .transaction
307            .data::<Message>()
308            .ok()
309            .is_some_and(|m| matches!(m, Message::ConnectNodeSend(ref s) if s.final_step))
310        {
311            self.swarm.abandon_connection_attempt(attempt).await;
312            return Err(HandshakeFailure::from_stage(
313                peer,
314                Error::CreateOffer,
315                CoreError::Transport(rings_transport::error::Error::UnsupportedOperation(
316                    "HTTP answerOffer/acceptAnswer requires a 2-step offer/answer handshake"
317                        .to_string(),
318                )),
319            ));
320        }
321        let exchange = async {
322            let reply = remote.answer_offer(&offer).await?;
323            if OfferReplyKind::from_payload(&reply)? == OfferReplyKind::CounterOffer {
324                self.answer_counter_offer(remote, peer, reply).await?;
325                return Ok(HttpExchange::PeerHandshake);
326            }
327            self.swarm
328                .accept_answer_for(attempt, reply)
329                .await
330                .map_err(|error| HandshakeFailure::from_stage(peer, Error::AcceptAnswer, error))
331                .map(|()| HttpExchange::Accepted)
332        };
333        match exchange.await {
334            Ok(HttpExchange::Accepted) => Ok(attempt),
335            Ok(HttpExchange::PeerHandshake) => Err(HandshakeFailure::InFlight { peer }),
336            Err(failure) => {
337                self.abandon_handshake(attempt).await;
338                Err(failure)
339            }
340        }
341    }
342
343    /// Answer the peer's prevailing `counter_offer` (#947) and deliver the answer with the
344    /// peer's `acceptAnswer`. Answering releases this node's own losing generation.
345    async fn answer_counter_offer(
346        &self,
347        remote: &impl RemoteHandshake,
348        peer: Did,
349        counter_offer: MessagePayload,
350    ) -> std::result::Result<(), HandshakeFailure> {
351        let answer = self
352            .swarm
353            .answer_offer(counter_offer)
354            .await
355            .map_err(|error| HandshakeFailure::from_stage(peer, Error::AnswerOffer, error))?
356            .answer()
357            .ok_or(HandshakeFailure::InFlight { peer })?;
358        remote.accept_answer(&answer).await?;
359        Ok(())
360    }
361
362    /// Cancel the generation `attempt` reserved iff it is still pending, that is, no data
363    /// channel has opened on it; one admitting, admitted or superseded meanwhile is left alone,
364    /// and a failure to cancel is logged since the core expires an unadmitted attempt on its
365    /// own.
366    pub(crate) async fn abandon_handshake(&self, attempt: ConnectionAttempt) {
367        if let Err(error) = self.swarm.cancel_pending_connection_attempt(attempt).await {
368            tracing::warn!(?attempt, %error, "failed to cancel the abandoned handshake");
369        }
370    }
371
372    /// Whether a seed document owes `peer` a dial: it is not this node and its admission was
373    /// not announced. A peer with a handshake in flight is dialed and refused by the core,
374    /// which `connect seed` reads as the peer being taken care of.
375    pub(crate) fn owes_seed_dial(&self, peer: Did) -> Result<bool> {
376        Ok(peer != self.swarm.did() && !self.swarm.is_peer_admitted(peer)?)
377    }
378}