1use std::{
-22 fmt::{self, Display},
-23 net::{IpAddr, SocketAddr},
-24};
-25
-26use data_encoding::HEXLOWER;
-27use iroh_base::{EndpointId, PublicKey, RelayUrl};
-28use n0_error::{e, ensure, stack_error};
-29use rand::Rng;
-30use serde::{Deserialize, Serialize};
-31use url::Url;
-32
-33use crate::magicsock::transports;
-34
-35pub const MAGIC: &str = "TS💬"; pub const MAGIC_LEN: usize = MAGIC.len();
-39
-40const V0: u8 = 0;
-42
-43pub(crate) const KEY_LEN: usize = 32;
-44const TX_LEN: usize = 12;
-45
-46const HEADER_LEN: usize = 2;
-50
-51const PING_LEN: usize = TX_LEN + iroh_base::PublicKey::LENGTH;
-52const EP_LENGTH: usize = 16 + 2; #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
-55#[repr(u8)]
-56pub enum MessageType {
-57 Ping = 0x01,
-58 Pong = 0x02,
-59 CallMeMaybe = 0x03,
-60}
-61
-62impl TryFrom<u8> for MessageType {
-63 type Error = u8;
-64
-65 fn try_from(value: u8) -> std::result::Result<Self, Self::Error> {
-66 match value {
-67 0x01 => Ok(MessageType::Ping),
-68 0x02 => Ok(MessageType::Pong),
-69 0x03 => Ok(MessageType::CallMeMaybe),
-70 _ => Err(value),
-71 }
-72 }
-73}
-74
-75const MESSAGE_HEADER_LEN: usize = MAGIC_LEN + KEY_LEN;
-76
-77pub fn encode_message(sender: &PublicKey, seal: Vec<u8>) -> Vec<u8> {
-78 let mut out = Vec::with_capacity(MESSAGE_HEADER_LEN);
-79 out.extend_from_slice(MAGIC.as_bytes());
-80 out.extend_from_slice(sender.as_bytes());
-81 out.extend(seal);
-82
-83 out
-84}
-85
-86pub fn looks_like_disco_wrapper(p: &[u8]) -> bool {
-88 if p.len() < MESSAGE_HEADER_LEN {
-89 return false;
-90 }
-91
-92 &p[..MAGIC_LEN] == MAGIC.as_bytes()
-93}
-94
-95pub fn source_and_box(p: &[u8]) -> Option<(PublicKey, &[u8])> {
-98 if !looks_like_disco_wrapper(p) {
-99 return None;
-100 }
-101
-102 let source = &p[MAGIC_LEN..MAGIC_LEN + KEY_LEN];
-103 let sender = PublicKey::try_from(source).ok()?;
-104 let sealed_box = &p[MAGIC_LEN + KEY_LEN..];
-105 Some((sender, sealed_box))
-106}
-107
-108#[derive(Debug, Clone, PartialEq, Eq)]
-110pub enum Message {
-111 Ping(Ping),
-112 Pong(Pong),
-113 CallMeMaybe(CallMeMaybe),
-114}
-115
-116#[derive(Debug, Clone, PartialEq, Eq)]
-117pub struct Ping {
-118 pub tx_id: TransactionId,
-120
-121 pub endpoint_key: PublicKey,
-125}
-126
-127impl Ping {
-128 pub(crate) fn new(endpoint_id: EndpointId) -> Self {
-132 Self {
-133 tx_id: TransactionId::default(),
-134 endpoint_key: endpoint_id,
-135 }
-136 }
-137
-138 fn from_bytes(p: &[u8]) -> Result<Self, ParseError> {
-139 ensure!(p.len() >= PING_LEN, ParseError::TooShort);
-141 let tx_id: [u8; TX_LEN] = p[..TX_LEN].try_into().expect("length checked");
-142 let raw_key = &p[TX_LEN..TX_LEN + iroh_base::PublicKey::LENGTH];
-143 let endpoint_key =
-144 PublicKey::try_from(raw_key).map_err(|_| e!(ParseError::InvalidEncoding))?;
-145 let tx_id = TransactionId::from(tx_id);
-146
-147 Ok(Ping {
-148 tx_id,
-149 endpoint_key,
-150 })
-151 }
-152
-153 fn as_bytes(&self) -> Vec<u8> {
-154 let header = msg_header(MessageType::Ping, V0);
-155 let mut out = vec![0u8; PING_LEN + HEADER_LEN];
-156
-157 out[..HEADER_LEN].copy_from_slice(&header);
-158 out[HEADER_LEN..HEADER_LEN + TX_LEN].copy_from_slice(&self.tx_id);
-159 out[HEADER_LEN + TX_LEN..].copy_from_slice(self.endpoint_key.as_ref());
-160
-161 out
-162 }
-163}
-164
-165#[derive(Debug, Clone, PartialEq, Eq)]
-169pub struct Pong {
-170 pub tx_id: TransactionId,
-171 pub ping_observed_addr: SendAddr,
-175}
-176
-177#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
-179pub enum SendAddr {
-180 Udp(SocketAddr),
-182 Relay(RelayUrl),
-184}
-185
-186impl From<transports::Addr> for SendAddr {
-187 fn from(addr: transports::Addr) -> Self {
-188 match addr {
-189 transports::Addr::Ip(addr) => SendAddr::Udp(addr),
-190 transports::Addr::Relay(url, _) => SendAddr::Relay(url),
-191 }
-192 }
-193}
-194
-195impl From<SocketAddr> for SendAddr {
-196 fn from(source: SocketAddr) -> Self {
-197 SendAddr::Udp(source)
-198 }
-199}
-200
-201impl From<RelayUrl> for SendAddr {
-202 fn from(source: RelayUrl) -> Self {
-203 SendAddr::Relay(source)
-204 }
-205}
-206
-207impl PartialEq<SocketAddr> for SendAddr {
-208 fn eq(&self, other: &SocketAddr) -> bool {
-209 match self {
-210 Self::Relay(_) => false,
-211 Self::Udp(addr) => addr.eq(other),
-212 }
-213 }
-214}
-215
-216impl Display for SendAddr {
-217 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
-218 match self {
-219 SendAddr::Relay(id) => write!(f, "Relay({id})"),
-220 SendAddr::Udp(addr) => write!(f, "UDP({addr})"),
-221 }
-222 }
-223}
-224
-225#[derive(Debug, Clone, PartialEq, Eq)]
-234pub struct CallMeMaybe {
-235 pub my_numbers: Vec<SocketAddr>,
-237}
-238
-239#[allow(missing_docs)]
-240#[stack_error(derive, add_meta)]
-241#[non_exhaustive]
-242pub enum ParseError {
-243 #[error("message is too short")]
-244 TooShort,
-245 #[error("invalid encoding")]
-246 InvalidEncoding,
-247 #[error("unknown format")]
-248 UnknownFormat,
-249}
-250
-251fn send_addr_from_bytes(p: &[u8]) -> Result<SendAddr, ParseError> {
-252 ensure!(p.len() > 2, ParseError::TooShort);
-253 match p[0] {
-254 0u8 => {
-255 let bytes: [u8; EP_LENGTH] = p[1..].try_into().map_err(|_| e!(ParseError::TooShort))?;
-256 let addr = socket_addr_from_bytes(bytes);
-257 Ok(SendAddr::Udp(addr))
-258 }
-259 1u8 => {
-260 let s = std::str::from_utf8(&p[1..]).map_err(|_| e!(ParseError::InvalidEncoding))?;
-261 let u: Url = s.parse().map_err(|_| e!(ParseError::InvalidEncoding))?;
-262 Ok(SendAddr::Relay(u.into()))
-263 }
-264 _ => Err(e!(ParseError::UnknownFormat)),
-265 }
-266}
-267
-268fn send_addr_to_vec(addr: &SendAddr) -> Vec<u8> {
-269 match addr {
-270 SendAddr::Relay(url) => {
-271 let mut out = vec![1u8];
-272 out.extend_from_slice(url.to_string().as_bytes());
-273 out
-274 }
-275 SendAddr::Udp(ip) => {
-276 let mut out = vec![0u8];
-277 out.extend_from_slice(&socket_addr_as_bytes(ip));
-278 out
-279 }
-280 }
-281}
-282
-283fn socket_addr_from_bytes(p: [u8; EP_LENGTH]) -> SocketAddr {
-285 debug_assert_eq!(EP_LENGTH, 16 + 2);
-286
-287 let raw_src_ip: [u8; 16] = p[..16].try_into().expect("array long enough");
-288 let raw_port: [u8; 2] = p[16..].try_into().expect("array long enough");
-289
-290 let src_ip = IpAddr::from(raw_src_ip).to_canonical();
-291 let src_port = u16::from_le_bytes(raw_port);
-292
-293 SocketAddr::new(src_ip, src_port)
-294}
-295
-296fn socket_addr_as_bytes(addr: &SocketAddr) -> [u8; EP_LENGTH] {
-297 let mut out = [0u8; EP_LENGTH];
-298 let ipv6 = match addr.ip() {
-299 IpAddr::V4(v4) => v4.to_ipv6_mapped(),
-300 IpAddr::V6(v6) => v6,
-301 };
-302 out[..16].copy_from_slice(&ipv6.octets());
-303 out[16..].copy_from_slice(&addr.port().to_le_bytes());
-304
-305 out
-306}
-307
-308impl Pong {
-309 fn from_bytes(p: &[u8]) -> Result<Self, ParseError> {
-310 let tx_id: [u8; TX_LEN] = p[..TX_LEN]
-311 .try_into()
-312 .map_err(|_| e!(ParseError::TooShort))?;
-313
-314 let tx_id = TransactionId::from(tx_id);
-315 let src = send_addr_from_bytes(&p[TX_LEN..])?;
-316
-317 Ok(Pong {
-318 tx_id,
-319 ping_observed_addr: src,
-320 })
-321 }
-322
-323 fn as_bytes(&self) -> Vec<u8> {
-324 let header = msg_header(MessageType::Pong, V0);
-325 let mut out = header.to_vec();
-326 out.extend_from_slice(&self.tx_id);
-327
-328 let src_bytes = send_addr_to_vec(&self.ping_observed_addr);
-329 out.extend(src_bytes);
-330 out
-331 }
-332}
-333
-334impl CallMeMaybe {
-335 fn from_bytes(p: &[u8]) -> Result<Self, ParseError> {
-336 ensure!(p.len() % EP_LENGTH == 0, ParseError::InvalidEncoding);
-337
-338 let num_entries = p.len() / EP_LENGTH;
-339 let mut m = CallMeMaybe {
-340 my_numbers: Vec::with_capacity(num_entries),
-341 };
-342
-343 for chunk in p.chunks_exact(EP_LENGTH) {
-344 let bytes: [u8; EP_LENGTH] = chunk
-345 .try_into()
-346 .map_err(|_| e!(ParseError::InvalidEncoding))?;
-347 let src = socket_addr_from_bytes(bytes);
-348 m.my_numbers.push(src);
-349 }
-350
-351 Ok(m)
-352 }
-353
-354 fn as_bytes(&self) -> Vec<u8> {
-355 let header = msg_header(MessageType::CallMeMaybe, V0);
-356 let mut out = vec![0u8; HEADER_LEN + self.my_numbers.len() * EP_LENGTH];
-357 out[..HEADER_LEN].copy_from_slice(&header);
-358
-359 for (m, chunk) in self
-360 .my_numbers
-361 .iter()
-362 .zip(out[HEADER_LEN..].chunks_exact_mut(EP_LENGTH))
-363 {
-364 let raw = socket_addr_as_bytes(m);
-365 chunk.copy_from_slice(&raw);
-366 }
-367
-368 out
-369 }
-370}
-371
-372impl Message {
-373 pub fn from_bytes(p: &[u8]) -> Result<Self, ParseError> {
-375 ensure!(p.len() >= 2, ParseError::TooShort);
-376
-377 let t = MessageType::try_from(p[0]).map_err(|_| e!(ParseError::UnknownFormat))?;
-378 let version = p[1];
-379 ensure!(version == V0, ParseError::UnknownFormat);
-380
-381 let p = &p[2..];
-382 match t {
-383 MessageType::Ping => {
-384 let ping = Ping::from_bytes(p)?;
-385 Ok(Message::Ping(ping))
-386 }
-387 MessageType::Pong => {
-388 let pong = Pong::from_bytes(p)?;
-389 Ok(Message::Pong(pong))
-390 }
-391 MessageType::CallMeMaybe => {
-392 let cm = CallMeMaybe::from_bytes(p)?;
-393 Ok(Message::CallMeMaybe(cm))
-394 }
-395 }
-396 }
-397
-398 pub fn as_bytes(&self) -> Vec<u8> {
-400 match self {
-401 Message::Ping(ping) => ping.as_bytes(),
-402 Message::Pong(pong) => pong.as_bytes(),
-403 Message::CallMeMaybe(cm) => cm.as_bytes(),
-404 }
-405 }
-406}
-407
-408impl Display for Message {
-409 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
-410 match self {
-411 Message::Ping(ping) => {
-412 write!(f, "Ping(tx={})", HEXLOWER.encode(&ping.tx_id))
-413 }
-414 Message::Pong(pong) => {
-415 write!(f, "Pong(tx={})", HEXLOWER.encode(&pong.tx_id))
-416 }
-417 Message::CallMeMaybe(_) => {
-418 write!(f, "CallMeMaybe")
-419 }
-420 }
-421 }
-422}
-423
-424const fn msg_header(t: MessageType, ver: u8) -> [u8; HEADER_LEN] {
-425 [t as u8, ver]
-426}
-427
-428const TRANSACTION_ID_SIZE: usize = 12;
-429
-430#[derive(Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)]
-438pub(crate) struct TransactionId([u8; TRANSACTION_ID_SIZE]);
-439
-440impl fmt::Debug for TransactionId {
-441 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
-442 write!(f, "TransactionId(0x")?;
-443 fmt_transcation_id(self.as_ref(), f)
-444 }
-445}
-446
-447impl fmt::Display for TransactionId {
-448 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
-449 write!(f, "transaction id (0x")?;
-450 fmt_transcation_id(self.as_ref(), f)
-451 }
-452}
-453
-454fn fmt_transcation_id(bytes: &[u8], f: &mut fmt::Formatter) -> fmt::Result {
-455 for byte in bytes {
-456 write!(f, "{:02X}", byte)?;
-457 }
-458 write!(f, ")")
-459}
-460
-461impl std::ops::Deref for TransactionId {
-462 type Target = [u8];
-463
-464 fn deref(&self) -> &[u8] {
-465 &self.0
-466 }
-467}
-468
-469impl AsRef<[u8]> for TransactionId {
-470 fn as_ref(&self) -> &[u8] {
-471 &self.0[..]
-472 }
-473}
-474
-475impl From<&[u8; TRANSACTION_ID_SIZE]> for TransactionId {
-476 fn from(buff: &[u8; TRANSACTION_ID_SIZE]) -> Self {
-477 Self(*buff)
-478 }
-479}
-480
-481impl From<[u8; TRANSACTION_ID_SIZE]> for TransactionId {
-482 fn from(buff: [u8; TRANSACTION_ID_SIZE]) -> Self {
-483 Self(buff)
-484 }
-485}
-486
-487impl rand::distr::Distribution<TransactionId> for rand::distr::StandardUniform {
-488 fn sample<R: Rng + ?Sized>(&self, rng: &mut R) -> TransactionId {
-489 let mut buffer = [0u8; TRANSACTION_ID_SIZE];
-490 rng.fill_bytes(&mut buffer);
-491 TransactionId::from(buffer)
-492 }
-493}
-494
-495impl Default for TransactionId {
-496 fn default() -> Self {
-498 let mut rng = rand::rng();
-499 rng.random()
-500 }
-501}
-502
-503#[cfg(test)]
-504mod tests {
-505 use iroh_base::SecretKey;
-506 use rand::SeedableRng;
-507
-508 use super::*;
-509 use crate::key::{SharedSecret, public_ed_box, secret_ed_box};
-510
-511 #[test]
-512 fn test_to_from_bytes() {
-513 struct Test {
-514 name: &'static str,
-515 m: Message,
-516 want: &'static str,
-517 }
-518 let tests = [
-519 Test {
-520 name: "ping_with_endpointkey_src",
-521 m: Message::Ping(Ping {
-522 tx_id: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12].into(),
-523 endpoint_key: PublicKey::try_from(
-524 &[
-525 190, 243, 65, 104, 37, 102, 175, 75, 243, 22, 69, 200, 167, 107, 24,
-526 63, 216, 140, 120, 43, 4, 112, 16, 62, 117, 155, 45, 215, 72, 175, 40,
-527 189,
-528 ][..],
-529 )
-530 .unwrap(),
-531 }),
-532 want: "01 00 01 02 03 04 05 06 07 08 09 0a 0b 0c be f3 41 68 25 66 af 4b f3 16 45 c8 a7 6b 18 3f d8 8c 78 2b 04 70 10 3e 75 9b 2d d7 48 af 28 bd",
-533 },
-534 Test {
-535 name: "pong",
-536 m: Message::Pong(Pong {
-537 tx_id: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12].into(),
-538 ping_observed_addr: SendAddr::Udp("2.3.4.5:1234".parse().unwrap()),
-539 }),
-540 want: "02 00 01 02 03 04 05 06 07 08 09 0a 0b 0c 00 00 00 00 00 00 00 00 00 00 00 ff ff 02 03 04 05 d2 04",
-541 },
-542 Test {
-543 name: "pongv6",
-544 m: Message::Pong(Pong {
-545 tx_id: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12].into(),
-546 ping_observed_addr: SendAddr::Udp("[fed0::12]:6666".parse().unwrap()),
-547 }),
-548 want: "02 00 01 02 03 04 05 06 07 08 09 0a 0b 0c 00 fe d0 00 00 00 00 00 00 00 00 00 00 00 00 00 12 0a 1a",
-549 },
-550 Test {
-551 name: "call_me_maybe",
-552 m: Message::CallMeMaybe(CallMeMaybe {
-553 my_numbers: Vec::new(),
-554 }),
-555 want: "03 00",
-556 },
-557 Test {
-558 name: "call_me_maybe_endpoints",
-559 m: Message::CallMeMaybe(CallMeMaybe {
-560 my_numbers: vec![
-561 "1.2.3.4:567".parse().unwrap(),
-562 "[2001::3456]:789".parse().unwrap(),
-563 ],
-564 }),
-565 want: "03 00 00 00 00 00 00 00 00 00 00 00 ff ff 01 02 03 04 37 02 20 01 00 00 00 00 00 00 00 00 00 00 00 00 34 56 15 03",
-566 },
-567 ];
-568 for test in tests {
-569 println!("{}", test.name);
-570
-571 let got = test.m.as_bytes();
-572 assert_eq!(
-573 got,
-574 data_encoding::HEXLOWER
-575 .decode(test.want.replace(' ', "").as_bytes())
-576 .unwrap(),
-577 "wrong as_bytes"
-578 );
-579
-580 let back = Message::from_bytes(&got).expect("failed to parse");
-581 assert_eq!(test.m, back, "wrong from_bytes");
-582 }
-583 }
-584
-585 #[test]
-586 fn test_extraction() {
-587 let mut rng = rand_chacha::ChaCha8Rng::seed_from_u64(0u64);
-588 let sender_key = SecretKey::generate(&mut rng);
-589 let recv_key = SecretKey::generate(&mut rng);
-590
-591 let msg = Message::Ping(Ping {
-592 tx_id: TransactionId::default(),
-593 endpoint_key: sender_key.public(),
-594 });
-595
-596 let sender_secret = secret_ed_box(&sender_key);
-597 let shared = SharedSecret::new(&sender_secret, &public_ed_box(&recv_key.public()));
-598 let mut seal = msg.as_bytes();
-599 shared.seal(&mut seal);
-600
-601 let bytes = encode_message(&sender_key.public(), seal.clone());
-602
-603 assert!(looks_like_disco_wrapper(&bytes));
-604 assert_eq!(source_and_box(&bytes).unwrap().0, sender_key.public());
-605
-606 let (raw_key, seal_back) = source_and_box(&bytes).unwrap();
-607 assert_eq!(raw_key, sender_key.public());
-608 assert_eq!(seal_back, seal);
-609
-610 let recv_secret = secret_ed_box(&recv_key);
-611 let shared_recv = SharedSecret::new(&recv_secret, &public_ed_box(&sender_key.public()));
-612 let mut open_seal = seal_back.to_vec();
-613 shared_recv
-614 .open(&mut open_seal)
-615 .expect("failed to open seal_back");
-616 let msg_back = Message::from_bytes(&open_seal).unwrap();
-617 assert_eq!(msg_back, msg);
-618 }
-619}