wire.rs (100331B)
1 use crate::error::RadrootsSimplexSmpProtoError; 2 use crate::uri::RadrootsSimplexSmpQueueMode; 3 use crate::version::{ 4 RADROOTS_SIMPLEX_SMP_BLOCKED_ENTITY_TRANSPORT_VERSION, 5 RADROOTS_SIMPLEX_SMP_CURRENT_TRANSPORT_VERSION, RADROOTS_SIMPLEX_SMP_INITIAL_TRANSPORT_VERSION, 6 RADROOTS_SIMPLEX_SMP_NEW_NOTIFIER_CREDENTIALS_TRANSPORT_VERSION, 7 RADROOTS_SIMPLEX_SMP_SENDER_AUTH_KEY_TRANSPORT_VERSION, 8 RADROOTS_SIMPLEX_SMP_SERVICE_CERTS_TRANSPORT_VERSION, 9 RADROOTS_SIMPLEX_SMP_SHORT_LINKS_TRANSPORT_VERSION, RadrootsSimplexSmpVersionRange, 10 }; 11 use alloc::boxed::Box; 12 use alloc::string::{String, ToString}; 13 use alloc::vec::Vec; 14 use core::net::Ipv6Addr; 15 use core::str::FromStr; 16 17 const TAG_NEW: &[u8] = b"NEW"; 18 const TAG_SUB: &[u8] = b"SUB"; 19 const TAG_SUBS: &[u8] = b"SUBS"; 20 const TAG_KEY: &[u8] = b"KEY"; 21 const TAG_RKEY: &[u8] = b"RKEY"; 22 const TAG_LSET: &[u8] = b"LSET"; 23 const TAG_LDEL: &[u8] = b"LDEL"; 24 const TAG_NKEY: &[u8] = b"NKEY"; 25 const TAG_NDEL: &[u8] = b"NDEL"; 26 const TAG_GET: &[u8] = b"GET"; 27 const TAG_ACK: &[u8] = b"ACK"; 28 const TAG_OFF: &[u8] = b"OFF"; 29 const TAG_DEL: &[u8] = b"DEL"; 30 const TAG_QUE: &[u8] = b"QUE"; 31 const TAG_SKEY: &[u8] = b"SKEY"; 32 const TAG_SEND: &[u8] = b"SEND"; 33 const TAG_PING: &[u8] = b"PING"; 34 const TAG_LKEY: &[u8] = b"LKEY"; 35 const TAG_LGET: &[u8] = b"LGET"; 36 const TAG_NSUB: &[u8] = b"NSUB"; 37 const TAG_NSUBS: &[u8] = b"NSUBS"; 38 const TAG_PRXY: &[u8] = b"PRXY"; 39 const TAG_PFWD: &[u8] = b"PFWD"; 40 const TAG_RFWD: &[u8] = b"RFWD"; 41 42 const TAG_IDS: &[u8] = b"IDS"; 43 const TAG_LNK: &[u8] = b"LNK"; 44 const TAG_SOK: &[u8] = b"SOK"; 45 const TAG_SOKS: &[u8] = b"SOKS"; 46 const TAG_NID: &[u8] = b"NID"; 47 const TAG_MSG: &[u8] = b"MSG"; 48 const TAG_NMSG: &[u8] = b"NMSG"; 49 const TAG_PKEY: &[u8] = b"PKEY"; 50 const TAG_RRES: &[u8] = b"RRES"; 51 const TAG_PRES: &[u8] = b"PRES"; 52 const TAG_END: &[u8] = b"END"; 53 const TAG_ENDS: &[u8] = b"ENDS"; 54 const TAG_DELD: &[u8] = b"DELD"; 55 const TAG_INFO: &[u8] = b"INFO"; 56 const TAG_OK: &[u8] = b"OK"; 57 const TAG_ERR: &[u8] = b"ERR"; 58 const TAG_PONG: &[u8] = b"PONG"; 59 60 const COMMAND_ERR_UNKNOWN: &[u8] = b"UNKNOWN"; 61 const COMMAND_ERR_SYNTAX: &[u8] = b"SYNTAX"; 62 const COMMAND_ERR_PROHIBITED: &[u8] = b"PROHIBITED"; 63 const COMMAND_ERR_NO_AUTH: &[u8] = b"NO_AUTH"; 64 const COMMAND_ERR_HAS_AUTH: &[u8] = b"HAS_AUTH"; 65 const COMMAND_ERR_NO_ENTITY: &[u8] = b"NO_ENTITY"; 66 const COMMAND_ERR_NO_QUEUE: &[u8] = b"NO_QUEUE"; 67 68 #[derive(Debug, Clone, Copy, PartialEq, Eq)] 69 pub enum RadrootsSimplexSmpSubscriptionMode { 70 Subscribe, 71 OnlyCreate, 72 } 73 74 #[derive(Debug, Clone, PartialEq, Eq)] 75 pub struct RadrootsSimplexSmpQueueLinkData { 76 pub fixed_data: Vec<u8>, 77 pub user_data: Vec<u8>, 78 } 79 80 #[derive(Debug, Clone, PartialEq, Eq)] 81 pub struct RadrootsSimplexSmpMessagingQueueRequest { 82 pub sender_id: Vec<u8>, 83 pub link_data: RadrootsSimplexSmpQueueLinkData, 84 } 85 86 #[derive(Debug, Clone, PartialEq, Eq)] 87 pub struct RadrootsSimplexSmpContactQueueRequest { 88 pub link_id: Vec<u8>, 89 pub sender_id: Vec<u8>, 90 pub link_data: RadrootsSimplexSmpQueueLinkData, 91 } 92 93 #[derive(Debug, Clone, PartialEq, Eq)] 94 pub struct RadrootsSimplexSmpKeyList { 95 pub first: Vec<u8>, 96 pub rest: Vec<Vec<u8>>, 97 } 98 99 #[derive(Debug, Clone, PartialEq, Eq)] 100 pub struct RadrootsSimplexSmpProtocolServer { 101 pub hosts: Vec<String>, 102 pub port: String, 103 pub key_hash: Vec<u8>, 104 } 105 106 #[derive(Debug, Clone, PartialEq, Eq)] 107 pub struct RadrootsSimplexSmpCertChainPublicKey { 108 pub certificate_chain: Vec<Vec<u8>>, 109 pub signed_public_key: Vec<u8>, 110 } 111 112 #[derive(Debug, Clone, PartialEq, Eq)] 113 pub enum RadrootsSimplexSmpBlockingReason { 114 Spam, 115 Content, 116 Other(String), 117 } 118 119 #[derive(Debug, Clone, PartialEq, Eq)] 120 pub struct RadrootsSimplexSmpBlockingInfo { 121 pub reason: RadrootsSimplexSmpBlockingReason, 122 } 123 124 #[derive(Debug, Clone, PartialEq, Eq)] 125 pub enum RadrootsSimplexSmpHandshakeError { 126 Parse, 127 Identity, 128 BadAuth, 129 BadService, 130 Other(String), 131 } 132 133 #[derive(Debug, Clone, PartialEq, Eq)] 134 pub enum RadrootsSimplexSmpTransportError { 135 Block, 136 Version, 137 LargeMsg, 138 Session, 139 NoAuth, 140 Handshake(RadrootsSimplexSmpHandshakeError), 141 } 142 143 #[derive(Debug, Clone, PartialEq, Eq)] 144 pub enum RadrootsSimplexSmpNetworkError { 145 Connect(String), 146 Tls(String), 147 UnknownCa, 148 Failed, 149 Timeout, 150 Subscribe(String), 151 } 152 153 #[derive(Debug, Clone, PartialEq, Eq)] 154 pub enum RadrootsSimplexSmpBrokerError { 155 Response(String), 156 Unexpected(String), 157 Network(RadrootsSimplexSmpNetworkError), 158 Host, 159 NoService, 160 Transport(RadrootsSimplexSmpTransportError), 161 Timeout, 162 } 163 164 #[derive(Debug, Clone, PartialEq, Eq)] 165 pub enum RadrootsSimplexSmpProxyError { 166 Protocol(Box<RadrootsSimplexSmpError>), 167 Broker(RadrootsSimplexSmpBrokerError), 168 BasicAuth, 169 NoSession, 170 } 171 172 #[derive(Debug, Clone, PartialEq, Eq)] 173 pub enum RadrootsSimplexSmpQueueRequestData { 174 Messaging(Option<RadrootsSimplexSmpMessagingQueueRequest>), 175 Contact(Option<RadrootsSimplexSmpContactQueueRequest>), 176 } 177 178 impl RadrootsSimplexSmpQueueRequestData { 179 pub const fn queue_mode(&self) -> RadrootsSimplexSmpQueueMode { 180 match self { 181 Self::Messaging(_) => RadrootsSimplexSmpQueueMode::Messaging, 182 Self::Contact(_) => RadrootsSimplexSmpQueueMode::Contact, 183 } 184 } 185 } 186 187 #[derive(Debug, Clone, PartialEq, Eq)] 188 pub struct RadrootsSimplexSmpNewNotifierCredentials { 189 pub notifier_auth_public_key: Vec<u8>, 190 pub recipient_notification_dh_public_key: Vec<u8>, 191 } 192 193 #[derive(Debug, Clone, PartialEq, Eq)] 194 pub struct RadrootsSimplexSmpServerNotifierCredentials { 195 pub notifier_id: Vec<u8>, 196 pub server_notification_dh_public_key: Vec<u8>, 197 } 198 199 #[derive(Debug, Clone, PartialEq, Eq)] 200 pub struct RadrootsSimplexSmpNewQueueRequest { 201 pub recipient_auth_public_key: Vec<u8>, 202 pub recipient_dh_public_key: Vec<u8>, 203 pub basic_auth: Option<String>, 204 pub subscription_mode: RadrootsSimplexSmpSubscriptionMode, 205 pub queue_request_data: Option<RadrootsSimplexSmpQueueRequestData>, 206 pub notifier_credentials: Option<RadrootsSimplexSmpNewNotifierCredentials>, 207 } 208 209 impl RadrootsSimplexSmpNewQueueRequest { 210 pub const fn sender_can_secure(&self) -> bool { 211 matches!( 212 self.queue_request_data, 213 Some(RadrootsSimplexSmpQueueRequestData::Messaging(_)) 214 ) 215 } 216 } 217 218 #[derive(Debug, Clone, PartialEq, Eq)] 219 pub struct RadrootsSimplexSmpMessageFlags { 220 pub notification: bool, 221 pub reserved: Vec<u8>, 222 } 223 224 impl RadrootsSimplexSmpMessageFlags { 225 pub const fn notifications_enabled() -> Self { 226 Self { 227 notification: true, 228 reserved: Vec::new(), 229 } 230 } 231 232 pub const fn notifications_disabled() -> Self { 233 Self { 234 notification: false, 235 reserved: Vec::new(), 236 } 237 } 238 } 239 240 impl Default for RadrootsSimplexSmpMessageFlags { 241 fn default() -> Self { 242 Self::notifications_disabled() 243 } 244 } 245 246 #[derive(Debug, Clone, PartialEq, Eq)] 247 pub struct RadrootsSimplexSmpSendCommand { 248 pub flags: RadrootsSimplexSmpMessageFlags, 249 pub message_body: Vec<u8>, 250 } 251 252 #[derive(Debug, Clone, PartialEq, Eq)] 253 pub enum RadrootsSimplexSmpCommand { 254 New(RadrootsSimplexSmpNewQueueRequest), 255 Sub, 256 Subs, 257 Key(Vec<u8>), 258 RKey(RadrootsSimplexSmpKeyList), 259 LSet { 260 link_id: Vec<u8>, 261 link_data: RadrootsSimplexSmpQueueLinkData, 262 }, 263 LDel, 264 NKey { 265 notifier_auth_public_key: Vec<u8>, 266 recipient_notification_dh_public_key: Vec<u8>, 267 }, 268 NDel, 269 Get, 270 Ack(Vec<u8>), 271 Off, 272 Del, 273 Que, 274 SKey(Vec<u8>), 275 Send(RadrootsSimplexSmpSendCommand), 276 Ping, 277 LKey(Vec<u8>), 278 LGet, 279 NSub, 280 NSubs, 281 Prxy { 282 server: RadrootsSimplexSmpProtocolServer, 283 basic_auth: Option<String>, 284 }, 285 PFwd { 286 relay_version: u16, 287 public_key: Vec<u8>, 288 encrypted_transmission: Vec<u8>, 289 }, 290 RFwd(Vec<u8>), 291 } 292 293 #[derive(Debug, Clone, PartialEq, Eq)] 294 pub struct RadrootsSimplexSmpQueueIdsResponse { 295 pub recipient_id: Vec<u8>, 296 pub sender_id: Vec<u8>, 297 pub server_dh_public_key: Vec<u8>, 298 pub queue_mode: Option<RadrootsSimplexSmpQueueMode>, 299 pub link_id: Option<Vec<u8>>, 300 pub service_id: Option<Vec<u8>>, 301 pub server_notification_credentials: Option<RadrootsSimplexSmpServerNotifierCredentials>, 302 } 303 304 impl RadrootsSimplexSmpQueueIdsResponse { 305 pub const fn sender_can_secure(&self) -> bool { 306 matches!( 307 self.queue_mode, 308 Some(RadrootsSimplexSmpQueueMode::Messaging) 309 ) 310 } 311 } 312 313 #[derive(Debug, Clone, PartialEq, Eq)] 314 pub struct RadrootsSimplexSmpNotifierIdsResponse { 315 pub notifier_id: Vec<u8>, 316 pub server_notification_dh_public_key: Vec<u8>, 317 } 318 319 #[derive(Debug, Clone, PartialEq, Eq)] 320 pub struct RadrootsSimplexSmpReceivedMessage { 321 pub message_id: Vec<u8>, 322 pub encrypted_body: Vec<u8>, 323 } 324 325 #[derive(Debug, Clone, PartialEq, Eq)] 326 pub enum RadrootsSimplexSmpCommandError { 327 Unknown, 328 Syntax, 329 Prohibited, 330 NoAuth, 331 HasAuth, 332 NoEntity, 333 Other(Vec<u8>), 334 } 335 336 #[derive(Debug, Clone, PartialEq, Eq)] 337 pub enum RadrootsSimplexSmpError { 338 Block, 339 Session, 340 Command(RadrootsSimplexSmpCommandError), 341 Proxy(RadrootsSimplexSmpProxyError), 342 Auth, 343 Blocked(RadrootsSimplexSmpBlockingInfo), 344 Service, 345 Crypto, 346 Quota, 347 Store(String), 348 NoMsg, 349 LargeMsg, 350 Expired, 351 Internal, 352 Duplicate, 353 Other(Vec<u8>), 354 } 355 356 #[derive(Debug, Clone, Copy, PartialEq, Eq)] 357 pub struct RadrootsSimplexSmpCorrelationId([u8; 24]); 358 359 impl RadrootsSimplexSmpCorrelationId { 360 pub const LENGTH: usize = 24; 361 362 pub const fn new(bytes: [u8; 24]) -> Self { 363 Self(bytes) 364 } 365 366 pub fn from_slice(value: &[u8]) -> Result<Self, RadrootsSimplexSmpProtoError> { 367 if value.len() != Self::LENGTH { 368 return Err(RadrootsSimplexSmpProtoError::InvalidCorrelationIdLength( 369 value.len(), 370 )); 371 } 372 let mut bytes = [0_u8; Self::LENGTH]; 373 bytes.copy_from_slice(value); 374 Ok(Self(bytes)) 375 } 376 377 pub const fn as_bytes(&self) -> &[u8; 24] { 378 &self.0 379 } 380 } 381 382 #[derive(Debug, Clone, PartialEq, Eq)] 383 pub enum RadrootsSimplexSmpBrokerMessage { 384 Ids(RadrootsSimplexSmpQueueIdsResponse), 385 Lnk { 386 sender_id: Vec<u8>, 387 link_data: RadrootsSimplexSmpQueueLinkData, 388 }, 389 Sok(Option<Vec<u8>>), 390 Soks(i64), 391 Nid(RadrootsSimplexSmpNotifierIdsResponse), 392 Msg(RadrootsSimplexSmpReceivedMessage), 393 NMsg { 394 nonce: [u8; 24], 395 encrypted_metadata: Vec<u8>, 396 }, 397 PKey { 398 session_id: Vec<u8>, 399 version_range: RadrootsSimplexSmpVersionRange, 400 cert_chain_public_key: RadrootsSimplexSmpCertChainPublicKey, 401 }, 402 RRes(Vec<u8>), 403 PRes(Vec<u8>), 404 End, 405 Ends(i64), 406 Deld, 407 Info(Vec<u8>), 408 Ok, 409 Err(RadrootsSimplexSmpError), 410 Pong, 411 } 412 413 #[derive(Debug, Clone, PartialEq, Eq)] 414 pub struct RadrootsSimplexSmpCommandTransmission { 415 pub authorization: Vec<u8>, 416 pub correlation_id: Option<RadrootsSimplexSmpCorrelationId>, 417 pub entity_id: Vec<u8>, 418 pub command: RadrootsSimplexSmpCommand, 419 } 420 421 #[derive(Debug, Clone, PartialEq, Eq)] 422 pub struct RadrootsSimplexSmpBrokerTransmission { 423 pub authorization: Vec<u8>, 424 pub correlation_id: Option<RadrootsSimplexSmpCorrelationId>, 425 pub entity_id: Vec<u8>, 426 pub message: RadrootsSimplexSmpBrokerMessage, 427 } 428 429 type RadrootsSimplexSmpDecodedTransmission<'a> = ( 430 Vec<u8>, 431 Option<RadrootsSimplexSmpCorrelationId>, 432 Vec<u8>, 433 &'a [u8], 434 ); 435 436 impl RadrootsSimplexSmpCommand { 437 pub fn encode(&self) -> Result<Vec<u8>, RadrootsSimplexSmpProtoError> { 438 self.encode_for_version(RADROOTS_SIMPLEX_SMP_CURRENT_TRANSPORT_VERSION) 439 } 440 441 pub fn encode_for_version( 442 &self, 443 transport_version: u16, 444 ) -> Result<Vec<u8>, RadrootsSimplexSmpProtoError> { 445 let mut buffer = Vec::new(); 446 match self { 447 Self::New(request) => encode_new_request(&mut buffer, request, transport_version)?, 448 Self::Sub => buffer.extend_from_slice(TAG_SUB), 449 Self::Subs => buffer.extend_from_slice(TAG_SUBS), 450 Self::Key(sender_auth_public_key) => { 451 buffer.extend_from_slice(TAG_KEY); 452 buffer.push(b' '); 453 push_short_bytes(&mut buffer, sender_auth_public_key)?; 454 } 455 Self::RKey(recipient_auth_public_keys) => { 456 buffer.extend_from_slice(TAG_RKEY); 457 buffer.push(b' '); 458 push_short_key_list(&mut buffer, recipient_auth_public_keys)?; 459 } 460 Self::LSet { link_id, link_data } => { 461 buffer.extend_from_slice(TAG_LSET); 462 buffer.push(b' '); 463 push_short_bytes(&mut buffer, link_id)?; 464 encode_queue_link_data(&mut buffer, link_data)?; 465 } 466 Self::LDel => buffer.extend_from_slice(TAG_LDEL), 467 Self::NKey { 468 notifier_auth_public_key, 469 recipient_notification_dh_public_key, 470 } => { 471 buffer.extend_from_slice(TAG_NKEY); 472 buffer.push(b' '); 473 push_short_bytes(&mut buffer, notifier_auth_public_key)?; 474 push_short_bytes(&mut buffer, recipient_notification_dh_public_key)?; 475 } 476 Self::NDel => buffer.extend_from_slice(TAG_NDEL), 477 Self::Get => buffer.extend_from_slice(TAG_GET), 478 Self::Ack(message_id) => { 479 buffer.extend_from_slice(TAG_ACK); 480 buffer.push(b' '); 481 push_short_bytes(&mut buffer, message_id)?; 482 } 483 Self::Off => buffer.extend_from_slice(TAG_OFF), 484 Self::Del => buffer.extend_from_slice(TAG_DEL), 485 Self::Que => buffer.extend_from_slice(TAG_QUE), 486 Self::SKey(sender_auth_public_key) => { 487 buffer.extend_from_slice(TAG_SKEY); 488 buffer.push(b' '); 489 push_short_bytes(&mut buffer, sender_auth_public_key)?; 490 } 491 Self::Send(send) => { 492 buffer.extend_from_slice(TAG_SEND); 493 buffer.push(b' '); 494 buffer.push(encode_bool(send.flags.notification)); 495 buffer.extend_from_slice(&send.flags.reserved); 496 buffer.push(b' '); 497 buffer.extend_from_slice(&send.message_body); 498 } 499 Self::Ping => buffer.extend_from_slice(TAG_PING), 500 Self::LKey(sender_auth_public_key) => { 501 buffer.extend_from_slice(TAG_LKEY); 502 buffer.push(b' '); 503 push_short_bytes(&mut buffer, sender_auth_public_key)?; 504 } 505 Self::LGet => buffer.extend_from_slice(TAG_LGET), 506 Self::NSub => buffer.extend_from_slice(TAG_NSUB), 507 Self::NSubs => buffer.extend_from_slice(TAG_NSUBS), 508 Self::Prxy { server, basic_auth } => { 509 buffer.extend_from_slice(TAG_PRXY); 510 buffer.push(b' '); 511 encode_protocol_server(&mut buffer, server)?; 512 push_maybe_string(&mut buffer, basic_auth.as_deref())?; 513 } 514 Self::PFwd { 515 relay_version, 516 public_key, 517 encrypted_transmission, 518 } => { 519 buffer.extend_from_slice(TAG_PFWD); 520 buffer.push(b' '); 521 buffer.extend_from_slice(&relay_version.to_be_bytes()); 522 push_short_bytes(&mut buffer, public_key)?; 523 buffer.extend_from_slice(encrypted_transmission); 524 } 525 Self::RFwd(encrypted_forward_transmission) => { 526 buffer.extend_from_slice(TAG_RFWD); 527 buffer.push(b' '); 528 buffer.extend_from_slice(encrypted_forward_transmission); 529 } 530 } 531 Ok(buffer) 532 } 533 534 pub fn decode(bytes: &[u8]) -> Result<Self, RadrootsSimplexSmpProtoError> { 535 Self::decode_for_version(RADROOTS_SIMPLEX_SMP_CURRENT_TRANSPORT_VERSION, bytes) 536 } 537 538 pub fn decode_for_version( 539 transport_version: u16, 540 bytes: &[u8], 541 ) -> Result<Self, RadrootsSimplexSmpProtoError> { 542 let (tag, rest) = parse_tag(bytes)?; 543 let mut cursor = Cursor::new(rest); 544 let command = match tag.as_slice() { 545 TAG_NEW => Self::New(decode_new_request(&mut cursor, transport_version)?), 546 TAG_SUB => Self::Sub, 547 TAG_SUBS => Self::Subs, 548 TAG_KEY => Self::Key(cursor.read_short_bytes()?), 549 TAG_RKEY => Self::RKey(cursor.read_short_key_list()?), 550 TAG_LSET => Self::LSet { 551 link_id: cursor.read_short_bytes()?, 552 link_data: decode_queue_link_data(&mut cursor)?, 553 }, 554 TAG_LDEL => Self::LDel, 555 TAG_NKEY => Self::NKey { 556 notifier_auth_public_key: cursor.read_short_bytes()?, 557 recipient_notification_dh_public_key: cursor.read_short_bytes()?, 558 }, 559 TAG_NDEL => Self::NDel, 560 TAG_GET => Self::Get, 561 TAG_ACK => Self::Ack(cursor.read_short_bytes()?), 562 TAG_OFF => Self::Off, 563 TAG_DEL => Self::Del, 564 TAG_QUE => Self::Que, 565 TAG_SKEY => Self::SKey(cursor.read_short_bytes()?), 566 TAG_SEND => Self::Send(decode_send_payload(rest)?), 567 TAG_PING => Self::Ping, 568 TAG_LKEY => Self::LKey(cursor.read_short_bytes()?), 569 TAG_LGET => Self::LGet, 570 TAG_NSUB => Self::NSub, 571 TAG_NSUBS => Self::NSubs, 572 TAG_PRXY => Self::Prxy { 573 server: decode_protocol_server(&mut cursor)?, 574 basic_auth: cursor.read_maybe_string()?, 575 }, 576 TAG_PFWD => Self::PFwd { 577 relay_version: u16::from_be_bytes(cursor.read_array::<2>()?), 578 public_key: cursor.read_short_bytes()?, 579 encrypted_transmission: cursor.read_remaining().to_vec(), 580 }, 581 TAG_RFWD => Self::RFwd(cursor.read_remaining().to_vec()), 582 _ => { 583 return Err(RadrootsSimplexSmpProtoError::UnsupportedTag( 584 String::from_utf8_lossy(&tag).into_owned(), 585 )); 586 } 587 }; 588 if !matches!(command, Self::Send(_)) && !cursor.is_empty() { 589 return Err(RadrootsSimplexSmpProtoError::TrailingBytes); 590 } 591 Ok(command) 592 } 593 } 594 595 impl RadrootsSimplexSmpBrokerMessage { 596 pub fn encode(&self) -> Result<Vec<u8>, RadrootsSimplexSmpProtoError> { 597 self.encode_for_version(RADROOTS_SIMPLEX_SMP_CURRENT_TRANSPORT_VERSION) 598 } 599 600 pub fn encode_for_version( 601 &self, 602 transport_version: u16, 603 ) -> Result<Vec<u8>, RadrootsSimplexSmpProtoError> { 604 let mut buffer = Vec::new(); 605 match self { 606 Self::Ids(response) => encode_ids_response(&mut buffer, response, transport_version)?, 607 Self::Lnk { 608 sender_id, 609 link_data, 610 } => { 611 buffer.extend_from_slice(TAG_LNK); 612 buffer.push(b' '); 613 push_short_bytes(&mut buffer, sender_id)?; 614 encode_queue_link_data(&mut buffer, link_data)?; 615 } 616 Self::Sok(service_id) => { 617 if transport_version >= RADROOTS_SIMPLEX_SMP_SERVICE_CERTS_TRANSPORT_VERSION { 618 buffer.extend_from_slice(TAG_SOK); 619 buffer.push(b' '); 620 push_maybe_short_bytes(&mut buffer, service_id.as_deref())?; 621 } else { 622 buffer.extend_from_slice(TAG_OK); 623 } 624 } 625 Self::Soks(queue_count) => { 626 buffer.extend_from_slice(TAG_SOKS); 627 buffer.push(b' '); 628 push_i64(&mut buffer, *queue_count); 629 } 630 Self::Nid(response) => { 631 buffer.extend_from_slice(TAG_NID); 632 buffer.push(b' '); 633 push_short_bytes(&mut buffer, &response.notifier_id)?; 634 push_short_bytes(&mut buffer, &response.server_notification_dh_public_key)?; 635 } 636 Self::Msg(message) => { 637 buffer.extend_from_slice(TAG_MSG); 638 buffer.push(b' '); 639 push_short_bytes(&mut buffer, &message.message_id)?; 640 buffer.extend_from_slice(&message.encrypted_body); 641 } 642 Self::NMsg { 643 nonce, 644 encrypted_metadata, 645 } => { 646 buffer.extend_from_slice(TAG_NMSG); 647 buffer.push(b' '); 648 buffer.extend_from_slice(nonce); 649 buffer.extend_from_slice(encrypted_metadata); 650 } 651 Self::PKey { 652 session_id, 653 version_range, 654 cert_chain_public_key, 655 } => { 656 buffer.extend_from_slice(TAG_PKEY); 657 buffer.push(b' '); 658 push_short_bytes(&mut buffer, session_id)?; 659 buffer.extend_from_slice(&version_range.min.to_be_bytes()); 660 buffer.extend_from_slice(&version_range.max.to_be_bytes()); 661 encode_cert_chain_public_key(&mut buffer, cert_chain_public_key)?; 662 } 663 Self::RRes(encrypted_forward_response) => { 664 buffer.extend_from_slice(TAG_RRES); 665 buffer.push(b' '); 666 buffer.extend_from_slice(encrypted_forward_response); 667 } 668 Self::PRes(encrypted_response) => { 669 buffer.extend_from_slice(TAG_PRES); 670 buffer.push(b' '); 671 buffer.extend_from_slice(encrypted_response); 672 } 673 Self::End => buffer.extend_from_slice(TAG_END), 674 Self::Ends(queue_count) => { 675 buffer.extend_from_slice(TAG_ENDS); 676 buffer.push(b' '); 677 push_i64(&mut buffer, *queue_count); 678 } 679 Self::Deld => buffer.extend_from_slice(TAG_DELD), 680 Self::Info(info) => { 681 buffer.extend_from_slice(TAG_INFO); 682 buffer.push(b' '); 683 buffer.extend_from_slice(info); 684 } 685 Self::Ok => buffer.extend_from_slice(TAG_OK), 686 Self::Err(error) => { 687 buffer.extend_from_slice(TAG_ERR); 688 buffer.push(b' '); 689 if transport_version < RADROOTS_SIMPLEX_SMP_BLOCKED_ENTITY_TRANSPORT_VERSION 690 && matches!(error, RadrootsSimplexSmpError::Blocked(_)) 691 { 692 buffer.extend_from_slice(b"AUTH"); 693 } else { 694 buffer.extend_from_slice(&encode_error(error)?); 695 } 696 } 697 Self::Pong => buffer.extend_from_slice(TAG_PONG), 698 } 699 Ok(buffer) 700 } 701 702 pub fn decode(bytes: &[u8]) -> Result<Self, RadrootsSimplexSmpProtoError> { 703 Self::decode_for_version(RADROOTS_SIMPLEX_SMP_CURRENT_TRANSPORT_VERSION, bytes) 704 } 705 706 pub fn decode_for_version( 707 transport_version: u16, 708 bytes: &[u8], 709 ) -> Result<Self, RadrootsSimplexSmpProtoError> { 710 let (tag, rest) = parse_tag(bytes)?; 711 let mut cursor = Cursor::new(rest); 712 let message = match tag.as_slice() { 713 TAG_IDS => Self::Ids(decode_ids_response(&mut cursor, transport_version)?), 714 TAG_LNK => Self::Lnk { 715 sender_id: cursor.read_short_bytes()?, 716 link_data: decode_queue_link_data(&mut cursor)?, 717 }, 718 TAG_SOK => Self::Sok(cursor.read_maybe(Cursor::read_short_bytes)?), 719 TAG_SOKS => Self::Soks(cursor.read_i64()?), 720 TAG_NID => Self::Nid(RadrootsSimplexSmpNotifierIdsResponse { 721 notifier_id: cursor.read_short_bytes()?, 722 server_notification_dh_public_key: cursor.read_short_bytes()?, 723 }), 724 TAG_MSG => Self::Msg(RadrootsSimplexSmpReceivedMessage { 725 message_id: cursor.read_short_bytes()?, 726 encrypted_body: cursor.read_remaining().to_vec(), 727 }), 728 TAG_NMSG => { 729 let nonce = cursor.read_array::<24>().map_err(|error| match error { 730 RadrootsSimplexSmpProtoError::UnexpectedEof => { 731 RadrootsSimplexSmpProtoError::InvalidNonceLength(cursor.remaining_len()) 732 } 733 other => other, 734 })?; 735 Self::NMsg { 736 nonce, 737 encrypted_metadata: cursor.read_remaining().to_vec(), 738 } 739 } 740 TAG_PKEY => { 741 let session_id = cursor.read_short_bytes()?; 742 let min = u16::from_be_bytes(cursor.read_array::<2>()?); 743 let max = u16::from_be_bytes(cursor.read_array::<2>()?); 744 Self::PKey { 745 session_id, 746 version_range: RadrootsSimplexSmpVersionRange::new(min, max)?, 747 cert_chain_public_key: decode_cert_chain_public_key(&mut cursor)?, 748 } 749 } 750 TAG_RRES => Self::RRes(cursor.read_remaining().to_vec()), 751 TAG_PRES => Self::PRes(cursor.read_remaining().to_vec()), 752 TAG_END => Self::End, 753 TAG_ENDS => Self::Ends(cursor.read_i64()?), 754 TAG_DELD => Self::Deld, 755 TAG_INFO => Self::Info(cursor.read_remaining().to_vec()), 756 TAG_OK => Self::Ok, 757 TAG_ERR => Self::Err(decode_error(rest)?), 758 TAG_PONG => Self::Pong, 759 _ => { 760 return Err(RadrootsSimplexSmpProtoError::UnsupportedTag( 761 String::from_utf8_lossy(&tag).into_owned(), 762 )); 763 } 764 }; 765 if !matches!( 766 message, 767 Self::Msg(_) 768 | Self::NMsg { .. } 769 | Self::RRes(_) 770 | Self::PRes(_) 771 | Self::Info(_) 772 | Self::Err(_) 773 ) && !cursor.is_empty() 774 { 775 return Err(RadrootsSimplexSmpProtoError::TrailingBytes); 776 } 777 Ok(message) 778 } 779 } 780 781 impl RadrootsSimplexSmpCommandTransmission { 782 pub fn encode(&self) -> Result<Vec<u8>, RadrootsSimplexSmpProtoError> { 783 self.encode_for_version(RADROOTS_SIMPLEX_SMP_CURRENT_TRANSPORT_VERSION) 784 } 785 786 pub fn encode_for_version( 787 &self, 788 transport_version: u16, 789 ) -> Result<Vec<u8>, RadrootsSimplexSmpProtoError> { 790 encode_transmission( 791 transport_version, 792 &self.authorization, 793 self.correlation_id, 794 &self.entity_id, 795 &self.command.encode_for_version(transport_version)?, 796 ) 797 } 798 799 pub fn decode(bytes: &[u8]) -> Result<Self, RadrootsSimplexSmpProtoError> { 800 Self::decode_for_version(RADROOTS_SIMPLEX_SMP_CURRENT_TRANSPORT_VERSION, bytes) 801 } 802 803 pub fn decode_for_version( 804 transport_version: u16, 805 bytes: &[u8], 806 ) -> Result<Self, RadrootsSimplexSmpProtoError> { 807 let (authorization, correlation_id, entity_id, frame) = 808 decode_transmission(transport_version, bytes)?; 809 Ok(Self { 810 authorization, 811 correlation_id, 812 entity_id, 813 command: RadrootsSimplexSmpCommand::decode_for_version(transport_version, frame)?, 814 }) 815 } 816 } 817 818 impl RadrootsSimplexSmpBrokerTransmission { 819 pub fn encode(&self) -> Result<Vec<u8>, RadrootsSimplexSmpProtoError> { 820 self.encode_for_version(RADROOTS_SIMPLEX_SMP_CURRENT_TRANSPORT_VERSION) 821 } 822 823 pub fn encode_for_version( 824 &self, 825 transport_version: u16, 826 ) -> Result<Vec<u8>, RadrootsSimplexSmpProtoError> { 827 encode_transmission( 828 transport_version, 829 &self.authorization, 830 self.correlation_id, 831 &self.entity_id, 832 &self.message.encode_for_version(transport_version)?, 833 ) 834 } 835 836 pub fn decode(bytes: &[u8]) -> Result<Self, RadrootsSimplexSmpProtoError> { 837 Self::decode_for_version(RADROOTS_SIMPLEX_SMP_CURRENT_TRANSPORT_VERSION, bytes) 838 } 839 840 pub fn decode_for_version( 841 transport_version: u16, 842 bytes: &[u8], 843 ) -> Result<Self, RadrootsSimplexSmpProtoError> { 844 let (authorization, correlation_id, entity_id, frame) = 845 decode_transmission(transport_version, bytes)?; 846 Ok(Self { 847 authorization, 848 correlation_id, 849 entity_id, 850 message: RadrootsSimplexSmpBrokerMessage::decode_for_version(transport_version, frame)?, 851 }) 852 } 853 } 854 855 fn encode_new_request( 856 buffer: &mut Vec<u8>, 857 request: &RadrootsSimplexSmpNewQueueRequest, 858 transport_version: u16, 859 ) -> Result<(), RadrootsSimplexSmpProtoError> { 860 if transport_version < RADROOTS_SIMPLEX_SMP_INITIAL_TRANSPORT_VERSION { 861 return Err(RadrootsSimplexSmpProtoError::UnsupportedTransportVersion( 862 transport_version, 863 )); 864 } 865 866 buffer.extend_from_slice(TAG_NEW); 867 buffer.push(b' '); 868 push_short_bytes(buffer, &request.recipient_auth_public_key)?; 869 push_short_bytes(buffer, &request.recipient_dh_public_key)?; 870 if transport_version >= RADROOTS_SIMPLEX_SMP_NEW_NOTIFIER_CREDENTIALS_TRANSPORT_VERSION { 871 push_maybe_string(buffer, request.basic_auth.as_deref())?; 872 buffer.push(encode_subscription_mode(request.subscription_mode)); 873 push_maybe( 874 buffer, 875 request.queue_request_data.as_ref(), 876 encode_queue_request_data, 877 )?; 878 push_maybe( 879 buffer, 880 request.notifier_credentials.as_ref(), 881 encode_new_notifier_credentials, 882 )?; 883 } else if transport_version >= RADROOTS_SIMPLEX_SMP_SHORT_LINKS_TRANSPORT_VERSION { 884 push_maybe_string(buffer, request.basic_auth.as_deref())?; 885 buffer.push(encode_subscription_mode(request.subscription_mode)); 886 push_maybe( 887 buffer, 888 request.queue_request_data.as_ref(), 889 encode_queue_request_data, 890 )?; 891 } else if transport_version >= RADROOTS_SIMPLEX_SMP_SENDER_AUTH_KEY_TRANSPORT_VERSION { 892 push_maybe_string(buffer, request.basic_auth.as_deref())?; 893 buffer.push(encode_subscription_mode(request.subscription_mode)); 894 buffer.push(encode_bool(request.sender_can_secure())); 895 } else { 896 push_legacy_basic_auth(buffer, request.basic_auth.as_deref())?; 897 buffer.push(encode_subscription_mode(request.subscription_mode)); 898 } 899 900 Ok(()) 901 } 902 903 fn decode_new_request( 904 cursor: &mut Cursor<'_>, 905 transport_version: u16, 906 ) -> Result<RadrootsSimplexSmpNewQueueRequest, RadrootsSimplexSmpProtoError> { 907 if transport_version < RADROOTS_SIMPLEX_SMP_INITIAL_TRANSPORT_VERSION { 908 return Err(RadrootsSimplexSmpProtoError::UnsupportedTransportVersion( 909 transport_version, 910 )); 911 } 912 913 let recipient_auth_public_key = cursor.read_short_bytes()?; 914 let recipient_dh_public_key = cursor.read_short_bytes()?; 915 let (basic_auth, subscription_mode, queue_request_data, notifier_credentials) = 916 if transport_version >= RADROOTS_SIMPLEX_SMP_NEW_NOTIFIER_CREDENTIALS_TRANSPORT_VERSION { 917 ( 918 cursor.read_maybe_string()?, 919 decode_subscription_mode(cursor.read_byte()?)?, 920 cursor.read_maybe(decode_queue_request_data)?, 921 cursor.read_maybe(decode_new_notifier_credentials)?, 922 ) 923 } else if transport_version >= RADROOTS_SIMPLEX_SMP_SHORT_LINKS_TRANSPORT_VERSION { 924 ( 925 cursor.read_maybe_string()?, 926 decode_subscription_mode(cursor.read_byte()?)?, 927 cursor.read_maybe(decode_queue_request_data)?, 928 None, 929 ) 930 } else if transport_version >= RADROOTS_SIMPLEX_SMP_SENDER_AUTH_KEY_TRANSPORT_VERSION { 931 let basic_auth = cursor.read_maybe_string()?; 932 let subscription_mode = decode_subscription_mode(cursor.read_byte()?)?; 933 let sender_can_secure = decode_bool(cursor.read_byte()?)?; 934 let queue_request_data = Some(if sender_can_secure { 935 RadrootsSimplexSmpQueueRequestData::Messaging(None) 936 } else { 937 RadrootsSimplexSmpQueueRequestData::Contact(None) 938 }); 939 (basic_auth, subscription_mode, queue_request_data, None) 940 } else { 941 ( 942 cursor.read_legacy_basic_auth()?, 943 decode_subscription_mode(cursor.read_byte()?)?, 944 None, 945 None, 946 ) 947 }; 948 949 Ok(RadrootsSimplexSmpNewQueueRequest { 950 recipient_auth_public_key, 951 recipient_dh_public_key, 952 basic_auth, 953 subscription_mode, 954 queue_request_data, 955 notifier_credentials, 956 }) 957 } 958 959 fn encode_ids_response( 960 buffer: &mut Vec<u8>, 961 response: &RadrootsSimplexSmpQueueIdsResponse, 962 transport_version: u16, 963 ) -> Result<(), RadrootsSimplexSmpProtoError> { 964 buffer.extend_from_slice(TAG_IDS); 965 buffer.push(b' '); 966 push_short_bytes(buffer, &response.recipient_id)?; 967 push_short_bytes(buffer, &response.sender_id)?; 968 push_short_bytes(buffer, &response.server_dh_public_key)?; 969 970 if transport_version >= RADROOTS_SIMPLEX_SMP_NEW_NOTIFIER_CREDENTIALS_TRANSPORT_VERSION { 971 push_maybe(buffer, response.queue_mode, encode_queue_mode)?; 972 push_maybe_short_bytes(buffer, response.link_id.as_deref())?; 973 push_maybe_short_bytes(buffer, response.service_id.as_deref())?; 974 push_maybe( 975 buffer, 976 response.server_notification_credentials.as_ref(), 977 encode_server_notifier_credentials, 978 )?; 979 } else if transport_version >= RADROOTS_SIMPLEX_SMP_SERVICE_CERTS_TRANSPORT_VERSION { 980 push_maybe(buffer, response.queue_mode, encode_queue_mode)?; 981 push_maybe_short_bytes(buffer, response.link_id.as_deref())?; 982 push_maybe_short_bytes(buffer, response.service_id.as_deref())?; 983 } else if transport_version >= RADROOTS_SIMPLEX_SMP_SHORT_LINKS_TRANSPORT_VERSION { 984 push_maybe(buffer, response.queue_mode, encode_queue_mode)?; 985 push_maybe_short_bytes(buffer, response.link_id.as_deref())?; 986 } else if transport_version >= RADROOTS_SIMPLEX_SMP_SENDER_AUTH_KEY_TRANSPORT_VERSION { 987 buffer.push(encode_bool(response.sender_can_secure())); 988 } 989 990 Ok(()) 991 } 992 993 fn decode_ids_response( 994 cursor: &mut Cursor<'_>, 995 transport_version: u16, 996 ) -> Result<RadrootsSimplexSmpQueueIdsResponse, RadrootsSimplexSmpProtoError> { 997 let recipient_id = cursor.read_short_bytes()?; 998 let sender_id = cursor.read_short_bytes()?; 999 let server_dh_public_key = cursor.read_short_bytes()?; 1000 1001 let (queue_mode, link_id, service_id, server_notification_credentials) = 1002 if transport_version >= RADROOTS_SIMPLEX_SMP_NEW_NOTIFIER_CREDENTIALS_TRANSPORT_VERSION { 1003 ( 1004 cursor.read_maybe(decode_queue_mode)?, 1005 cursor.read_maybe(Cursor::read_short_bytes)?, 1006 cursor.read_maybe(Cursor::read_short_bytes)?, 1007 cursor.read_maybe(decode_server_notifier_credentials)?, 1008 ) 1009 } else if transport_version >= RADROOTS_SIMPLEX_SMP_SERVICE_CERTS_TRANSPORT_VERSION { 1010 ( 1011 cursor.read_maybe(decode_queue_mode)?, 1012 cursor.read_maybe(Cursor::read_short_bytes)?, 1013 cursor.read_maybe(Cursor::read_short_bytes)?, 1014 None, 1015 ) 1016 } else if transport_version >= RADROOTS_SIMPLEX_SMP_SHORT_LINKS_TRANSPORT_VERSION { 1017 ( 1018 cursor.read_maybe(decode_queue_mode)?, 1019 cursor.read_maybe(Cursor::read_short_bytes)?, 1020 None, 1021 None, 1022 ) 1023 } else if transport_version >= RADROOTS_SIMPLEX_SMP_SENDER_AUTH_KEY_TRANSPORT_VERSION { 1024 let sender_can_secure = decode_bool(cursor.read_byte()?)?; 1025 ( 1026 Some(if sender_can_secure { 1027 RadrootsSimplexSmpQueueMode::Messaging 1028 } else { 1029 RadrootsSimplexSmpQueueMode::Contact 1030 }), 1031 None, 1032 None, 1033 None, 1034 ) 1035 } else { 1036 (None, None, None, None) 1037 }; 1038 1039 Ok(RadrootsSimplexSmpQueueIdsResponse { 1040 recipient_id, 1041 sender_id, 1042 server_dh_public_key, 1043 queue_mode, 1044 link_id, 1045 service_id, 1046 server_notification_credentials, 1047 }) 1048 } 1049 1050 fn encode_queue_request_data( 1051 buffer: &mut Vec<u8>, 1052 queue_request_data: &RadrootsSimplexSmpQueueRequestData, 1053 ) -> Result<(), RadrootsSimplexSmpProtoError> { 1054 match queue_request_data { 1055 RadrootsSimplexSmpQueueRequestData::Messaging(data) => { 1056 buffer.push(b'M'); 1057 push_maybe(buffer, data.as_ref(), encode_messaging_queue_request) 1058 } 1059 RadrootsSimplexSmpQueueRequestData::Contact(data) => { 1060 buffer.push(b'C'); 1061 push_maybe(buffer, data.as_ref(), encode_contact_queue_request) 1062 } 1063 } 1064 } 1065 1066 fn decode_queue_request_data( 1067 cursor: &mut Cursor<'_>, 1068 ) -> Result<RadrootsSimplexSmpQueueRequestData, RadrootsSimplexSmpProtoError> { 1069 match cursor.read_byte()? { 1070 b'M' => Ok(RadrootsSimplexSmpQueueRequestData::Messaging( 1071 cursor.read_maybe(decode_messaging_queue_request)?, 1072 )), 1073 b'C' => Ok(RadrootsSimplexSmpQueueRequestData::Contact( 1074 cursor.read_maybe(decode_contact_queue_request)?, 1075 )), 1076 value => Err(RadrootsSimplexSmpProtoError::InvalidTag( 1077 String::from_utf8_lossy(&[value]).into_owned(), 1078 )), 1079 } 1080 } 1081 1082 fn encode_messaging_queue_request( 1083 buffer: &mut Vec<u8>, 1084 request: &RadrootsSimplexSmpMessagingQueueRequest, 1085 ) -> Result<(), RadrootsSimplexSmpProtoError> { 1086 push_short_bytes(buffer, &request.sender_id)?; 1087 encode_queue_link_data(buffer, &request.link_data) 1088 } 1089 1090 fn decode_messaging_queue_request( 1091 cursor: &mut Cursor<'_>, 1092 ) -> Result<RadrootsSimplexSmpMessagingQueueRequest, RadrootsSimplexSmpProtoError> { 1093 Ok(RadrootsSimplexSmpMessagingQueueRequest { 1094 sender_id: cursor.read_short_bytes()?, 1095 link_data: decode_queue_link_data(cursor)?, 1096 }) 1097 } 1098 1099 fn encode_contact_queue_request( 1100 buffer: &mut Vec<u8>, 1101 request: &RadrootsSimplexSmpContactQueueRequest, 1102 ) -> Result<(), RadrootsSimplexSmpProtoError> { 1103 push_short_bytes(buffer, &request.link_id)?; 1104 push_short_bytes(buffer, &request.sender_id)?; 1105 encode_queue_link_data(buffer, &request.link_data) 1106 } 1107 1108 fn decode_contact_queue_request( 1109 cursor: &mut Cursor<'_>, 1110 ) -> Result<RadrootsSimplexSmpContactQueueRequest, RadrootsSimplexSmpProtoError> { 1111 Ok(RadrootsSimplexSmpContactQueueRequest { 1112 link_id: cursor.read_short_bytes()?, 1113 sender_id: cursor.read_short_bytes()?, 1114 link_data: decode_queue_link_data(cursor)?, 1115 }) 1116 } 1117 1118 fn encode_protocol_server( 1119 buffer: &mut Vec<u8>, 1120 server: &RadrootsSimplexSmpProtocolServer, 1121 ) -> Result<(), RadrootsSimplexSmpProtoError> { 1122 validate_transport_hosts(&server.hosts)?; 1123 push_short_string_list(buffer, &server.hosts)?; 1124 push_short_string(buffer, &server.port)?; 1125 push_short_bytes(buffer, &server.key_hash) 1126 } 1127 1128 fn decode_protocol_server( 1129 cursor: &mut Cursor<'_>, 1130 ) -> Result<RadrootsSimplexSmpProtocolServer, RadrootsSimplexSmpProtoError> { 1131 let hosts = cursor.read_short_string_list()?; 1132 validate_transport_hosts(&hosts)?; 1133 Ok(RadrootsSimplexSmpProtocolServer { 1134 hosts, 1135 port: cursor.read_short_string_lossy()?, 1136 key_hash: cursor.read_short_bytes()?, 1137 }) 1138 } 1139 1140 fn encode_cert_chain_public_key( 1141 buffer: &mut Vec<u8>, 1142 cert_chain_public_key: &RadrootsSimplexSmpCertChainPublicKey, 1143 ) -> Result<(), RadrootsSimplexSmpProtoError> { 1144 push_large_bytes_list(buffer, &cert_chain_public_key.certificate_chain)?; 1145 push_large_bytes(buffer, &cert_chain_public_key.signed_public_key) 1146 } 1147 1148 fn decode_cert_chain_public_key( 1149 cursor: &mut Cursor<'_>, 1150 ) -> Result<RadrootsSimplexSmpCertChainPublicKey, RadrootsSimplexSmpProtoError> { 1151 Ok(RadrootsSimplexSmpCertChainPublicKey { 1152 certificate_chain: cursor.read_large_bytes_list()?, 1153 signed_public_key: cursor.read_large_bytes()?, 1154 }) 1155 } 1156 1157 fn encode_queue_link_data( 1158 buffer: &mut Vec<u8>, 1159 link_data: &RadrootsSimplexSmpQueueLinkData, 1160 ) -> Result<(), RadrootsSimplexSmpProtoError> { 1161 push_large_bytes(buffer, &link_data.fixed_data)?; 1162 push_large_bytes(buffer, &link_data.user_data) 1163 } 1164 1165 fn decode_queue_link_data( 1166 cursor: &mut Cursor<'_>, 1167 ) -> Result<RadrootsSimplexSmpQueueLinkData, RadrootsSimplexSmpProtoError> { 1168 Ok(RadrootsSimplexSmpQueueLinkData { 1169 fixed_data: cursor.read_large_bytes()?, 1170 user_data: cursor.read_large_bytes()?, 1171 }) 1172 } 1173 1174 fn encode_new_notifier_credentials( 1175 buffer: &mut Vec<u8>, 1176 credentials: &RadrootsSimplexSmpNewNotifierCredentials, 1177 ) -> Result<(), RadrootsSimplexSmpProtoError> { 1178 push_short_bytes(buffer, &credentials.notifier_auth_public_key)?; 1179 push_short_bytes(buffer, &credentials.recipient_notification_dh_public_key) 1180 } 1181 1182 fn decode_new_notifier_credentials( 1183 cursor: &mut Cursor<'_>, 1184 ) -> Result<RadrootsSimplexSmpNewNotifierCredentials, RadrootsSimplexSmpProtoError> { 1185 Ok(RadrootsSimplexSmpNewNotifierCredentials { 1186 notifier_auth_public_key: cursor.read_short_bytes()?, 1187 recipient_notification_dh_public_key: cursor.read_short_bytes()?, 1188 }) 1189 } 1190 1191 fn encode_server_notifier_credentials( 1192 buffer: &mut Vec<u8>, 1193 credentials: &RadrootsSimplexSmpServerNotifierCredentials, 1194 ) -> Result<(), RadrootsSimplexSmpProtoError> { 1195 push_short_bytes(buffer, &credentials.notifier_id)?; 1196 push_short_bytes(buffer, &credentials.server_notification_dh_public_key) 1197 } 1198 1199 fn decode_server_notifier_credentials( 1200 cursor: &mut Cursor<'_>, 1201 ) -> Result<RadrootsSimplexSmpServerNotifierCredentials, RadrootsSimplexSmpProtoError> { 1202 Ok(RadrootsSimplexSmpServerNotifierCredentials { 1203 notifier_id: cursor.read_short_bytes()?, 1204 server_notification_dh_public_key: cursor.read_short_bytes()?, 1205 }) 1206 } 1207 1208 fn encode_queue_mode( 1209 buffer: &mut Vec<u8>, 1210 queue_mode: RadrootsSimplexSmpQueueMode, 1211 ) -> Result<(), RadrootsSimplexSmpProtoError> { 1212 buffer.push(match queue_mode { 1213 RadrootsSimplexSmpQueueMode::Messaging => b'M', 1214 RadrootsSimplexSmpQueueMode::Contact => b'C', 1215 }); 1216 Ok(()) 1217 } 1218 1219 fn decode_queue_mode( 1220 cursor: &mut Cursor<'_>, 1221 ) -> Result<RadrootsSimplexSmpQueueMode, RadrootsSimplexSmpProtoError> { 1222 match cursor.read_byte()? { 1223 b'M' => Ok(RadrootsSimplexSmpQueueMode::Messaging), 1224 b'C' => Ok(RadrootsSimplexSmpQueueMode::Contact), 1225 value => Err(RadrootsSimplexSmpProtoError::InvalidTag( 1226 String::from_utf8_lossy(&[value]).into_owned(), 1227 )), 1228 } 1229 } 1230 1231 fn validate_transport_hosts(hosts: &[String]) -> Result<(), RadrootsSimplexSmpProtoError> { 1232 for host in hosts { 1233 validate_transport_host(host)?; 1234 } 1235 Ok(()) 1236 } 1237 1238 fn validate_transport_host(host: &str) -> Result<(), RadrootsSimplexSmpProtoError> { 1239 if is_valid_ipv4_transport_host(host) 1240 || is_valid_ipv6_transport_host(host) 1241 || is_valid_onion_transport_host(host) 1242 || is_valid_domain_transport_host(host) 1243 { 1244 return Ok(()); 1245 } 1246 Err(RadrootsSimplexSmpProtoError::InvalidHostList( 1247 host.to_string(), 1248 )) 1249 } 1250 1251 fn is_valid_ipv4_transport_host(host: &str) -> bool { 1252 let mut segments = 0_usize; 1253 for segment in host.split('.') { 1254 if segment.is_empty() || !segment.bytes().all(|byte| byte.is_ascii_digit()) { 1255 return false; 1256 } 1257 if segment.parse::<u16>().map_or(true, |value| value > 255) { 1258 return false; 1259 } 1260 segments += 1; 1261 } 1262 segments == 4 1263 } 1264 1265 fn is_valid_ipv6_transport_host(host: &str) -> bool { 1266 let candidate = if let Some(stripped) = host.strip_prefix('[') { 1267 let Some(inner) = stripped.strip_suffix(']') else { 1268 return false; 1269 }; 1270 inner 1271 } else { 1272 if host.ends_with(']') { 1273 return false; 1274 } 1275 host 1276 }; 1277 if candidate.is_empty() 1278 || !candidate 1279 .bytes() 1280 .all(|byte| byte.is_ascii_hexdigit() || byte == b':') 1281 { 1282 return false; 1283 } 1284 Ipv6Addr::from_str(candidate).is_ok() 1285 } 1286 1287 fn is_valid_onion_transport_host(host: &str) -> bool { 1288 let Some(prefix) = host.strip_suffix(".onion") else { 1289 return false; 1290 }; 1291 !prefix.is_empty() 1292 && prefix 1293 .bytes() 1294 .all(|byte| byte.is_ascii_lowercase() || byte.is_ascii_digit()) 1295 } 1296 1297 fn is_valid_domain_transport_host(host: &str) -> bool { 1298 !host.is_empty() 1299 && !host.ends_with(".onion") 1300 && !host.starts_with('[') 1301 && !host.ends_with(']') 1302 && !host.contains(':') 1303 && host 1304 .chars() 1305 .all(|character| !matches!(character, '#' | ',' | ';' | '/' | ' ' | '\n' | '\r' | '\t')) 1306 } 1307 1308 fn encode_transmission( 1309 transport_version: u16, 1310 authorization: &[u8], 1311 correlation_id: Option<RadrootsSimplexSmpCorrelationId>, 1312 entity_id: &[u8], 1313 frame: &[u8], 1314 ) -> Result<Vec<u8>, RadrootsSimplexSmpProtoError> { 1315 let mut buffer = Vec::new(); 1316 push_short_bytes(&mut buffer, authorization)?; 1317 if transport_version >= RADROOTS_SIMPLEX_SMP_SERVICE_CERTS_TRANSPORT_VERSION 1318 && !authorization.is_empty() 1319 { 1320 push_maybe_short_bytes(&mut buffer, None)?; 1321 } 1322 push_short_bytes( 1323 &mut buffer, 1324 correlation_id 1325 .map(|id| id.0.to_vec()) 1326 .as_deref() 1327 .unwrap_or_default(), 1328 )?; 1329 push_short_bytes(&mut buffer, entity_id)?; 1330 buffer.extend_from_slice(frame); 1331 Ok(buffer) 1332 } 1333 1334 fn decode_transmission( 1335 transport_version: u16, 1336 bytes: &[u8], 1337 ) -> Result<RadrootsSimplexSmpDecodedTransmission<'_>, RadrootsSimplexSmpProtoError> { 1338 let mut cursor = Cursor::new(bytes); 1339 let authorization = cursor.read_short_bytes()?; 1340 if transport_version >= RADROOTS_SIMPLEX_SMP_SERVICE_CERTS_TRANSPORT_VERSION 1341 && !authorization.is_empty() 1342 { 1343 let _ = cursor.read_maybe(Cursor::read_short_bytes)?; 1344 } 1345 let correlation_id = match cursor.read_short_bytes()?.as_slice() { 1346 [] => None, 1347 value => Some(RadrootsSimplexSmpCorrelationId::from_slice(value)?), 1348 }; 1349 let entity_id = cursor.read_short_bytes()?; 1350 let frame = cursor.read_remaining(); 1351 if frame.is_empty() { 1352 return Err(RadrootsSimplexSmpProtoError::UnexpectedEof); 1353 } 1354 Ok((authorization, correlation_id, entity_id, frame)) 1355 } 1356 1357 fn decode_send_payload( 1358 payload: &[u8], 1359 ) -> Result<RadrootsSimplexSmpSendCommand, RadrootsSimplexSmpProtoError> { 1360 let Some(space_index) = payload.iter().position(|byte| *byte == b' ') else { 1361 return Err(RadrootsSimplexSmpProtoError::UnexpectedEof); 1362 }; 1363 let flags_bytes = &payload[..space_index]; 1364 if flags_bytes.is_empty() { 1365 return Err(RadrootsSimplexSmpProtoError::MissingField("msg_flags")); 1366 } 1367 let flags = RadrootsSimplexSmpMessageFlags { 1368 notification: decode_bool(flags_bytes[0])?, 1369 reserved: flags_bytes[1..].to_vec(), 1370 }; 1371 Ok(RadrootsSimplexSmpSendCommand { 1372 flags, 1373 message_body: payload[space_index + 1..].to_vec(), 1374 }) 1375 } 1376 1377 fn encode_error(error: &RadrootsSimplexSmpError) -> Result<Vec<u8>, RadrootsSimplexSmpProtoError> { 1378 Ok(match error { 1379 RadrootsSimplexSmpError::Block => b"BLOCK".to_vec(), 1380 RadrootsSimplexSmpError::Session => b"SESSION".to_vec(), 1381 RadrootsSimplexSmpError::Command(command_error) => { 1382 let mut bytes = b"CMD ".to_vec(); 1383 bytes.extend_from_slice(match command_error { 1384 RadrootsSimplexSmpCommandError::Unknown => COMMAND_ERR_UNKNOWN, 1385 RadrootsSimplexSmpCommandError::Syntax => COMMAND_ERR_SYNTAX, 1386 RadrootsSimplexSmpCommandError::Prohibited => COMMAND_ERR_PROHIBITED, 1387 RadrootsSimplexSmpCommandError::NoAuth => COMMAND_ERR_NO_AUTH, 1388 RadrootsSimplexSmpCommandError::HasAuth => COMMAND_ERR_HAS_AUTH, 1389 RadrootsSimplexSmpCommandError::NoEntity => COMMAND_ERR_NO_ENTITY, 1390 RadrootsSimplexSmpCommandError::Other(raw) => raw, 1391 }); 1392 bytes 1393 } 1394 RadrootsSimplexSmpError::Proxy(proxy_error) => { 1395 let mut bytes = b"PROXY ".to_vec(); 1396 bytes.extend_from_slice(&encode_proxy_error(proxy_error)?); 1397 bytes 1398 } 1399 RadrootsSimplexSmpError::Auth => b"AUTH".to_vec(), 1400 RadrootsSimplexSmpError::Blocked(blocking_info) => { 1401 let mut bytes = b"BLOCKED ".to_vec(); 1402 bytes.extend_from_slice(&encode_blocking_info(blocking_info)); 1403 bytes 1404 } 1405 RadrootsSimplexSmpError::Service => b"SERVICE".to_vec(), 1406 RadrootsSimplexSmpError::Crypto => b"CRYPTO".to_vec(), 1407 RadrootsSimplexSmpError::Quota => b"QUOTA".to_vec(), 1408 RadrootsSimplexSmpError::Store(store_error) => { 1409 let mut bytes = b"STORE ".to_vec(); 1410 bytes.extend_from_slice(store_error.as_bytes()); 1411 bytes 1412 } 1413 RadrootsSimplexSmpError::NoMsg => b"NO_MSG".to_vec(), 1414 RadrootsSimplexSmpError::LargeMsg => b"LARGE_MSG".to_vec(), 1415 RadrootsSimplexSmpError::Expired => b"EXPIRED".to_vec(), 1416 RadrootsSimplexSmpError::Internal => b"INTERNAL".to_vec(), 1417 RadrootsSimplexSmpError::Duplicate => b"DUPLICATE_".to_vec(), 1418 RadrootsSimplexSmpError::Other(raw) => raw.clone(), 1419 }) 1420 } 1421 1422 fn decode_error(bytes: &[u8]) -> Result<RadrootsSimplexSmpError, RadrootsSimplexSmpProtoError> { 1423 if bytes == b"BLOCK" { 1424 return Ok(RadrootsSimplexSmpError::Block); 1425 } 1426 if bytes == b"SESSION" { 1427 return Ok(RadrootsSimplexSmpError::Session); 1428 } 1429 if bytes == b"AUTH" { 1430 return Ok(RadrootsSimplexSmpError::Auth); 1431 } 1432 if bytes == b"SERVICE" { 1433 return Ok(RadrootsSimplexSmpError::Service); 1434 } 1435 if bytes == b"CRYPTO" { 1436 return Ok(RadrootsSimplexSmpError::Crypto); 1437 } 1438 if bytes == b"QUOTA" { 1439 return Ok(RadrootsSimplexSmpError::Quota); 1440 } 1441 if let Some(store_error) = bytes.strip_prefix(b"STORE ") { 1442 return Ok(RadrootsSimplexSmpError::Store( 1443 String::from_utf8_lossy(store_error).into_owned(), 1444 )); 1445 } 1446 if bytes == b"NO_MSG" { 1447 return Ok(RadrootsSimplexSmpError::NoMsg); 1448 } 1449 if bytes == b"LARGE_MSG" { 1450 return Ok(RadrootsSimplexSmpError::LargeMsg); 1451 } 1452 if bytes == b"EXPIRED" { 1453 return Ok(RadrootsSimplexSmpError::Expired); 1454 } 1455 if bytes == b"INTERNAL" { 1456 return Ok(RadrootsSimplexSmpError::Internal); 1457 } 1458 if bytes == b"DUPLICATE_" { 1459 return Ok(RadrootsSimplexSmpError::Duplicate); 1460 } 1461 if let Some(command) = bytes.strip_prefix(b"CMD ") { 1462 let command_error = match command { 1463 COMMAND_ERR_UNKNOWN => RadrootsSimplexSmpCommandError::Unknown, 1464 COMMAND_ERR_SYNTAX => RadrootsSimplexSmpCommandError::Syntax, 1465 COMMAND_ERR_PROHIBITED => RadrootsSimplexSmpCommandError::Prohibited, 1466 COMMAND_ERR_NO_AUTH => RadrootsSimplexSmpCommandError::NoAuth, 1467 COMMAND_ERR_HAS_AUTH => RadrootsSimplexSmpCommandError::HasAuth, 1468 COMMAND_ERR_NO_ENTITY | COMMAND_ERR_NO_QUEUE => { 1469 RadrootsSimplexSmpCommandError::NoEntity 1470 } 1471 raw => RadrootsSimplexSmpCommandError::Other(raw.to_vec()), 1472 }; 1473 return Ok(RadrootsSimplexSmpError::Command(command_error)); 1474 } 1475 if let Some(proxy_error) = bytes.strip_prefix(b"PROXY ") { 1476 return Ok(RadrootsSimplexSmpError::Proxy(decode_proxy_error( 1477 proxy_error, 1478 )?)); 1479 } 1480 if let Some(blocking_info) = bytes.strip_prefix(b"BLOCKED ") { 1481 return Ok(RadrootsSimplexSmpError::Blocked(decode_blocking_info( 1482 blocking_info, 1483 )?)); 1484 } 1485 Ok(RadrootsSimplexSmpError::Other(bytes.to_vec())) 1486 } 1487 1488 fn encode_proxy_error( 1489 error: &RadrootsSimplexSmpProxyError, 1490 ) -> Result<Vec<u8>, RadrootsSimplexSmpProtoError> { 1491 Ok(match error { 1492 RadrootsSimplexSmpProxyError::Protocol(error) => { 1493 let mut bytes = b"PROTOCOL ".to_vec(); 1494 bytes.extend_from_slice(&encode_error(error)?); 1495 bytes 1496 } 1497 RadrootsSimplexSmpProxyError::Broker(error) => { 1498 let mut bytes = b"BROKER ".to_vec(); 1499 bytes.extend_from_slice(&encode_broker_error(error)?); 1500 bytes 1501 } 1502 RadrootsSimplexSmpProxyError::BasicAuth => b"BASIC_AUTH".to_vec(), 1503 RadrootsSimplexSmpProxyError::NoSession => b"NO_SESSION".to_vec(), 1504 }) 1505 } 1506 1507 fn decode_proxy_error( 1508 bytes: &[u8], 1509 ) -> Result<RadrootsSimplexSmpProxyError, RadrootsSimplexSmpProtoError> { 1510 let (tag, rest) = parse_tag(bytes)?; 1511 match tag.as_slice() { 1512 b"PROTOCOL" => Ok(RadrootsSimplexSmpProxyError::Protocol(Box::new( 1513 decode_error(rest)?, 1514 ))), 1515 b"BROKER" => Ok(RadrootsSimplexSmpProxyError::Broker(decode_broker_error( 1516 rest, 1517 )?)), 1518 b"BASIC_AUTH" if rest.is_empty() => Ok(RadrootsSimplexSmpProxyError::BasicAuth), 1519 b"NO_SESSION" if rest.is_empty() => Ok(RadrootsSimplexSmpProxyError::NoSession), 1520 _ => Err(invalid_ascii_tag(&tag)), 1521 } 1522 } 1523 1524 fn encode_broker_error( 1525 error: &RadrootsSimplexSmpBrokerError, 1526 ) -> Result<Vec<u8>, RadrootsSimplexSmpProtoError> { 1527 Ok(match error { 1528 RadrootsSimplexSmpBrokerError::Response(response_error) => { 1529 let mut bytes = b"RESPONSE ".to_vec(); 1530 push_short_string(&mut bytes, response_error)?; 1531 bytes 1532 } 1533 RadrootsSimplexSmpBrokerError::Unexpected(response_error) => { 1534 let mut bytes = b"UNEXPECTED ".to_vec(); 1535 push_short_string(&mut bytes, response_error)?; 1536 bytes 1537 } 1538 RadrootsSimplexSmpBrokerError::Network(_) => b"NETWORK".to_vec(), 1539 RadrootsSimplexSmpBrokerError::Host => b"HOST".to_vec(), 1540 RadrootsSimplexSmpBrokerError::NoService => b"NO_SERVICE".to_vec(), 1541 RadrootsSimplexSmpBrokerError::Transport(error) => { 1542 let mut bytes = b"TRANSPORT ".to_vec(); 1543 bytes.extend_from_slice(&encode_transport_error(error)); 1544 bytes 1545 } 1546 RadrootsSimplexSmpBrokerError::Timeout => b"TIMEOUT".to_vec(), 1547 }) 1548 } 1549 1550 fn decode_broker_error( 1551 bytes: &[u8], 1552 ) -> Result<RadrootsSimplexSmpBrokerError, RadrootsSimplexSmpProtoError> { 1553 let (tag, rest) = parse_tag(bytes)?; 1554 match tag.as_slice() { 1555 b"RESPONSE" => Ok(RadrootsSimplexSmpBrokerError::Response( 1556 decode_short_string_lossy(rest)?, 1557 )), 1558 b"UNEXPECTED" => Ok(RadrootsSimplexSmpBrokerError::Unexpected( 1559 decode_short_string_lossy(rest)?, 1560 )), 1561 b"TRANSPORT" => Ok(RadrootsSimplexSmpBrokerError::Transport( 1562 decode_transport_error(rest)?, 1563 )), 1564 b"NETWORK" if rest.is_empty() => Ok(RadrootsSimplexSmpBrokerError::Network( 1565 RadrootsSimplexSmpNetworkError::Failed, 1566 )), 1567 b"NETWORK" => Ok(RadrootsSimplexSmpBrokerError::Network( 1568 decode_network_error(rest)?, 1569 )), 1570 b"TIMEOUT" if rest.is_empty() => Ok(RadrootsSimplexSmpBrokerError::Timeout), 1571 b"HOST" if rest.is_empty() => Ok(RadrootsSimplexSmpBrokerError::Host), 1572 b"NO_SERVICE" if rest.is_empty() => Ok(RadrootsSimplexSmpBrokerError::NoService), 1573 _ => Err(invalid_ascii_tag(&tag)), 1574 } 1575 } 1576 1577 fn encode_transport_error(error: &RadrootsSimplexSmpTransportError) -> Vec<u8> { 1578 match error { 1579 RadrootsSimplexSmpTransportError::Block => b"BLOCK".to_vec(), 1580 RadrootsSimplexSmpTransportError::Version => b"VERSION".to_vec(), 1581 RadrootsSimplexSmpTransportError::LargeMsg => b"LARGE_MSG".to_vec(), 1582 RadrootsSimplexSmpTransportError::Session => b"SESSION".to_vec(), 1583 RadrootsSimplexSmpTransportError::NoAuth => b"NO_AUTH".to_vec(), 1584 RadrootsSimplexSmpTransportError::Handshake(error) => { 1585 let mut bytes = b"HANDSHAKE ".to_vec(); 1586 bytes.extend_from_slice(&encode_handshake_error(error)); 1587 bytes 1588 } 1589 } 1590 } 1591 1592 fn decode_transport_error( 1593 bytes: &[u8], 1594 ) -> Result<RadrootsSimplexSmpTransportError, RadrootsSimplexSmpProtoError> { 1595 let (tag, rest) = parse_tag(bytes)?; 1596 match tag.as_slice() { 1597 b"BLOCK" if rest.is_empty() => Ok(RadrootsSimplexSmpTransportError::Block), 1598 b"VERSION" if rest.is_empty() => Ok(RadrootsSimplexSmpTransportError::Version), 1599 b"LARGE_MSG" if rest.is_empty() => Ok(RadrootsSimplexSmpTransportError::LargeMsg), 1600 b"SESSION" if rest.is_empty() => Ok(RadrootsSimplexSmpTransportError::Session), 1601 b"NO_AUTH" if rest.is_empty() => Ok(RadrootsSimplexSmpTransportError::NoAuth), 1602 b"HANDSHAKE" => Ok(RadrootsSimplexSmpTransportError::Handshake( 1603 decode_handshake_error(rest)?, 1604 )), 1605 _ => Err(invalid_ascii_tag(&tag)), 1606 } 1607 } 1608 1609 #[cfg(test)] 1610 fn encode_network_error(error: &RadrootsSimplexSmpNetworkError) -> Vec<u8> { 1611 match error { 1612 RadrootsSimplexSmpNetworkError::Connect(connect_error) => { 1613 let mut bytes = b"CONNECT ".to_vec(); 1614 push_short_string(&mut bytes, connect_error) 1615 .expect("connect_error length is bounded by SMP short-string encoding"); 1616 bytes 1617 } 1618 RadrootsSimplexSmpNetworkError::Tls(tls_error) => { 1619 let mut bytes = b"TLS ".to_vec(); 1620 push_short_string(&mut bytes, tls_error) 1621 .expect("tls_error length is bounded by SMP short-string encoding"); 1622 bytes 1623 } 1624 RadrootsSimplexSmpNetworkError::UnknownCa => b"UNKNOWNCA".to_vec(), 1625 RadrootsSimplexSmpNetworkError::Failed => b"FAILED".to_vec(), 1626 RadrootsSimplexSmpNetworkError::Timeout => b"TIMEOUT".to_vec(), 1627 RadrootsSimplexSmpNetworkError::Subscribe(subscribe_error) => { 1628 let mut bytes = b"SUBSCRIBE ".to_vec(); 1629 push_short_string(&mut bytes, subscribe_error) 1630 .expect("subscribe_error length is bounded by SMP short-string encoding"); 1631 bytes 1632 } 1633 } 1634 } 1635 1636 fn decode_network_error( 1637 bytes: &[u8], 1638 ) -> Result<RadrootsSimplexSmpNetworkError, RadrootsSimplexSmpProtoError> { 1639 let (tag, rest) = parse_tag(bytes)?; 1640 match tag.as_slice() { 1641 b"CONNECT" => Ok(RadrootsSimplexSmpNetworkError::Connect( 1642 decode_short_string_lossy(rest)?, 1643 )), 1644 b"TLS" => Ok(RadrootsSimplexSmpNetworkError::Tls( 1645 decode_short_string_lossy(rest)?, 1646 )), 1647 b"UNKNOWNCA" if rest.is_empty() => Ok(RadrootsSimplexSmpNetworkError::UnknownCa), 1648 b"FAILED" if rest.is_empty() => Ok(RadrootsSimplexSmpNetworkError::Failed), 1649 b"TIMEOUT" if rest.is_empty() => Ok(RadrootsSimplexSmpNetworkError::Timeout), 1650 b"SUBSCRIBE" => Ok(RadrootsSimplexSmpNetworkError::Subscribe( 1651 decode_short_string_lossy(rest)?, 1652 )), 1653 _ => Err(invalid_ascii_tag(&tag)), 1654 } 1655 } 1656 1657 fn encode_handshake_error(error: &RadrootsSimplexSmpHandshakeError) -> Vec<u8> { 1658 match error { 1659 RadrootsSimplexSmpHandshakeError::Parse => b"PARSE".to_vec(), 1660 RadrootsSimplexSmpHandshakeError::Identity => b"IDENTITY".to_vec(), 1661 RadrootsSimplexSmpHandshakeError::BadAuth => b"BAD_AUTH".to_vec(), 1662 RadrootsSimplexSmpHandshakeError::BadService => b"BAD_SERVICE".to_vec(), 1663 RadrootsSimplexSmpHandshakeError::Other(raw) => raw.as_bytes().to_vec(), 1664 } 1665 } 1666 1667 fn decode_handshake_error( 1668 bytes: &[u8], 1669 ) -> Result<RadrootsSimplexSmpHandshakeError, RadrootsSimplexSmpProtoError> { 1670 match bytes { 1671 b"PARSE" => Ok(RadrootsSimplexSmpHandshakeError::Parse), 1672 b"IDENTITY" => Ok(RadrootsSimplexSmpHandshakeError::Identity), 1673 b"BAD_AUTH" => Ok(RadrootsSimplexSmpHandshakeError::BadAuth), 1674 b"BAD_SERVICE" => Ok(RadrootsSimplexSmpHandshakeError::BadService), 1675 raw => Err(invalid_ascii_tag(raw)), 1676 } 1677 } 1678 1679 fn encode_blocking_info(info: &RadrootsSimplexSmpBlockingInfo) -> Vec<u8> { 1680 let mut bytes = b"reason=".to_vec(); 1681 bytes.extend_from_slice(match &info.reason { 1682 RadrootsSimplexSmpBlockingReason::Spam => b"spam", 1683 RadrootsSimplexSmpBlockingReason::Content => b"content", 1684 RadrootsSimplexSmpBlockingReason::Other(reason) => reason.as_bytes(), 1685 }); 1686 bytes 1687 } 1688 1689 fn decode_blocking_info( 1690 bytes: &[u8], 1691 ) -> Result<RadrootsSimplexSmpBlockingInfo, RadrootsSimplexSmpProtoError> { 1692 let Some(reason) = bytes.strip_prefix(b"reason=") else { 1693 return Err(invalid_ascii_tag(bytes)); 1694 }; 1695 let reason = match reason { 1696 b"spam" => RadrootsSimplexSmpBlockingReason::Spam, 1697 b"content" => RadrootsSimplexSmpBlockingReason::Content, 1698 raw => return Err(invalid_ascii_tag(raw)), 1699 }; 1700 Ok(RadrootsSimplexSmpBlockingInfo { reason }) 1701 } 1702 1703 fn decode_short_string_lossy(bytes: &[u8]) -> Result<String, RadrootsSimplexSmpProtoError> { 1704 let mut cursor = Cursor::new(bytes); 1705 let value = cursor.read_short_string_lossy()?; 1706 if !cursor.is_empty() { 1707 return Err(RadrootsSimplexSmpProtoError::TrailingBytes); 1708 } 1709 Ok(value) 1710 } 1711 1712 fn invalid_ascii_tag(bytes: &[u8]) -> RadrootsSimplexSmpProtoError { 1713 RadrootsSimplexSmpProtoError::InvalidTag(String::from_utf8_lossy(bytes).into_owned()) 1714 } 1715 1716 fn parse_tag(bytes: &[u8]) -> Result<(Vec<u8>, &[u8]), RadrootsSimplexSmpProtoError> { 1717 if bytes.is_empty() { 1718 return Err(RadrootsSimplexSmpProtoError::UnexpectedEof); 1719 } 1720 if let Some(space_index) = bytes.iter().position(|byte| *byte == b' ') { 1721 Ok((bytes[..space_index].to_vec(), &bytes[space_index + 1..])) 1722 } else { 1723 Ok((bytes.to_vec(), &[])) 1724 } 1725 } 1726 1727 fn encode_subscription_mode(mode: RadrootsSimplexSmpSubscriptionMode) -> u8 { 1728 match mode { 1729 RadrootsSimplexSmpSubscriptionMode::Subscribe => b'S', 1730 RadrootsSimplexSmpSubscriptionMode::OnlyCreate => b'C', 1731 } 1732 } 1733 1734 fn decode_subscription_mode( 1735 value: u8, 1736 ) -> Result<RadrootsSimplexSmpSubscriptionMode, RadrootsSimplexSmpProtoError> { 1737 match value { 1738 b'S' => Ok(RadrootsSimplexSmpSubscriptionMode::Subscribe), 1739 b'C' => Ok(RadrootsSimplexSmpSubscriptionMode::OnlyCreate), 1740 _ => Err(RadrootsSimplexSmpProtoError::InvalidTag( 1741 String::from_utf8_lossy(&[value]).into_owned(), 1742 )), 1743 } 1744 } 1745 1746 fn encode_bool(value: bool) -> u8 { 1747 if value { b'T' } else { b'F' } 1748 } 1749 1750 fn decode_bool(value: u8) -> Result<bool, RadrootsSimplexSmpProtoError> { 1751 match value { 1752 b'T' => Ok(true), 1753 b'F' => Ok(false), 1754 other => Err(RadrootsSimplexSmpProtoError::InvalidBoolEncoding(other)), 1755 } 1756 } 1757 1758 fn push_i64(buffer: &mut Vec<u8>, value: i64) { 1759 buffer.extend_from_slice(&value.to_be_bytes()); 1760 } 1761 1762 fn push_short_bytes( 1763 buffer: &mut Vec<u8>, 1764 bytes: &[u8], 1765 ) -> Result<(), RadrootsSimplexSmpProtoError> { 1766 let len = u8::try_from(bytes.len()) 1767 .map_err(|_| RadrootsSimplexSmpProtoError::InvalidShortFieldLength(bytes.len()))?; 1768 buffer.push(len); 1769 buffer.extend_from_slice(bytes); 1770 Ok(()) 1771 } 1772 1773 fn push_short_string( 1774 buffer: &mut Vec<u8>, 1775 value: &str, 1776 ) -> Result<(), RadrootsSimplexSmpProtoError> { 1777 push_short_bytes(buffer, value.as_bytes()) 1778 } 1779 1780 fn push_large_bytes( 1781 buffer: &mut Vec<u8>, 1782 bytes: &[u8], 1783 ) -> Result<(), RadrootsSimplexSmpProtoError> { 1784 let len = u16::try_from(bytes.len()) 1785 .map_err(|_| RadrootsSimplexSmpProtoError::InvalidLargeFieldLength(bytes.len()))?; 1786 buffer.extend_from_slice(&len.to_be_bytes()); 1787 buffer.extend_from_slice(bytes); 1788 Ok(()) 1789 } 1790 1791 fn push_short_key_list( 1792 buffer: &mut Vec<u8>, 1793 keys: &RadrootsSimplexSmpKeyList, 1794 ) -> Result<(), RadrootsSimplexSmpProtoError> { 1795 let len = 1 + keys.rest.len(); 1796 let len = 1797 u8::try_from(len).map_err(|_| RadrootsSimplexSmpProtoError::InvalidListLength(len))?; 1798 buffer.push(len); 1799 push_short_bytes(buffer, &keys.first)?; 1800 for key in &keys.rest { 1801 push_short_bytes(buffer, key)?; 1802 } 1803 Ok(()) 1804 } 1805 1806 fn push_short_string_list( 1807 buffer: &mut Vec<u8>, 1808 values: &[String], 1809 ) -> Result<(), RadrootsSimplexSmpProtoError> { 1810 if values.is_empty() { 1811 return Err(RadrootsSimplexSmpProtoError::InvalidListLength(0)); 1812 } 1813 let len = u8::try_from(values.len()) 1814 .map_err(|_| RadrootsSimplexSmpProtoError::InvalidListLength(values.len()))?; 1815 buffer.push(len); 1816 for value in values { 1817 push_short_string(buffer, value)?; 1818 } 1819 Ok(()) 1820 } 1821 1822 fn push_large_bytes_list( 1823 buffer: &mut Vec<u8>, 1824 values: &[Vec<u8>], 1825 ) -> Result<(), RadrootsSimplexSmpProtoError> { 1826 if values.is_empty() { 1827 return Err(RadrootsSimplexSmpProtoError::InvalidListLength(0)); 1828 } 1829 let len = u8::try_from(values.len()) 1830 .map_err(|_| RadrootsSimplexSmpProtoError::InvalidListLength(values.len()))?; 1831 buffer.push(len); 1832 for value in values { 1833 push_large_bytes(buffer, value)?; 1834 } 1835 Ok(()) 1836 } 1837 1838 fn push_maybe<T, F>( 1839 buffer: &mut Vec<u8>, 1840 value: Option<T>, 1841 mut encode: F, 1842 ) -> Result<(), RadrootsSimplexSmpProtoError> 1843 where 1844 T: Copy, 1845 F: FnMut(&mut Vec<u8>, T) -> Result<(), RadrootsSimplexSmpProtoError>, 1846 { 1847 match value { 1848 None => { 1849 buffer.push(b'0'); 1850 Ok(()) 1851 } 1852 Some(value) => { 1853 buffer.push(b'1'); 1854 encode(buffer, value) 1855 } 1856 } 1857 } 1858 1859 fn push_maybe_short_bytes( 1860 buffer: &mut Vec<u8>, 1861 value: Option<&[u8]>, 1862 ) -> Result<(), RadrootsSimplexSmpProtoError> { 1863 push_maybe(buffer, value, push_short_bytes) 1864 } 1865 1866 fn push_maybe_string( 1867 buffer: &mut Vec<u8>, 1868 value: Option<&str>, 1869 ) -> Result<(), RadrootsSimplexSmpProtoError> { 1870 match value { 1871 None => { 1872 buffer.push(b'0'); 1873 Ok(()) 1874 } 1875 Some(value) => { 1876 validate_basic_auth(value)?; 1877 buffer.push(b'1'); 1878 push_short_bytes(buffer, value.as_bytes()) 1879 } 1880 } 1881 } 1882 1883 fn push_legacy_basic_auth( 1884 buffer: &mut Vec<u8>, 1885 value: Option<&str>, 1886 ) -> Result<(), RadrootsSimplexSmpProtoError> { 1887 match value { 1888 None => Ok(()), 1889 Some(value) => { 1890 validate_basic_auth(value)?; 1891 buffer.push(b'A'); 1892 push_short_bytes(buffer, value.as_bytes()) 1893 } 1894 } 1895 } 1896 1897 fn validate_basic_auth(value: &str) -> Result<(), RadrootsSimplexSmpProtoError> { 1898 if value 1899 .bytes() 1900 .all(|byte| byte.is_ascii_graphic() && byte != b'@' && byte != b':' && byte != b'/') 1901 { 1902 Ok(()) 1903 } else { 1904 Err(RadrootsSimplexSmpProtoError::InvalidUri(value.to_string())) 1905 } 1906 } 1907 1908 struct Cursor<'a> { 1909 bytes: &'a [u8], 1910 offset: usize, 1911 } 1912 1913 impl<'a> Cursor<'a> { 1914 const fn new(bytes: &'a [u8]) -> Self { 1915 Self { bytes, offset: 0 } 1916 } 1917 1918 fn is_empty(&self) -> bool { 1919 self.offset >= self.bytes.len() 1920 } 1921 1922 fn remaining_len(&self) -> usize { 1923 self.bytes.len().saturating_sub(self.offset) 1924 } 1925 1926 fn read_byte(&mut self) -> Result<u8, RadrootsSimplexSmpProtoError> { 1927 let byte = *self 1928 .bytes 1929 .get(self.offset) 1930 .ok_or(RadrootsSimplexSmpProtoError::UnexpectedEof)?; 1931 self.offset += 1; 1932 Ok(byte) 1933 } 1934 1935 fn read_exact(&mut self, len: usize) -> Result<&'a [u8], RadrootsSimplexSmpProtoError> { 1936 let end = self.offset + len; 1937 let value = self 1938 .bytes 1939 .get(self.offset..end) 1940 .ok_or(RadrootsSimplexSmpProtoError::UnexpectedEof)?; 1941 self.offset = end; 1942 Ok(value) 1943 } 1944 1945 fn read_array<const N: usize>(&mut self) -> Result<[u8; N], RadrootsSimplexSmpProtoError> { 1946 let mut array = [0_u8; N]; 1947 array.copy_from_slice(self.read_exact(N)?); 1948 Ok(array) 1949 } 1950 1951 fn read_short_bytes(&mut self) -> Result<Vec<u8>, RadrootsSimplexSmpProtoError> { 1952 let len = usize::from(self.read_byte()?); 1953 Ok(self.read_exact(len)?.to_vec()) 1954 } 1955 1956 fn read_short_string(&mut self) -> Result<String, RadrootsSimplexSmpProtoError> { 1957 String::from_utf8(self.read_short_bytes()?) 1958 .map_err(|error| RadrootsSimplexSmpProtoError::InvalidUtf8(error.to_string())) 1959 } 1960 1961 fn read_short_string_lossy(&mut self) -> Result<String, RadrootsSimplexSmpProtoError> { 1962 Ok(String::from_utf8_lossy(&self.read_short_bytes()?).into_owned()) 1963 } 1964 1965 fn read_short_key_list( 1966 &mut self, 1967 ) -> Result<RadrootsSimplexSmpKeyList, RadrootsSimplexSmpProtoError> { 1968 let len = usize::from(self.read_byte()?); 1969 if len == 0 { 1970 return Err(RadrootsSimplexSmpProtoError::InvalidListLength(0)); 1971 } 1972 let first = self.read_short_bytes()?; 1973 let mut rest = Vec::with_capacity(len.saturating_sub(1)); 1974 for _ in 1..len { 1975 rest.push(self.read_short_bytes()?); 1976 } 1977 Ok(RadrootsSimplexSmpKeyList { first, rest }) 1978 } 1979 1980 fn read_short_string_list(&mut self) -> Result<Vec<String>, RadrootsSimplexSmpProtoError> { 1981 let len = usize::from(self.read_byte()?); 1982 if len == 0 { 1983 return Err(RadrootsSimplexSmpProtoError::InvalidListLength(0)); 1984 } 1985 let mut values = Vec::with_capacity(len); 1986 for _ in 0..len { 1987 values.push(self.read_short_string()?); 1988 } 1989 Ok(values) 1990 } 1991 1992 fn read_large_bytes(&mut self) -> Result<Vec<u8>, RadrootsSimplexSmpProtoError> { 1993 let len = usize::from(u16::from_be_bytes(self.read_array::<2>()?)); 1994 Ok(self.read_exact(len)?.to_vec()) 1995 } 1996 1997 fn read_large_bytes_list(&mut self) -> Result<Vec<Vec<u8>>, RadrootsSimplexSmpProtoError> { 1998 let len = usize::from(self.read_byte()?); 1999 if len == 0 { 2000 return Err(RadrootsSimplexSmpProtoError::InvalidListLength(0)); 2001 } 2002 let mut values = Vec::with_capacity(len); 2003 for _ in 0..len { 2004 values.push(self.read_large_bytes()?); 2005 } 2006 Ok(values) 2007 } 2008 2009 fn read_i64(&mut self) -> Result<i64, RadrootsSimplexSmpProtoError> { 2010 Ok(i64::from_be_bytes(self.read_array::<8>()?)) 2011 } 2012 2013 fn read_maybe_string(&mut self) -> Result<Option<String>, RadrootsSimplexSmpProtoError> { 2014 self.read_maybe(|cursor| { 2015 let value = cursor.read_short_bytes()?; 2016 let string = String::from_utf8(value) 2017 .map_err(|error| RadrootsSimplexSmpProtoError::InvalidUtf8(error.to_string()))?; 2018 validate_basic_auth(&string)?; 2019 Ok(string) 2020 }) 2021 } 2022 2023 fn read_legacy_basic_auth(&mut self) -> Result<Option<String>, RadrootsSimplexSmpProtoError> { 2024 match self.bytes.get(self.offset).copied() { 2025 Some(b'A') => { 2026 self.offset += 1; 2027 let value = self.read_short_bytes()?; 2028 let string = String::from_utf8(value).map_err(|error| { 2029 RadrootsSimplexSmpProtoError::InvalidUtf8(error.to_string()) 2030 })?; 2031 validate_basic_auth(&string)?; 2032 Ok(Some(string)) 2033 } 2034 Some(_) => Ok(None), 2035 None => Err(RadrootsSimplexSmpProtoError::UnexpectedEof), 2036 } 2037 } 2038 2039 fn read_maybe<T, F>(&mut self, decode: F) -> Result<Option<T>, RadrootsSimplexSmpProtoError> 2040 where 2041 F: FnOnce(&mut Self) -> Result<T, RadrootsSimplexSmpProtoError>, 2042 { 2043 match self.read_byte()? { 2044 b'0' => Ok(None), 2045 b'1' => Ok(Some(decode(self)?)), 2046 other => Err(RadrootsSimplexSmpProtoError::InvalidMaybeTag(other)), 2047 } 2048 } 2049 2050 fn read_remaining(&mut self) -> &'a [u8] { 2051 let remaining = &self.bytes[self.offset..]; 2052 self.offset = self.bytes.len(); 2053 remaining 2054 } 2055 } 2056 2057 #[cfg(test)] 2058 mod tests { 2059 use super::*; 2060 2061 fn correlation_id(byte: u8) -> RadrootsSimplexSmpCorrelationId { 2062 RadrootsSimplexSmpCorrelationId::new([byte; 24]) 2063 } 2064 2065 #[test] 2066 fn round_trips_current_new_command_transmission() { 2067 let transmission = RadrootsSimplexSmpCommandTransmission { 2068 authorization: vec![1, 2, 3], 2069 correlation_id: Some(correlation_id(7)), 2070 entity_id: Vec::new(), 2071 command: RadrootsSimplexSmpCommand::New(RadrootsSimplexSmpNewQueueRequest { 2072 recipient_auth_public_key: vec![0x01, 0x02, 0x03], 2073 recipient_dh_public_key: vec![0x04, 0x05], 2074 basic_auth: Some("server-pass".to_string()), 2075 subscription_mode: RadrootsSimplexSmpSubscriptionMode::Subscribe, 2076 queue_request_data: Some(RadrootsSimplexSmpQueueRequestData::Messaging(Some( 2077 RadrootsSimplexSmpMessagingQueueRequest { 2078 sender_id: vec![0x10, 0x11], 2079 link_data: RadrootsSimplexSmpQueueLinkData { 2080 fixed_data: vec![0xaa, 0xbb], 2081 user_data: vec![0xcc, 0xdd, 0xee], 2082 }, 2083 }, 2084 ))), 2085 notifier_credentials: Some(RadrootsSimplexSmpNewNotifierCredentials { 2086 notifier_auth_public_key: vec![0x21, 0x22], 2087 recipient_notification_dh_public_key: vec![0x23, 0x24], 2088 }), 2089 }), 2090 }; 2091 2092 let encoded = transmission.encode().unwrap(); 2093 let decoded = RadrootsSimplexSmpCommandTransmission::decode(&encoded).unwrap(); 2094 assert_eq!(decoded, transmission); 2095 } 2096 2097 #[test] 2098 fn round_trips_v9_new_command_transmission() { 2099 let transmission = RadrootsSimplexSmpCommandTransmission { 2100 authorization: vec![1, 2, 3], 2101 correlation_id: Some(correlation_id(7)), 2102 entity_id: Vec::new(), 2103 command: RadrootsSimplexSmpCommand::New(RadrootsSimplexSmpNewQueueRequest { 2104 recipient_auth_public_key: vec![0x01, 0x02, 0x03], 2105 recipient_dh_public_key: vec![0x04, 0x05], 2106 basic_auth: Some("server-pass".to_string()), 2107 subscription_mode: RadrootsSimplexSmpSubscriptionMode::Subscribe, 2108 queue_request_data: Some(RadrootsSimplexSmpQueueRequestData::Messaging(None)), 2109 notifier_credentials: None, 2110 }), 2111 }; 2112 2113 let encoded = transmission 2114 .encode_for_version(RADROOTS_SIMPLEX_SMP_SENDER_AUTH_KEY_TRANSPORT_VERSION) 2115 .unwrap(); 2116 let decoded = RadrootsSimplexSmpCommandTransmission::decode_for_version( 2117 RADROOTS_SIMPLEX_SMP_SENDER_AUTH_KEY_TRANSPORT_VERSION, 2118 &encoded, 2119 ) 2120 .unwrap(); 2121 assert_eq!(decoded, transmission); 2122 } 2123 2124 #[test] 2125 fn round_trips_v6_new_command_transmission() { 2126 let transmission = RadrootsSimplexSmpCommandTransmission { 2127 authorization: vec![1, 2, 3], 2128 correlation_id: Some(correlation_id(7)), 2129 entity_id: Vec::new(), 2130 command: RadrootsSimplexSmpCommand::New(RadrootsSimplexSmpNewQueueRequest { 2131 recipient_auth_public_key: vec![0x01, 0x02, 0x03], 2132 recipient_dh_public_key: vec![0x04, 0x05], 2133 basic_auth: Some("server-pass".to_string()), 2134 subscription_mode: RadrootsSimplexSmpSubscriptionMode::Subscribe, 2135 queue_request_data: None, 2136 notifier_credentials: None, 2137 }), 2138 }; 2139 2140 let encoded = transmission 2141 .encode_for_version(RADROOTS_SIMPLEX_SMP_INITIAL_TRANSPORT_VERSION) 2142 .unwrap(); 2143 let decoded = RadrootsSimplexSmpCommandTransmission::decode_for_version( 2144 RADROOTS_SIMPLEX_SMP_INITIAL_TRANSPORT_VERSION, 2145 &encoded, 2146 ) 2147 .unwrap(); 2148 assert_eq!(decoded, transmission); 2149 } 2150 2151 #[test] 2152 fn round_trips_send_command_transmission() { 2153 let transmission = RadrootsSimplexSmpCommandTransmission { 2154 authorization: Vec::new(), 2155 correlation_id: Some(correlation_id(9)), 2156 entity_id: vec![0xaa, 0xbb], 2157 command: RadrootsSimplexSmpCommand::Send(RadrootsSimplexSmpSendCommand { 2158 flags: RadrootsSimplexSmpMessageFlags { 2159 notification: true, 2160 reserved: b"0".to_vec(), 2161 }, 2162 message_body: vec![0xde, 0xad, 0xbe, 0xef], 2163 }), 2164 }; 2165 2166 let encoded = transmission.encode().unwrap(); 2167 let decoded = RadrootsSimplexSmpCommandTransmission::decode(&encoded).unwrap(); 2168 assert_eq!(decoded, transmission); 2169 } 2170 2171 #[test] 2172 fn round_trips_v15_new_command_transmission() { 2173 let transmission = RadrootsSimplexSmpCommandTransmission { 2174 authorization: vec![1, 2, 3], 2175 correlation_id: Some(correlation_id(7)), 2176 entity_id: Vec::new(), 2177 command: RadrootsSimplexSmpCommand::New(RadrootsSimplexSmpNewQueueRequest { 2178 recipient_auth_public_key: vec![0x01, 0x02, 0x03], 2179 recipient_dh_public_key: vec![0x04, 0x05], 2180 basic_auth: Some("server-pass".to_string()), 2181 subscription_mode: RadrootsSimplexSmpSubscriptionMode::Subscribe, 2182 queue_request_data: Some(RadrootsSimplexSmpQueueRequestData::Messaging(Some( 2183 RadrootsSimplexSmpMessagingQueueRequest { 2184 sender_id: vec![0x10, 0x11], 2185 link_data: RadrootsSimplexSmpQueueLinkData { 2186 fixed_data: vec![0xaa, 0xbb], 2187 user_data: vec![0xcc, 0xdd, 0xee], 2188 }, 2189 }, 2190 ))), 2191 notifier_credentials: None, 2192 }), 2193 }; 2194 2195 let encoded = transmission 2196 .encode_for_version(RADROOTS_SIMPLEX_SMP_SHORT_LINKS_TRANSPORT_VERSION) 2197 .unwrap(); 2198 let decoded = RadrootsSimplexSmpCommandTransmission::decode_for_version( 2199 RADROOTS_SIMPLEX_SMP_SHORT_LINKS_TRANSPORT_VERSION, 2200 &encoded, 2201 ) 2202 .unwrap(); 2203 assert_eq!(decoded, transmission); 2204 } 2205 2206 #[test] 2207 fn current_authenticated_transmission_encodes_absent_service_signature_as_maybe_none() { 2208 let transmission = RadrootsSimplexSmpCommandTransmission { 2209 authorization: vec![1, 2, 3], 2210 correlation_id: Some(correlation_id(7)), 2211 entity_id: Vec::new(), 2212 command: RadrootsSimplexSmpCommand::Ping, 2213 }; 2214 2215 let encoded = transmission.encode().unwrap(); 2216 assert_eq!(encoded[0], 3); 2217 assert_eq!(&encoded[1..4], &[1, 2, 3]); 2218 assert_eq!(encoded[4], b'0'); 2219 2220 let decoded = RadrootsSimplexSmpCommandTransmission::decode(&encoded).unwrap(); 2221 assert_eq!(decoded, transmission); 2222 } 2223 2224 #[test] 2225 fn round_trips_current_ids_broker_transmission() { 2226 let transmission = RadrootsSimplexSmpBrokerTransmission { 2227 authorization: Vec::new(), 2228 correlation_id: Some(correlation_id(3)), 2229 entity_id: Vec::new(), 2230 message: RadrootsSimplexSmpBrokerMessage::Ids(RadrootsSimplexSmpQueueIdsResponse { 2231 recipient_id: vec![0x10], 2232 sender_id: vec![0x11], 2233 server_dh_public_key: vec![0x12, 0x13], 2234 queue_mode: Some(RadrootsSimplexSmpQueueMode::Messaging), 2235 link_id: Some(vec![0x14, 0x15]), 2236 service_id: Some(vec![0x16, 0x17]), 2237 server_notification_credentials: Some( 2238 RadrootsSimplexSmpServerNotifierCredentials { 2239 notifier_id: vec![0x18, 0x19], 2240 server_notification_dh_public_key: vec![0x1a, 0x1b], 2241 }, 2242 ), 2243 }), 2244 }; 2245 2246 let encoded = transmission.encode().unwrap(); 2247 let decoded = RadrootsSimplexSmpBrokerTransmission::decode(&encoded).unwrap(); 2248 assert_eq!(decoded, transmission); 2249 } 2250 2251 #[test] 2252 fn round_trips_v9_ids_broker_transmission() { 2253 let transmission = RadrootsSimplexSmpBrokerTransmission { 2254 authorization: Vec::new(), 2255 correlation_id: Some(correlation_id(3)), 2256 entity_id: Vec::new(), 2257 message: RadrootsSimplexSmpBrokerMessage::Ids(RadrootsSimplexSmpQueueIdsResponse { 2258 recipient_id: vec![0x10], 2259 sender_id: vec![0x11], 2260 server_dh_public_key: vec![0x12, 0x13], 2261 queue_mode: Some(RadrootsSimplexSmpQueueMode::Messaging), 2262 link_id: None, 2263 service_id: None, 2264 server_notification_credentials: None, 2265 }), 2266 }; 2267 2268 let encoded = transmission 2269 .encode_for_version(RADROOTS_SIMPLEX_SMP_SENDER_AUTH_KEY_TRANSPORT_VERSION) 2270 .unwrap(); 2271 let decoded = RadrootsSimplexSmpBrokerTransmission::decode_for_version( 2272 RADROOTS_SIMPLEX_SMP_SENDER_AUTH_KEY_TRANSPORT_VERSION, 2273 &encoded, 2274 ) 2275 .unwrap(); 2276 assert_eq!(decoded, transmission); 2277 } 2278 2279 #[test] 2280 fn round_trips_error_broker_transmission() { 2281 let transmission = RadrootsSimplexSmpBrokerTransmission { 2282 authorization: Vec::new(), 2283 correlation_id: Some(correlation_id(5)), 2284 entity_id: vec![0x01], 2285 message: RadrootsSimplexSmpBrokerMessage::Err(RadrootsSimplexSmpError::Command( 2286 RadrootsSimplexSmpCommandError::Prohibited, 2287 )), 2288 }; 2289 2290 let encoded = transmission.encode().unwrap(); 2291 let decoded = RadrootsSimplexSmpBrokerTransmission::decode(&encoded).unwrap(); 2292 assert_eq!(decoded, transmission); 2293 } 2294 2295 #[test] 2296 fn round_trips_message_notification() { 2297 let transmission = RadrootsSimplexSmpBrokerTransmission { 2298 authorization: Vec::new(), 2299 correlation_id: None, 2300 entity_id: vec![0x99], 2301 message: RadrootsSimplexSmpBrokerMessage::NMsg { 2302 nonce: [0x22; 24], 2303 encrypted_metadata: vec![0x33, 0x44, 0x55], 2304 }, 2305 }; 2306 2307 let encoded = transmission.encode().unwrap(); 2308 let decoded = RadrootsSimplexSmpBrokerTransmission::decode(&encoded).unwrap(); 2309 assert_eq!(decoded, transmission); 2310 } 2311 2312 #[test] 2313 fn v6_new_command_uses_legacy_basic_auth_layout() { 2314 let command = RadrootsSimplexSmpCommand::New(RadrootsSimplexSmpNewQueueRequest { 2315 recipient_auth_public_key: vec![0x01, 0x02, 0x03], 2316 recipient_dh_public_key: vec![0x04, 0x05], 2317 basic_auth: Some("server-pass".to_string()), 2318 subscription_mode: RadrootsSimplexSmpSubscriptionMode::Subscribe, 2319 queue_request_data: Some(RadrootsSimplexSmpQueueRequestData::Messaging(None)), 2320 notifier_credentials: Some(RadrootsSimplexSmpNewNotifierCredentials { 2321 notifier_auth_public_key: vec![0x21, 0x22], 2322 recipient_notification_dh_public_key: vec![0x23, 0x24], 2323 }), 2324 }); 2325 2326 let encoded = command 2327 .encode_for_version(RADROOTS_SIMPLEX_SMP_INITIAL_TRANSPORT_VERSION) 2328 .unwrap(); 2329 2330 assert_eq!( 2331 encoded, 2332 b"NEW \x03\x01\x02\x03\x02\x04\x05A\x0bserver-passS".to_vec() 2333 ); 2334 } 2335 2336 #[test] 2337 fn v9_new_matches_official_sender_secure_layout() { 2338 let command = RadrootsSimplexSmpCommand::New(RadrootsSimplexSmpNewQueueRequest { 2339 recipient_auth_public_key: vec![0x01, 0x02, 0x03], 2340 recipient_dh_public_key: vec![0x04, 0x05], 2341 basic_auth: Some("server-pass".to_string()), 2342 subscription_mode: RadrootsSimplexSmpSubscriptionMode::Subscribe, 2343 queue_request_data: Some(RadrootsSimplexSmpQueueRequestData::Messaging(None)), 2344 notifier_credentials: None, 2345 }); 2346 2347 let encoded = command 2348 .encode_for_version(RADROOTS_SIMPLEX_SMP_SENDER_AUTH_KEY_TRANSPORT_VERSION) 2349 .unwrap(); 2350 2351 assert_eq!( 2352 encoded, 2353 b"NEW \x03\x01\x02\x03\x02\x04\x051\x0bserver-passST".to_vec() 2354 ); 2355 } 2356 2357 #[test] 2358 fn v15_new_matches_official_short_link_layout() { 2359 let command = RadrootsSimplexSmpCommand::New(RadrootsSimplexSmpNewQueueRequest { 2360 recipient_auth_public_key: vec![0x01, 0x02, 0x03], 2361 recipient_dh_public_key: vec![0x04, 0x05], 2362 basic_auth: Some("server-pass".to_string()), 2363 subscription_mode: RadrootsSimplexSmpSubscriptionMode::Subscribe, 2364 queue_request_data: Some(RadrootsSimplexSmpQueueRequestData::Messaging(Some( 2365 RadrootsSimplexSmpMessagingQueueRequest { 2366 sender_id: vec![0x10, 0x11], 2367 link_data: RadrootsSimplexSmpQueueLinkData { 2368 fixed_data: vec![0xaa, 0xbb], 2369 user_data: vec![0xcc, 0xdd, 0xee], 2370 }, 2371 }, 2372 ))), 2373 notifier_credentials: Some(RadrootsSimplexSmpNewNotifierCredentials { 2374 notifier_auth_public_key: vec![0x21, 0x22], 2375 recipient_notification_dh_public_key: vec![0x23, 0x24], 2376 }), 2377 }); 2378 2379 let encoded = command 2380 .encode_for_version(RADROOTS_SIMPLEX_SMP_SHORT_LINKS_TRANSPORT_VERSION) 2381 .unwrap(); 2382 2383 assert_eq!( 2384 encoded, 2385 b"NEW \x03\x01\x02\x03\x02\x04\x051\x0bserver-passS1M1\x02\x10\x11\x00\x02\xaa\xbb\x00\x03\xcc\xdd\xee" 2386 .to_vec() 2387 ); 2388 } 2389 2390 #[test] 2391 fn v17_ids_matches_official_notifier_layout() { 2392 let response = RadrootsSimplexSmpBrokerMessage::Ids(RadrootsSimplexSmpQueueIdsResponse { 2393 recipient_id: vec![0x10], 2394 sender_id: vec![0x11], 2395 server_dh_public_key: vec![0x12, 0x13], 2396 queue_mode: Some(RadrootsSimplexSmpQueueMode::Messaging), 2397 link_id: Some(vec![0x14, 0x15]), 2398 service_id: Some(vec![0x16, 0x17]), 2399 server_notification_credentials: Some(RadrootsSimplexSmpServerNotifierCredentials { 2400 notifier_id: vec![0x18, 0x19], 2401 server_notification_dh_public_key: vec![0x1a, 0x1b], 2402 }), 2403 }); 2404 2405 let encoded = response.encode().unwrap(); 2406 2407 assert_eq!( 2408 encoded, 2409 b"IDS \x01\x10\x01\x11\x02\x12\x131M1\x02\x14\x151\x02\x16\x171\x02\x18\x19\x02\x1a\x1b" 2410 .to_vec() 2411 ); 2412 } 2413 2414 #[test] 2415 fn v15_ids_matches_official_short_link_layout() { 2416 let response = RadrootsSimplexSmpBrokerMessage::Ids(RadrootsSimplexSmpQueueIdsResponse { 2417 recipient_id: vec![0x10], 2418 sender_id: vec![0x11], 2419 server_dh_public_key: vec![0x12, 0x13], 2420 queue_mode: Some(RadrootsSimplexSmpQueueMode::Messaging), 2421 link_id: Some(vec![0x14, 0x15]), 2422 service_id: Some(vec![0x16, 0x17]), 2423 server_notification_credentials: None, 2424 }); 2425 2426 let encoded = response 2427 .encode_for_version(RADROOTS_SIMPLEX_SMP_SHORT_LINKS_TRANSPORT_VERSION) 2428 .unwrap(); 2429 2430 assert_eq!( 2431 encoded, 2432 b"IDS \x01\x10\x01\x11\x02\x12\x131M1\x02\x14\x15".to_vec() 2433 ); 2434 } 2435 2436 #[test] 2437 fn v9_ids_matches_official_sender_secure_layout() { 2438 let response = RadrootsSimplexSmpBrokerMessage::Ids(RadrootsSimplexSmpQueueIdsResponse { 2439 recipient_id: vec![0x10], 2440 sender_id: vec![0x11], 2441 server_dh_public_key: vec![0x12, 0x13], 2442 queue_mode: Some(RadrootsSimplexSmpQueueMode::Messaging), 2443 link_id: Some(vec![0x14, 0x15]), 2444 service_id: Some(vec![0x16, 0x17]), 2445 server_notification_credentials: None, 2446 }); 2447 2448 let encoded = response 2449 .encode_for_version(RADROOTS_SIMPLEX_SMP_SENDER_AUTH_KEY_TRANSPORT_VERSION) 2450 .unwrap(); 2451 2452 assert_eq!(encoded, b"IDS \x01\x10\x01\x11\x02\x12\x13T".to_vec()); 2453 } 2454 2455 #[test] 2456 fn prxy_matches_official_proxy_session_layout() { 2457 let command = RadrootsSimplexSmpCommand::Prxy { 2458 server: RadrootsSimplexSmpProtocolServer { 2459 hosts: vec![ 2460 "smp4.simplex.im".to_string(), 2461 "simplexabc.onion".to_string(), 2462 ], 2463 port: "5223".to_string(), 2464 key_hash: vec![0xaa, 0xbb, 0xcc], 2465 }, 2466 basic_auth: Some("relay-pass".to_string()), 2467 }; 2468 2469 let encoded = command.encode().unwrap(); 2470 2471 assert_eq!( 2472 encoded, 2473 b"PRXY \x02\x0fsmp4.simplex.im\x10simplexabc.onion\x045223\x03\xaa\xbb\xcc1\x0arelay-pass" 2474 .to_vec() 2475 ); 2476 } 2477 2478 #[test] 2479 fn pkey_matches_official_proxy_session_key_layout() { 2480 let message = RadrootsSimplexSmpBrokerMessage::PKey { 2481 session_id: vec![0x31, 0x32], 2482 version_range: RadrootsSimplexSmpVersionRange::new(8, 16).unwrap(), 2483 cert_chain_public_key: RadrootsSimplexSmpCertChainPublicKey { 2484 certificate_chain: vec![vec![0x41, 0x42], vec![0x43, 0x44, 0x45]], 2485 signed_public_key: vec![0x51, 0x52, 0x53], 2486 }, 2487 }; 2488 2489 let encoded = message.encode().unwrap(); 2490 2491 assert_eq!( 2492 encoded, 2493 b"PKEY \x0212\x00\x08\x00\x10\x02\x00\x02AB\x00\x03CDE\x00\x03QRS".to_vec() 2494 ); 2495 } 2496 2497 #[test] 2498 fn proxy_transport_error_matches_official_nested_error_layout() { 2499 let encoded = RadrootsSimplexSmpBrokerMessage::Err(RadrootsSimplexSmpError::Proxy( 2500 RadrootsSimplexSmpProxyError::Broker(RadrootsSimplexSmpBrokerError::Transport( 2501 RadrootsSimplexSmpTransportError::Handshake( 2502 RadrootsSimplexSmpHandshakeError::Identity, 2503 ), 2504 )), 2505 )) 2506 .encode() 2507 .unwrap(); 2508 2509 assert_eq!( 2510 encoded, 2511 b"ERR PROXY BROKER TRANSPORT HANDSHAKE IDENTITY".to_vec() 2512 ); 2513 } 2514 2515 #[test] 2516 fn round_trips_proxy_and_short_link_commands() { 2517 let prxy = RadrootsSimplexSmpCommandTransmission { 2518 authorization: Vec::new(), 2519 correlation_id: Some(correlation_id(1)), 2520 entity_id: Vec::new(), 2521 command: RadrootsSimplexSmpCommand::Prxy { 2522 server: RadrootsSimplexSmpProtocolServer { 2523 hosts: vec![ 2524 "smp4.simplex.im".to_string(), 2525 "simplexabc.onion".to_string(), 2526 ], 2527 port: "5223".to_string(), 2528 key_hash: vec![0xaa, 0xbb, 0xcc], 2529 }, 2530 basic_auth: Some("relay-pass".to_string()), 2531 }, 2532 }; 2533 2534 let rkey = RadrootsSimplexSmpCommandTransmission { 2535 authorization: vec![0x42], 2536 correlation_id: Some(correlation_id(2)), 2537 entity_id: vec![0x11], 2538 command: RadrootsSimplexSmpCommand::RKey(RadrootsSimplexSmpKeyList { 2539 first: vec![0x01, 0x02], 2540 rest: vec![vec![0x03, 0x04], vec![0x05, 0x06]], 2541 }), 2542 }; 2543 2544 let pkey_encoded = prxy.encode().unwrap(); 2545 let pkey_decoded = RadrootsSimplexSmpCommandTransmission::decode(&pkey_encoded).unwrap(); 2546 assert_eq!(pkey_decoded, prxy); 2547 2548 let rkey_encoded = rkey.encode().unwrap(); 2549 let rkey_decoded = RadrootsSimplexSmpCommandTransmission::decode(&rkey_encoded).unwrap(); 2550 assert_eq!(rkey_decoded, rkey); 2551 } 2552 2553 #[test] 2554 fn protocol_server_accepts_official_transport_host_forms() { 2555 let server = RadrootsSimplexSmpProtocolServer { 2556 hosts: vec![ 2557 "smp4.simplex.im".to_string(), 2558 "192.0.2.24".to_string(), 2559 "2001:db8::24".to_string(), 2560 "[2001:db8::42]".to_string(), 2561 "simplexabc.onion".to_string(), 2562 ], 2563 port: "5223".to_string(), 2564 key_hash: vec![0xaa, 0xbb, 0xcc], 2565 }; 2566 2567 let mut encoded = Vec::new(); 2568 encode_protocol_server(&mut encoded, &server).unwrap(); 2569 let decoded = decode_protocol_server(&mut Cursor::new(&encoded)).unwrap(); 2570 2571 assert_eq!(decoded, server); 2572 } 2573 2574 #[test] 2575 fn protocol_server_rejects_invalid_transport_host_forms() { 2576 let invalid_server = RadrootsSimplexSmpProtocolServer { 2577 hosts: vec!["bad host".to_string()], 2578 port: "5223".to_string(), 2579 key_hash: vec![0xaa, 0xbb, 0xcc], 2580 }; 2581 2582 let mut encoded = Vec::new(); 2583 assert_eq!( 2584 encode_protocol_server(&mut encoded, &invalid_server), 2585 Err(RadrootsSimplexSmpProtoError::InvalidHostList( 2586 "bad host".to_string(), 2587 )) 2588 ); 2589 2590 let mut invalid_bytes = Vec::new(); 2591 push_short_string_list(&mut invalid_bytes, &["[invalid]".to_string()]).unwrap(); 2592 push_short_string(&mut invalid_bytes, "5223").unwrap(); 2593 push_short_bytes(&mut invalid_bytes, &[0xaa, 0xbb, 0xcc]).unwrap(); 2594 2595 assert_eq!( 2596 decode_protocol_server(&mut Cursor::new(&invalid_bytes)), 2597 Err(RadrootsSimplexSmpProtoError::InvalidHostList( 2598 "[invalid]".to_string(), 2599 )) 2600 ); 2601 } 2602 2603 #[test] 2604 fn top_level_unknown_error_tags_stay_opaque() { 2605 assert_eq!( 2606 decode_error(b"FUTURE"), 2607 Ok(RadrootsSimplexSmpError::Other(b"FUTURE".to_vec())) 2608 ); 2609 } 2610 2611 #[test] 2612 fn malformed_nested_proxy_error_fails_decode() { 2613 assert_eq!( 2614 decode_error(b"PROXY BROKER TRANSPORT HANDSHAKE UNKNOWN"), 2615 Err(RadrootsSimplexSmpProtoError::InvalidTag( 2616 "UNKNOWN".to_string(), 2617 )) 2618 ); 2619 } 2620 2621 #[test] 2622 fn malformed_blocked_reason_fails_decode() { 2623 assert_eq!( 2624 decode_error(b"BLOCKED reason=custom"), 2625 Err(RadrootsSimplexSmpProtoError::InvalidTag( 2626 "custom".to_string(), 2627 )) 2628 ); 2629 } 2630 2631 #[test] 2632 fn malformed_network_detail_fails_decode() { 2633 assert_eq!( 2634 decode_broker_error(b"NETWORK CONNECT"), 2635 Err(RadrootsSimplexSmpProtoError::UnexpectedEof) 2636 ); 2637 } 2638 2639 #[test] 2640 fn round_trips_proxy_forward_commands() { 2641 let pfwd = RadrootsSimplexSmpCommandTransmission { 2642 authorization: Vec::new(), 2643 correlation_id: Some(correlation_id(3)), 2644 entity_id: vec![0x90, 0x91], 2645 command: RadrootsSimplexSmpCommand::PFwd { 2646 relay_version: 16, 2647 public_key: vec![0x10, 0x11, 0x12], 2648 encrypted_transmission: vec![0xde, 0xad, 0xbe, 0xef], 2649 }, 2650 }; 2651 let rfwd = RadrootsSimplexSmpCommandTransmission { 2652 authorization: Vec::new(), 2653 correlation_id: Some(correlation_id(4)), 2654 entity_id: Vec::new(), 2655 command: RadrootsSimplexSmpCommand::RFwd(vec![0xca, 0xfe, 0xba, 0xbe]), 2656 }; 2657 2658 let pfwd_encoded = pfwd.encode().unwrap(); 2659 let pfwd_decoded = RadrootsSimplexSmpCommandTransmission::decode(&pfwd_encoded).unwrap(); 2660 assert_eq!(pfwd_decoded, pfwd); 2661 2662 let rfwd_encoded = rfwd.encode().unwrap(); 2663 let rfwd_decoded = RadrootsSimplexSmpCommandTransmission::decode(&rfwd_encoded).unwrap(); 2664 assert_eq!(rfwd_decoded, rfwd); 2665 } 2666 2667 #[test] 2668 fn round_trips_service_and_proxy_broker_messages() { 2669 let service = RadrootsSimplexSmpBrokerTransmission { 2670 authorization: Vec::new(), 2671 correlation_id: Some(correlation_id(5)), 2672 entity_id: vec![0x44], 2673 message: RadrootsSimplexSmpBrokerMessage::Sok(Some(vec![0x20, 0x21])), 2674 }; 2675 let proxy = RadrootsSimplexSmpBrokerTransmission { 2676 authorization: Vec::new(), 2677 correlation_id: None, 2678 entity_id: Vec::new(), 2679 message: RadrootsSimplexSmpBrokerMessage::PKey { 2680 session_id: vec![0x31, 0x32], 2681 version_range: RadrootsSimplexSmpVersionRange::new(8, 16).unwrap(), 2682 cert_chain_public_key: RadrootsSimplexSmpCertChainPublicKey { 2683 certificate_chain: vec![vec![0x41, 0x42], vec![0x43, 0x44, 0x45]], 2684 signed_public_key: vec![0x51, 0x52, 0x53], 2685 }, 2686 }, 2687 }; 2688 2689 let service_encoded = service.encode().unwrap(); 2690 let service_decoded = 2691 RadrootsSimplexSmpBrokerTransmission::decode(&service_encoded).unwrap(); 2692 assert_eq!(service_decoded, service); 2693 2694 let proxy_encoded = proxy.encode().unwrap(); 2695 let proxy_decoded = RadrootsSimplexSmpBrokerTransmission::decode(&proxy_encoded).unwrap(); 2696 assert_eq!(proxy_decoded, proxy); 2697 } 2698 2699 #[test] 2700 fn round_trips_proxy_and_blocked_errors() { 2701 let proxy_error = RadrootsSimplexSmpBrokerTransmission { 2702 authorization: Vec::new(), 2703 correlation_id: Some(correlation_id(6)), 2704 entity_id: vec![0x77], 2705 message: RadrootsSimplexSmpBrokerMessage::Err(RadrootsSimplexSmpError::Proxy( 2706 RadrootsSimplexSmpProxyError::Broker(RadrootsSimplexSmpBrokerError::Transport( 2707 RadrootsSimplexSmpTransportError::Handshake( 2708 RadrootsSimplexSmpHandshakeError::Identity, 2709 ), 2710 )), 2711 )), 2712 }; 2713 let blocked_error = RadrootsSimplexSmpBrokerTransmission { 2714 authorization: Vec::new(), 2715 correlation_id: Some(correlation_id(7)), 2716 entity_id: vec![0x88], 2717 message: RadrootsSimplexSmpBrokerMessage::Err(RadrootsSimplexSmpError::Blocked( 2718 RadrootsSimplexSmpBlockingInfo { 2719 reason: RadrootsSimplexSmpBlockingReason::Spam, 2720 }, 2721 )), 2722 }; 2723 2724 let proxy_encoded = proxy_error.encode().unwrap(); 2725 let proxy_decoded = RadrootsSimplexSmpBrokerTransmission::decode(&proxy_encoded).unwrap(); 2726 assert_eq!(proxy_decoded, proxy_error); 2727 2728 let blocked_encoded = blocked_error.encode().unwrap(); 2729 let blocked_decoded = 2730 RadrootsSimplexSmpBrokerTransmission::decode(&blocked_encoded).unwrap(); 2731 assert_eq!(blocked_decoded, blocked_error); 2732 } 2733 2734 #[test] 2735 fn service_ok_downgrades_to_ok_before_service_certs() { 2736 let encoded = RadrootsSimplexSmpBrokerMessage::Sok(Some(vec![0x10])) 2737 .encode_for_version(RADROOTS_SIMPLEX_SMP_SHORT_LINKS_TRANSPORT_VERSION) 2738 .unwrap(); 2739 2740 assert_eq!(encoded, b"OK".to_vec()); 2741 } 2742 2743 #[test] 2744 fn blocked_error_downgrades_to_auth_before_blocked_entity_version() { 2745 let encoded = RadrootsSimplexSmpBrokerMessage::Err(RadrootsSimplexSmpError::Blocked( 2746 RadrootsSimplexSmpBlockingInfo { 2747 reason: RadrootsSimplexSmpBlockingReason::Content, 2748 }, 2749 )) 2750 .encode_for_version(RADROOTS_SIMPLEX_SMP_SENDER_AUTH_KEY_TRANSPORT_VERSION) 2751 .unwrap(); 2752 2753 assert_eq!(encoded, b"ERR AUTH".to_vec()); 2754 } 2755 2756 #[test] 2757 fn decodes_optional_network_detail_and_preserves_encode_behavior() { 2758 let detailed = decode_broker_error(b"NETWORK CONNECT \x03dns").unwrap(); 2759 assert_eq!( 2760 detailed, 2761 RadrootsSimplexSmpBrokerError::Network(RadrootsSimplexSmpNetworkError::Connect( 2762 "dns".to_string(), 2763 )) 2764 ); 2765 2766 let encoded = 2767 encode_network_error(&RadrootsSimplexSmpNetworkError::Connect("dns".to_string())); 2768 assert_eq!(encoded, b"CONNECT \x03dns".to_vec()); 2769 assert_eq!( 2770 encode_broker_error(&RadrootsSimplexSmpBrokerError::Network( 2771 RadrootsSimplexSmpNetworkError::Connect("dns".to_string()), 2772 )) 2773 .unwrap(), 2774 b"NETWORK".to_vec() 2775 ); 2776 } 2777 }