Skip to main content

ton_connect_core/
http_bridge.rs

1//! Runtime-neutral HTTP bridge endpoint and SSE framing primitives.
2
3use std::{fmt, mem, num::NonZeroU32, num::NonZeroUsize};
4
5use base64::{Engine as _, engine::general_purpose::STANDARD};
6use serde::{Deserialize, Deserializer, Serialize, Serializer, de, de::DeserializeOwned};
7use thiserror::Error;
8use url::Url;
9
10use crate::{
11    AppRequest, Base64Value, BridgeMessage, ClientId, KnownAppRequest, RpcError, SessionCrypto,
12    SessionCryptoError, TraceId, ValueError,
13};
14
15/// Heartbeat representation requested from the bridge SSE endpoint.
16#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
17pub enum HeartbeatMode {
18    /// Legacy named SSE event, also used when the query parameter is omitted.
19    #[default]
20    Legacy,
21    /// Standard `message` event whose data is the literal `heartbeat`.
22    Message,
23}
24
25impl HeartbeatMode {
26    const fn as_str(self) -> &'static str {
27        match self {
28            Self::Legacy => "legacy",
29            Self::Message => "message",
30        }
31    }
32}
33
34/// Validated base URL of a TON Connect HTTP bridge.
35///
36/// Published bridges require HTTPS. Plain HTTP is accepted only for an
37/// explicit loopback host so local conformance tests do not weaken production
38/// transport policy.
39#[derive(Clone, Eq, PartialEq)]
40pub struct HttpBridgeUrl(Url);
41
42impl HttpBridgeUrl {
43    /// Returns the validated bridge base URL.
44    #[must_use]
45    pub fn as_str(&self) -> &str {
46        self.0.as_str()
47    }
48
49    /// Builds the bridge SSE endpoint without discarding a base-path segment.
50    #[must_use]
51    pub fn events_endpoint(
52        &self,
53        client_id: ClientId,
54        last_event_id: Option<&str>,
55        trace_id: Option<&TraceId>,
56    ) -> Url {
57        self.events_endpoint_with_heartbeat(
58            client_id,
59            last_event_id,
60            trace_id,
61            HeartbeatMode::Message,
62        )
63    }
64
65    /// Builds the bridge SSE endpoint with an explicit heartbeat wire format.
66    #[must_use]
67    pub fn events_endpoint_with_heartbeat(
68        &self,
69        client_id: ClientId,
70        last_event_id: Option<&str>,
71        trace_id: Option<&TraceId>,
72        heartbeat: HeartbeatMode,
73    ) -> Url {
74        self.events_endpoint_for_ids(&client_id.to_string(), last_event_id, trace_id, heartbeat)
75    }
76
77    /// Builds one SSE endpoint subscribing to multiple bridge client IDs.
78    pub fn events_endpoint_many(
79        &self,
80        client_ids: &[ClientId],
81        last_event_id: Option<&str>,
82        trace_id: Option<&TraceId>,
83    ) -> Result<Url, HttpBridgeError> {
84        if client_ids.is_empty() {
85            return Err(HttpBridgeError::EmptySubscription);
86        }
87        let client_ids = client_ids
88            .iter()
89            .map(ToString::to_string)
90            .collect::<Vec<_>>()
91            .join(",");
92        Ok(self.events_endpoint_for_ids(
93            &client_ids,
94            last_event_id,
95            trace_id,
96            HeartbeatMode::Message,
97        ))
98    }
99
100    /// Builds a multi-client SSE endpoint with an explicit heartbeat format.
101    pub fn events_endpoint_many_with_heartbeat(
102        &self,
103        client_ids: &[ClientId],
104        last_event_id: Option<&str>,
105        trace_id: Option<&TraceId>,
106        heartbeat: HeartbeatMode,
107    ) -> Result<Url, HttpBridgeError> {
108        if client_ids.is_empty() {
109            return Err(HttpBridgeError::EmptySubscription);
110        }
111        let client_ids = client_ids
112            .iter()
113            .map(ToString::to_string)
114            .collect::<Vec<_>>()
115            .join(",");
116        Ok(self.events_endpoint_for_ids(&client_ids, last_event_id, trace_id, heartbeat))
117    }
118
119    fn events_endpoint_for_ids(
120        &self,
121        client_ids: &str,
122        last_event_id: Option<&str>,
123        trace_id: Option<&TraceId>,
124        heartbeat: HeartbeatMode,
125    ) -> Url {
126        let mut endpoint = self.endpoint("events");
127        {
128            let mut query = endpoint.query_pairs_mut();
129            let _ = query.append_pair("client_id", client_ids);
130            if let Some(last_event_id) = last_event_id {
131                let _ = query.append_pair("last_event_id", last_event_id);
132            }
133            if let Some(trace_id) = trace_id {
134                let _ = query.append_pair("trace_id", trace_id.as_str());
135            }
136            let _ = query.append_pair("heartbeat", heartbeat.as_str());
137        }
138        endpoint
139    }
140
141    /// Builds the bridge send endpoint for one encrypted message.
142    #[must_use]
143    pub fn message_endpoint(
144        &self,
145        sender: ClientId,
146        recipient: ClientId,
147        ttl: NonZeroU32,
148        topic: Option<&str>,
149        trace_id: Option<&TraceId>,
150    ) -> Url {
151        let mut endpoint = self.endpoint("message");
152        let sender = sender.to_string();
153        let recipient = recipient.to_string();
154        let ttl = ttl.to_string();
155        {
156            let mut query = endpoint.query_pairs_mut();
157            let _ = query
158                .append_pair("client_id", &sender)
159                .append_pair("to", &recipient)
160                .append_pair("ttl", &ttl);
161            if let Some(topic) = topic {
162                let _ = query.append_pair("topic", topic);
163            }
164            if let Some(trace_id) = trace_id {
165                let _ = query.append_pair("trace_id", trace_id.as_str());
166            }
167        }
168        endpoint
169    }
170
171    /// Encrypts and serializes one plaintext protocol value into a complete
172    /// runtime-neutral `POST /message` operation.
173    pub fn prepare_post<T: Serialize>(
174        &self,
175        crypto: &SessionCrypto,
176        recipient: ClientId,
177        ttl: NonZeroU32,
178        topic: Option<&str>,
179        trace_id: Option<&TraceId>,
180        payload: &T,
181    ) -> Result<PreparedBridgePost, BridgeCodecError> {
182        let plaintext = serde_json::to_vec(payload).map_err(BridgeCodecError::Json)?;
183        let encrypted = crypto.encrypt(recipient, &plaintext)?;
184        let body = Base64Value::try_from(STANDARD.encode(encrypted))?;
185        Ok(PreparedBridgePost {
186            url: self.message_endpoint(crypto.client_id(), recipient, ttl, topic, trace_id),
187            body,
188        })
189    }
190
191    /// Encodes an RPC request and derives the bridge push topic from its method.
192    ///
193    /// This prevents a caller from accidentally publishing a topic that differs
194    /// from the encrypted request and causes an incorrect push notification.
195    pub fn prepare_app_request_post(
196        &self,
197        crypto: &SessionCrypto,
198        recipient: ClientId,
199        ttl: NonZeroU32,
200        trace_id: Option<&TraceId>,
201        request: &KnownAppRequest,
202    ) -> Result<PreparedBridgePost, BridgeCodecError> {
203        let method = request.method();
204        let envelope = AppRequest::encode(request.clone())?;
205        self.prepare_post(
206            crypto,
207            recipient,
208            ttl,
209            Some(method.as_str()),
210            trace_id,
211            &envelope,
212        )
213    }
214
215    fn endpoint(&self, suffix: &str) -> Url {
216        let mut endpoint = self.0.clone();
217        let mut path = endpoint.path().trim_end_matches('/').to_owned();
218        path.push('/');
219        path.push_str(suffix);
220        endpoint.set_path(&path);
221        endpoint
222    }
223}
224
225/// Fully prepared body and URL for one HTTP bridge `POST /message` call.
226#[derive(Clone, Debug, Eq, PartialEq)]
227pub struct PreparedBridgePost {
228    url: Url,
229    body: Base64Value,
230}
231
232impl PreparedBridgePost {
233    /// Returns the URL that must receive an HTTP `POST`.
234    #[must_use]
235    pub const fn url(&self) -> &Url {
236        &self.url
237    }
238
239    /// Returns the raw base64 request body, without a JSON envelope.
240    #[must_use]
241    pub const fn body(&self) -> &Base64Value {
242        &self.body
243    }
244}
245
246impl fmt::Debug for HttpBridgeUrl {
247    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
248        formatter
249            .debug_tuple("HttpBridgeUrl")
250            .field(&self.0)
251            .finish()
252    }
253}
254
255impl fmt::Display for HttpBridgeUrl {
256    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
257        formatter.write_str(self.as_str())
258    }
259}
260
261impl Serialize for HttpBridgeUrl {
262    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
263    where
264        S: Serializer,
265    {
266        serializer.serialize_str(self.as_str())
267    }
268}
269
270impl<'de> Deserialize<'de> for HttpBridgeUrl {
271    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
272    where
273        D: Deserializer<'de>,
274    {
275        let value = String::deserialize(deserializer)?;
276        Self::try_from(value.as_str()).map_err(de::Error::custom)
277    }
278}
279
280impl TryFrom<&str> for HttpBridgeUrl {
281    type Error = HttpBridgeError;
282
283    fn try_from(value: &str) -> Result<Self, Self::Error> {
284        let parsed = Url::parse(value).map_err(|_| HttpBridgeError::InvalidUrl)?;
285        let secure = parsed.scheme() == "https" && parsed.has_host();
286        let loopback = parsed.scheme() == "http"
287            && parsed.host().is_some_and(|host| match host {
288                url::Host::Domain(domain) => domain.eq_ignore_ascii_case("localhost"),
289                url::Host::Ipv4(address) => address.is_loopback(),
290                url::Host::Ipv6(address) => address.is_loopback(),
291            });
292        if (!secure && !loopback) || parsed.query().is_some() || parsed.fragment().is_some() {
293            return Err(HttpBridgeError::InvalidUrl);
294        }
295        Ok(Self(parsed))
296    }
297}
298
299/// One decoded bridge message together with its SSE resume cursor.
300#[derive(Clone, Debug, Eq, PartialEq)]
301pub struct BridgeSseMessage {
302    event_id: Option<String>,
303    message: BridgeMessage,
304}
305
306impl BridgeSseMessage {
307    /// Returns the cursor to pass as `last_event_id` after reconnecting.
308    #[must_use]
309    pub fn event_id(&self) -> Option<&str> {
310        self.event_id.as_deref()
311    }
312
313    /// Returns the validated encrypted bridge envelope.
314    #[must_use]
315    pub const fn message(&self) -> &BridgeMessage {
316        &self.message
317    }
318
319    /// Consumes the SSE wrapper and returns the bridge envelope.
320    #[must_use]
321    pub fn into_message(self) -> BridgeMessage {
322        self.message
323    }
324
325    /// Authenticates, decrypts, and parses this SSE message for the fixed peer.
326    ///
327    /// Checking `expected_peer` before decryption is important when one SSE
328    /// connection subscribes to several local client IDs: ciphertext from an
329    /// unrelated session must never reach that session's request reducer.
330    pub fn decrypt<T: DeserializeOwned>(
331        &self,
332        crypto: &SessionCrypto,
333        expected_peer: ClientId,
334    ) -> Result<T, BridgeCodecError> {
335        if self.message.from() != expected_peer {
336            return Err(BridgeCodecError::UnexpectedPeer);
337        }
338        let encrypted = self.message.message().decode()?;
339        let plaintext = crypto.decrypt(expected_peer, &encrypted)?;
340        serde_json::from_slice(&plaintext).map_err(BridgeCodecError::Json)
341    }
342}
343
344/// Failure while encoding or decoding an end-to-end encrypted bridge value.
345#[derive(Debug, Error)]
346pub enum BridgeCodecError {
347    /// The bridge envelope came from a client other than the session peer.
348    #[error("bridge message sender does not match the TON Connect session peer")]
349    UnexpectedPeer,
350    /// Plaintext JSON could not be encoded or decoded as the requested type.
351    #[error("invalid TON Connect bridge plaintext: {0}")]
352    Json(serde_json::Error),
353    /// A typed RPC request could not be encoded into its bridge envelope.
354    #[error(transparent)]
355    Rpc(#[from] RpcError),
356    /// Base64 wire data is malformed.
357    #[error(transparent)]
358    InvalidBase64(#[from] ValueError),
359    /// Authenticated session encryption or decryption failed.
360    #[error(transparent)]
361    Crypto(#[from] SessionCryptoError),
362}
363
364/// Incremental decoder for the `text/event-stream` returned by `/events`.
365///
366/// The decoder accepts arbitrarily split network chunks, tolerates comments,
367/// legacy heartbeat events, and the `heartbeat=message` payload. A strict size
368/// bound prevents an untrusted bridge from growing the pending event forever.
369#[derive(Debug)]
370pub struct BridgeSseDecoder {
371    pending: Vec<u8>,
372    event_type: Option<String>,
373    data_lines: Vec<String>,
374    last_event_id: Option<String>,
375    current_event_bytes: usize,
376    max_event_bytes: NonZeroUsize,
377}
378
379impl BridgeSseDecoder {
380    /// Creates a decoder with an explicit maximum size for one SSE event.
381    #[must_use]
382    pub const fn new(max_event_bytes: NonZeroUsize) -> Self {
383        Self {
384            pending: Vec::new(),
385            event_type: None,
386            data_lines: Vec::new(),
387            last_event_id: None,
388            current_event_bytes: 0,
389            max_event_bytes,
390        }
391    }
392
393    /// Appends one transport chunk and returns every complete bridge message.
394    pub fn push(&mut self, chunk: &[u8]) -> Result<Vec<BridgeSseMessage>, HttpBridgeError> {
395        self.pending.extend_from_slice(chunk);
396        let mut messages = Vec::new();
397
398        while let Some(newline) = self.pending.iter().position(|byte| *byte == b'\n') {
399            let mut line = self.pending.drain(..=newline).collect::<Vec<_>>();
400            if line.last() == Some(&b'\n') {
401                let _ = line.pop();
402            }
403            if line.last() == Some(&b'\r') {
404                let _ = line.pop();
405            }
406            self.current_event_bytes = self
407                .current_event_bytes
408                .saturating_add(line.len())
409                .saturating_add(1);
410            // Bytes after this newline can belong to later events already
411            // buffered in the same network chunk, so only charge this line to
412            // the current event. The remaining partial line is checked below.
413            self.ensure_size_bound(0)?;
414
415            let line = String::from_utf8(line).map_err(|_| HttpBridgeError::InvalidSseUtf8)?;
416            if line.is_empty() {
417                if let Some(message) = self.dispatch()? {
418                    messages.push(message);
419                }
420                self.current_event_bytes = 0;
421            } else {
422                self.process_line(&line);
423            }
424        }
425
426        self.ensure_size_bound(self.pending.len())?;
427        Ok(messages)
428    }
429
430    fn ensure_size_bound(&self, pending_bytes: usize) -> Result<(), HttpBridgeError> {
431        if self.current_event_bytes.saturating_add(pending_bytes) > self.max_event_bytes.get() {
432            Err(HttpBridgeError::EventTooLarge)
433        } else {
434            Ok(())
435        }
436    }
437
438    fn process_line(&mut self, line: &str) {
439        if line.starts_with(':') {
440            return;
441        }
442        let (field, value) = line.split_once(':').map_or((line, ""), |(field, value)| {
443            (field, value.strip_prefix(' ').unwrap_or(value))
444        });
445        match field {
446            "event" => self.event_type = Some(value.to_owned()),
447            "data" => self.data_lines.push(value.to_owned()),
448            "id" if !value.contains('\0') => self.last_event_id = Some(value.to_owned()),
449            _ => {}
450        }
451    }
452
453    fn dispatch(&mut self) -> Result<Option<BridgeSseMessage>, HttpBridgeError> {
454        let event_type = self
455            .event_type
456            .take()
457            .unwrap_or_else(|| "message".to_owned());
458        let data = mem::take(&mut self.data_lines).join("\n");
459        if event_type == "heartbeat" || data.is_empty() || data == "heartbeat" {
460            return Ok(None);
461        }
462        if event_type != "message" {
463            return Ok(None);
464        }
465        let message = serde_json::from_str(&data).map_err(HttpBridgeError::InvalidMessage)?;
466        Ok(Some(BridgeSseMessage {
467            event_id: self.last_event_id.clone(),
468            message,
469        }))
470    }
471}
472
473/// Invalid bridge configuration or untrusted SSE input.
474#[derive(Debug, Error)]
475pub enum HttpBridgeError {
476    /// The bridge base is not an absolute HTTP(S) URL without query or fragment.
477    #[error("bridge URL must be an HTTPS base (or loopback HTTP) without query or fragment")]
478    InvalidUrl,
479    /// A bridge event subscription contained no client IDs.
480    #[error("bridge event subscription must contain at least one client id")]
481    EmptySubscription,
482    /// A pending SSE event exceeded the configured memory bound.
483    #[error("bridge SSE event exceeded the configured size limit")]
484    EventTooLarge,
485    /// An SSE field was not valid UTF-8.
486    #[error("bridge SSE stream contains invalid UTF-8")]
487    InvalidSseUtf8,
488    /// An SSE message event did not contain a valid bridge envelope.
489    #[error("invalid bridge message in SSE event: {0}")]
490    InvalidMessage(serde_json::Error),
491}
492
493#[cfg(test)]
494mod tests {
495    use std::{error::Error, num::NonZeroUsize};
496
497    use super::*;
498    use crate::{AppRequest, SessionCrypto};
499
500    const CLIENT: &str = "0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef";
501
502    #[test]
503    fn endpoints_preserve_the_published_base_path() -> Result<(), Box<dyn Error>> {
504        let bridge = HttpBridgeUrl::try_from("https://bridge.example/ton/bridge/")?;
505        let client = CLIENT.parse()?;
506        let event = bridge.events_endpoint(client, Some("41"), None);
507        assert_eq!(event.path(), "/ton/bridge/events");
508        assert_eq!(
509            event.query(),
510            Some(concat!(
511                "client_id=0123456789abcdef0123456789abcdef",
512                "0123456789abcdef0123456789abcdef&last_event_id=41&heartbeat=message"
513            ))
514        );
515        let legacy =
516            bridge.events_endpoint_with_heartbeat(client, None, None, HeartbeatMode::Legacy);
517        assert!(legacy.as_str().contains("heartbeat=legacy"));
518
519        let ttl = NonZeroU32::new(300).ok_or("TTL must be non-zero")?;
520        let message = bridge.message_endpoint(client, client, ttl, Some("disconnect"), None);
521        assert_eq!(message.path(), "/ton/bridge/message");
522        assert!(message.as_str().contains("topic=disconnect"));
523        Ok(())
524    }
525
526    #[test]
527    fn bridge_transport_requires_https_except_for_explicit_loopback() {
528        assert!(HttpBridgeUrl::try_from("https://bridge.example/bridge").is_ok());
529        assert!(HttpBridgeUrl::try_from("http://127.0.0.1:8080/bridge").is_ok());
530        assert!(HttpBridgeUrl::try_from("http://localhost:8080/bridge").is_ok());
531        assert!(HttpBridgeUrl::try_from("http://bridge.example/bridge").is_err());
532    }
533
534    #[test]
535    fn event_endpoint_supports_multiple_client_queues() -> Result<(), Box<dyn Error>> {
536        let bridge = HttpBridgeUrl::try_from("https://bridge.example/bridge")?;
537        assert_eq!(bridge.to_string(), "https://bridge.example/bridge");
538        assert!(format!("{bridge:?}").contains("bridge.example"));
539        let first = ClientId::from_bytes([1_u8; 32]);
540        let second = ClientId::from_bytes([2_u8; 32]);
541        let endpoint = bridge.events_endpoint_many(&[first, second], None, None)?;
542        let client_ids = endpoint
543            .query_pairs()
544            .find_map(|(name, value)| (name == "client_id").then(|| value.into_owned()));
545
546        assert_eq!(client_ids, Some(format!("{first},{second}")));
547        let legacy = bridge.events_endpoint_many_with_heartbeat(
548            &[first, second],
549            Some("8"),
550            None,
551            HeartbeatMode::Legacy,
552        )?;
553        assert!(legacy.as_str().contains("last_event_id=8"));
554        assert!(legacy.as_str().contains("heartbeat=legacy"));
555        assert!(matches!(
556            bridge.events_endpoint_many(&[], None, None),
557            Err(HttpBridgeError::EmptySubscription)
558        ));
559        assert!(matches!(
560            bridge.events_endpoint_many_with_heartbeat(&[], None, None, HeartbeatMode::Message),
561            Err(HttpBridgeError::EmptySubscription)
562        ));
563        Ok(())
564    }
565
566    #[test]
567    fn decoder_handles_byte_splits_crlf_and_both_heartbeats() -> Result<(), Box<dyn Error>> {
568        let input = concat!(
569            "event: heartbeat\r\n\r\n",
570            "event: message\n",
571            "data: heartbeat\n\n",
572            "id: 42\n",
573            "event: message\n",
574            "data: {\"from\":\"0123456789abcdef0123456789abcdef",
575            "0123456789abcdef0123456789abcdef\",\"message\":\"AA==\"}\n\n"
576        );
577        let limit = NonZeroUsize::new(4096).ok_or("limit must be non-zero")?;
578        let mut decoder = BridgeSseDecoder::new(limit);
579        let mut messages = Vec::new();
580        for chunk in input.as_bytes().chunks(1) {
581            messages.extend(decoder.push(chunk)?);
582        }
583
584        assert_eq!(messages.len(), 1);
585        assert_eq!(
586            messages.first().and_then(BridgeSseMessage::event_id),
587            Some("42")
588        );
589        assert_eq!(
590            messages
591                .first()
592                .map(BridgeSseMessage::message)
593                .map(BridgeMessage::from),
594            Some(CLIENT.parse()?)
595        );
596        Ok(())
597    }
598
599    #[test]
600    fn decoder_rejects_an_unbounded_event_before_dispatch() -> Result<(), Box<dyn Error>> {
601        let limit = NonZeroUsize::new(16).ok_or("limit must be non-zero")?;
602        let mut decoder = BridgeSseDecoder::new(limit);
603        assert!(matches!(
604            decoder.push(b"data: 01234567890123456789"),
605            Err(HttpBridgeError::EventTooLarge)
606        ));
607        Ok(())
608    }
609
610    #[test]
611    fn decoder_applies_the_limit_per_event_not_per_network_chunk() -> Result<(), Box<dyn Error>> {
612        let limit = NonZeroUsize::new(32).ok_or("limit must be non-zero")?;
613        let mut decoder = BridgeSseDecoder::new(limit);
614        let heartbeats = "event: heartbeat\n\n".repeat(100);
615        assert!(decoder.push(heartbeats.as_bytes()).is_ok());
616        Ok(())
617    }
618
619    #[test]
620    fn encrypted_request_round_trips_through_the_sse_envelope() -> Result<(), Box<dyn Error>> {
621        let dapp = SessionCrypto::generate()?;
622        let wallet = SessionCrypto::generate()?;
623        let request = AppRequest {
624            method: "disconnect".to_owned(),
625            params: Vec::new(),
626            id: "7".to_owned(),
627        };
628        let bridge = HttpBridgeUrl::try_from("https://bridge.example/bridge")?;
629        let ttl = NonZeroU32::new(300).ok_or("TTL must be non-zero")?;
630        let known = request.clone().decode()?;
631        let post = bridge.prepare_app_request_post(&dapp, wallet.client_id(), ttl, None, &known)?;
632        let envelope = serde_json::json!({
633            "from": dapp.client_id().to_string(),
634            "message": post.body().as_str()
635        });
636        let stream = format!("id: 9\ndata: {envelope}\n\n");
637        let limit = NonZeroUsize::new(4096).ok_or("limit must be non-zero")?;
638        let mut decoder = BridgeSseDecoder::new(limit);
639        let messages = decoder.push(stream.as_bytes())?;
640        let message = messages.first().ok_or("message must be decoded")?;
641        let decrypted = message.decrypt::<AppRequest>(&wallet, dapp.client_id())?;
642
643        assert_eq!(decrypted, request);
644        assert_eq!(message.event_id(), Some("9"));
645        assert_eq!(message.clone().into_message(), *message.message());
646        assert!(post.url().as_str().contains("topic=disconnect"));
647        assert!(matches!(
648            message.decrypt::<AppRequest>(&wallet, ClientId::from_bytes([9_u8; 32])),
649            Err(BridgeCodecError::UnexpectedPeer)
650        ));
651        Ok(())
652    }
653}