tycho_network/util/
mod.rs1use bytes::Buf;
2
3pub use self::router::{Routable, Router, RouterBuilder};
4#[cfg(test)]
5pub use self::test::make_peer_info_stub;
6pub use self::traits::{NetworkExt, UnknownPeerError};
7use crate::types::PeerId;
8
9mod router;
10mod traits;
11
12#[cfg(test)]
13mod test;
14
15#[macro_export]
16macro_rules! match_tl_request {
17 ($req_body:expr, $(tag = $tag:expr,)? {
18 $($ty:path as $pat:pat => $expr:expr),*$(,)?
19 }, $err:pat => $err_exr:expr) => {
20 '__match_req: {
21 let $err = $crate::match_tl_request!(@inner $req_body, $($tag)?, {
22 $(
23 <$ty>::TL_ID => match $crate::__internal::tl_proto::deserialize::<$ty>(&($req_body)) {
24 Ok($pat) => break '__match_req ($expr),
25 Err(e) => e,
26 }
27 )*
28 _ => $crate::__internal::tl_proto::TlError::UnknownConstructor,
29 });
30 $err_exr
31 }
32 };
33
34 (@inner $req_body:expr, $tag:expr, $($rest:tt)*) => {
35 match $tag $($rest)*
36 };
37 (@inner $req_body:expr, , $($rest:tt)*) => {
38 if ($req_body).len() >= 4 {
39 match ($req_body).as_ref().get_u32_le() $($rest)*
40 } else {
41 $crate::__internal::tl_proto::TlError::UnexpectedEof
42 }
43 };
44}
45
46pub fn check_peer_signature<T>(peed_id: &PeerId, signature: &[u8; 64], data: &T) -> bool
47where
48 T: tl_proto::TlWrite,
49{
50 let Some(public_key) = peed_id.as_public_key() else {
51 return false;
52 };
53 public_key.verify_tl(data, signature)
54}
55
56pub fn try_handle_prefix<T>(req: &T) -> Result<(u32, &[u8]), tl_proto::TlError>
57where
58 T: AsRef<[u8]>,
59{
60 let body = req.as_ref();
61 if body.len() < 4 {
62 return Err(tl_proto::TlError::UnexpectedEof);
63 }
64
65 let constructor = std::convert::identity(body).get_u32_le();
66 Ok((constructor, body))
67}
68
69pub fn try_handle_prefix_with_offset<T>(req: &T) -> Result<(u32, &[u8]), tl_proto::TlError>
70where
71 T: AsRef<[u8]>,
72{
73 let body = req.as_ref();
74 if body.len() < 4 {
75 return Err(tl_proto::TlError::UnexpectedEof);
76 }
77
78 let constructor = std::convert::identity(body).get_u32_le();
79 Ok((constructor, &body[4..]))
80}