Skip to main content

rings_node/processor/
messaging.rs

1//! Messages a processor sends: plain and direct custom messages, extension envelopes, and the
2//! end-to-end encrypted handshake and stream.
3
4use rings_core::dht::Did;
5use rings_core::ecc::PublicKey;
6use rings_core::ecc::SecretKey;
7use rings_core::message::e2e;
8use rings_core::message::e2e::E2eHandshakeRequest;
9use rings_core::message::e2e::E2eHandshakeResponse;
10use rings_core::message::e2e::E2eStreamDecryptor;
11use rings_core::message::e2e::E2eStreamFrame;
12use rings_core::swarm::application::ApplicationData;
13
14use super::Processor;
15use crate::error::Error;
16use crate::error::Result;
17
18impl Processor {
19    /// Send custom message to a did.
20    pub async fn send_message(&self, destination: Did, msg: &[u8]) -> Result<uuid::Uuid> {
21        tracing::trace!(size = msg.len(), %destination, "send_message");
22
23        self.swarm
24            .send_message(ApplicationData::custom(msg), destination)
25            .await
26            .map_err(Error::SendMessage)
27    }
28
29    /// Send a custom message to an already connected peer without Chord routing.
30    ///
31    /// Protocols with their own authenticated hop selection, such as onion circuits, use this
32    /// to keep the core transport from replacing their selected next hop.
33    pub async fn send_direct_message(&self, destination: Did, msg: &[u8]) -> Result<uuid::Uuid> {
34        tracing::trace!(size = msg.len(), %destination, "send_direct_message");
35
36        self.swarm
37            .send_direct_message(ApplicationData::custom(msg), destination)
38            .await
39            .map_err(Error::SendMessage)
40    }
41
42    /// Send an E2E handshake request to a DID.
43    ///
44    /// The negotiated key is the peer's account/identity secp256k1 key, not
45    /// the ephemeral delegatee key.
46    pub async fn send_e2e_handshake(&self, destination: Did) -> Result<uuid::Uuid> {
47        let public_key = self.swarm.delegator_pubkey().map_err(Error::SendMessage)?;
48        self.swarm
49            .send_message(
50                ApplicationData::E2eHandshakeRequest(E2eHandshakeRequest::new(public_key)),
51                destination,
52            )
53            .await
54            .map_err(Error::SendMessage)
55    }
56
57    /// Send an ElGamal-encrypted E2E message to a DID with a verified recipient key.
58    ///
59    /// Returns the stream id shared by all emitted E2E stream frames.
60    pub async fn send_e2e_message(
61        &self,
62        destination: Did,
63        recipient_public_key: PublicKey<33>,
64        msg: &[u8],
65    ) -> Result<uuid::Uuid> {
66        self.send_e2e_message_with_frame_len(
67            destination,
68            recipient_public_key,
69            msg,
70            e2e::DEFAULT_E2E_PLAINTEXT_FRAME_LEN,
71        )
72        .await
73    }
74
75    /// Send an ElGamal-encrypted E2E stream with an explicit plaintext frame size.
76    ///
77    /// Returns the stream id shared by all emitted E2E stream frames.
78    pub async fn send_e2e_message_with_frame_len(
79        &self,
80        destination: Did,
81        recipient_public_key: PublicKey<33>,
82        msg: &[u8],
83        max_plaintext_frame_len: usize,
84    ) -> Result<uuid::Uuid> {
85        e2e::ensure_public_key_matches_did(recipient_public_key, destination)
86            .map_err(Error::SendMessage)?;
87        let sender_public_key = self.swarm.delegator_pubkey().map_err(Error::SendMessage)?;
88        let stream_id = self.rng().next_uuid();
89        let frames = e2e::encrypt_stream_frames_with_rng(
90            msg,
91            stream_id,
92            sender_public_key,
93            recipient_public_key,
94            max_plaintext_frame_len,
95            self.rng().clone(),
96        )
97        .map_err(Error::SendMessage)?
98        .collect::<rings_core::error::Result<Vec<_>>>()
99        .map_err(Error::SendMessage)?;
100
101        for frame in frames {
102            self.swarm
103                .send_message(ApplicationData::E2eStreamFrame(frame), destination)
104                .await
105                .map_err(Error::SendMessage)?;
106        }
107
108        Ok(stream_id)
109    }
110
111    /// Verify an E2E handshake request and return the requester's identity public key.
112    pub fn verify_e2e_handshake_request(
113        &self,
114        requester: Did,
115        request: &E2eHandshakeRequest,
116    ) -> Result<PublicKey<33>> {
117        request
118            .verify_requester(requester)
119            .map_err(Error::CoreError)?;
120        Ok(request.requester_public_key)
121    }
122
123    /// Verify an E2E handshake response and return the responder's identity public key.
124    pub fn verify_e2e_handshake_response(
125        &self,
126        responder: Did,
127        response: &E2eHandshakeResponse,
128    ) -> Result<PublicKey<33>> {
129        response
130            .verify_responder(responder)
131            .map_err(Error::CoreError)?;
132        Ok(response.responder_public_key)
133    }
134
135    /// Create an E2E stream decryptor with this node's identity/signing secret key; its stall
136    /// deadline runs from now.
137    ///
138    /// The ciphertext is encrypted to the DID/account key negotiated by the
139    /// handshake. A session private key cannot decrypt it unless the delegatee key
140    /// is also the account key, so callers must supply the local identity key
141    /// explicitly.
142    pub fn e2e_stream_decryptor(
143        &self,
144        expected_sender: Did,
145        stream_id: e2e::E2eStreamId,
146        recipient_identity_key: SecretKey,
147    ) -> Result<E2eStreamDecryptor> {
148        e2e::ensure_public_key_matches_did(recipient_identity_key.pubkey(), self.did())
149            .map_err(Error::CoreError)?;
150        Ok(E2eStreamDecryptor::new(
151            stream_id,
152            expected_sender,
153            recipient_identity_key,
154            self.clock().now_ms(),
155        ))
156    }
157
158    /// Decrypt one E2E stream frame arriving now with an already-created stream decryptor.
159    /// Fails with `E2eStreamStalled` once the stream has made no progress for its stall
160    /// deadline: a frame of it was lost.
161    pub fn decrypt_e2e_stream_frame(
162        &self,
163        decryptor: &mut E2eStreamDecryptor,
164        frame: &E2eStreamFrame,
165    ) -> Result<Vec<u8>> {
166        decryptor
167            .decrypt_next(frame, self.clock().now_ms())
168            .map_err(Error::CoreError)
169    }
170
171    /// Whether an E2E stream is still live now; poll it while no frame of the stream arrives,
172    /// so a lost frame (the final one included) is reported rather than waited for.
173    pub fn check_e2e_stream(&self, decryptor: &E2eStreamDecryptor) -> Result<()> {
174        decryptor
175            .check(self.clock().now_ms())
176            .map_err(Error::CoreError)
177    }
178
179    /// Send a namespaced [`Envelope`](crate::extension::ext::Envelope) to a did over the
180    /// P2P transport (the wire codec
181    /// of the extension layer). `send_envelope : (Did, Envelope) → IO TxId`.
182    pub async fn send_envelope(
183        &self,
184        destination: Did,
185        envelope: &crate::extension::ext::Envelope,
186    ) -> Result<uuid::Uuid> {
187        let msg_bytes = envelope.encode()?;
188        self.send_message(destination, &msg_bytes).await
189    }
190
191    /// Send a namespaced envelope directly to an already connected peer.
192    ///
193    /// This bypasses Chord routing while retaining the normal custom-message envelope codec.
194    pub async fn send_direct_envelope(
195        &self,
196        destination: Did,
197        envelope: &crate::extension::ext::Envelope,
198    ) -> Result<uuid::Uuid> {
199        let msg_bytes = envelope.encode()?;
200        self.send_direct_message(destination, &msg_bytes).await
201    }
202}