subject.rs (23905B)
1 /* 2 This file is part of TALER 3 Copyright (C) 2024-2026 Taler Systems SA 4 5 TALER is free software; you can redistribute it and/or modify it under the 6 terms of the GNU Affero General Public License as published by the Free Software 7 Foundation; either version 3, or (at your option) any later version. 8 9 TALER is distributed in the hope that it will be useful, but WITHOUT ANY 10 WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR 11 A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. 12 13 You should have received a copy of the GNU Affero General Public License along with 14 TALER; see the file COPYING. If not, see <http://www.gnu.org/licenses/> 15 */ 16 17 use std::{ 18 fmt::{Debug, Display, Write as _}, 19 str::FromStr, 20 }; 21 22 use aws_lc_rs::digest::{SHA256, digest}; 23 use compact_str::CompactString; 24 use taler_common::{ 25 api::{EddsaPublicKey, ShortHashCode}, 26 db::IncomingType, 27 encoding::base32::{Base32Error, CROCKFORD_ALPHABET}, 28 types::url, 29 }; 30 use url::Url; 31 32 #[derive(Debug, Clone, PartialEq, Eq)] 33 pub enum IncomingSubject { 34 Key(IncomingKey), 35 AdminBalanceAdjust, 36 } 37 38 #[derive(Debug, Clone, PartialEq, Eq)] 39 pub struct IncomingKey { 40 pub ty: IncomingType, 41 pub key: EddsaPublicKey, 42 } 43 44 impl IncomingKey { 45 pub fn reserve(key: EddsaPublicKey) -> Self { 46 Self { 47 ty: IncomingType::reserve, 48 key, 49 } 50 } 51 52 pub fn kyc(key: EddsaPublicKey) -> Self { 53 Self { 54 ty: IncomingType::kyc, 55 key, 56 } 57 } 58 59 pub fn map(key: EddsaPublicKey) -> Self { 60 Self { 61 ty: IncomingType::map, 62 key, 63 } 64 } 65 } 66 67 #[derive(Debug, PartialEq, Eq)] 68 pub struct OutgoingSubject { 69 pub wtid: ShortHashCode, 70 pub exchange_base_url: Url, 71 pub metadata: Option<CompactString>, 72 } 73 74 impl OutgoingSubject { 75 /// Generate a random outgoing subject for https://exchange.test.com 76 pub fn rand() -> Self { 77 Self { 78 wtid: ShortHashCode::rand(), 79 exchange_base_url: url("https://exchange.test.com"), 80 metadata: None, 81 } 82 } 83 } 84 85 /** Base32 quality by proximity to spec and error probability */ 86 #[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)] 87 enum Base32Quality { 88 /// Both mixed casing and mixed characters, that's weird 89 Mixed, 90 /// Standard but use lowercase, maybe the client shown lowercase in the UI 91 Standard, 92 /// Uppercase but mixed characters, its common when making typos 93 Upper, 94 /// Both uppercase and use the standard alphabet as it should 95 UpperStandard, 96 } 97 98 impl Base32Quality { 99 pub fn measure(s: &str) -> Self { 100 let mut uppercase = true; 101 let mut standard = true; 102 for b in s.bytes() { 103 uppercase &= b.is_ascii_uppercase() | b.is_ascii_digit(); 104 standard &= CROCKFORD_ALPHABET.contains(&b) 105 | CROCKFORD_ALPHABET.contains(&b.to_ascii_uppercase()) 106 } 107 match (uppercase, standard) { 108 (true, true) => Base32Quality::UpperStandard, 109 (true, false) => Base32Quality::Upper, 110 (false, true) => Base32Quality::Standard, 111 (false, false) => Base32Quality::Mixed, 112 } 113 } 114 } 115 116 #[derive(Debug)] 117 pub struct Candidate { 118 subject: IncomingSubject, 119 quality: Base32Quality, 120 } 121 122 #[derive(Debug, PartialEq, Eq)] 123 pub enum IncomingSubjectResult { 124 Success(IncomingSubject), 125 Ambiguous, 126 } 127 128 #[derive(Debug, PartialEq, Eq, thiserror::Error)] 129 pub enum IncomingSubjectErr { 130 #[error("found multiple public keys")] 131 Ambiguous, 132 #[error("missing reserve public key")] 133 Missing, 134 } 135 136 #[derive(Debug, thiserror::Error)] 137 pub enum OutgoingSubjectErr { 138 #[error("missing parts")] 139 MissingParts, 140 #[error("malformed wtid: {0}")] 141 Wtid(#[from] Base32Error<32>), 142 #[error("malformed exchange url: {0}")] 143 Url(#[from] url::ParseError), 144 } 145 146 /// Parse a talerable outgoing transfer subject 147 pub fn parse_outgoing(subject: &str) -> Result<OutgoingSubject, OutgoingSubjectErr> { 148 let mut parts = subject.split(' '); 149 let first = parts.next().ok_or(OutgoingSubjectErr::MissingParts)?; 150 let second = parts.next().ok_or(OutgoingSubjectErr::MissingParts)?; 151 Ok(if let Some(third) = parts.next() { 152 OutgoingSubject { 153 wtid: second.parse()?, 154 exchange_base_url: third.parse()?, 155 metadata: Some(first.into()), 156 } 157 } else { 158 OutgoingSubject { 159 wtid: first.parse()?, 160 exchange_base_url: second.parse()?, 161 metadata: None, 162 } 163 }) 164 } 165 166 /// Format an outgoing subject 167 pub fn fmt_out_subject( 168 wtid: &ShortHashCode, 169 url: impl AsRef<str>, 170 metadata: Option<&str>, 171 ) -> String { 172 let mut buf = String::new(); 173 if let Some(metadata) = metadata { 174 buf.push_str(metadata); 175 buf.push(' '); 176 } 177 write!(&mut buf, "{wtid} {}", url.as_ref()).unwrap(); 178 buf 179 } 180 181 /// Format an incoming subject 182 pub fn fmt_in_subject(ty: IncomingType, key: &EddsaPublicKey) -> impl Display { 183 std::fmt::from_fn(move |f| match ty { 184 IncomingType::reserve => write!(f, "{key}"), 185 IncomingType::kyc => write!(f, "KYC:{key}"), 186 IncomingType::map => write!(f, "MAP:{key}"), 187 }) 188 } 189 190 /** 191 * Extract the public key from an unstructured incoming transfer subject. 192 * 193 * When a user enters the transfer object in an unstructured way, for ex in 194 * their banking UI, they may mistakenly enter separators such as ' \n-+' and 195 * make typos. 196 * To parse them while ignoring user errors, we reconstruct valid keys from key 197 * parts, resolving ambiguities where possible. 198 **/ 199 pub fn parse_incoming_unstructured(subject: &str) -> Result<IncomingSubject, IncomingSubjectErr> { 200 // We expect subject to be less than 4GB 201 assert!(subject.len() <= u32::MAX as usize); 202 203 const KEY_SIZE: usize = 52; 204 const PREFIXED_SIZE: usize = KEY_SIZE + 3; 205 const ADMIN_BALANCE_ADJUST: &str = "ADMINBALANCEADJUST"; 206 207 /** Parse an incoming subject */ 208 #[inline] 209 fn parse_single(str: &str) -> Option<Candidate> { 210 if str == ADMIN_BALANCE_ADJUST { 211 return Some(Candidate { 212 subject: IncomingSubject::AdminBalanceAdjust, 213 quality: Base32Quality::UpperStandard, 214 }); 215 } 216 // Check key type 217 let (ty, raw) = match str.len() { 218 KEY_SIZE => (IncomingType::reserve, str), 219 PREFIXED_SIZE => { 220 let (prefix, key) = str.split_at(3); 221 if prefix.eq_ignore_ascii_case("KYC") { 222 (IncomingType::kyc, key) 223 } else if prefix.eq_ignore_ascii_case("MAP") { 224 (IncomingType::map, key) 225 } else { 226 return None; 227 } 228 } 229 _ => return None, 230 }; 231 232 // Check key validity 233 let key = EddsaPublicKey::from_str(raw).ok()?; 234 235 let quality = Base32Quality::measure(raw); 236 Some(Candidate { 237 subject: IncomingSubject::Key(IncomingKey { ty, key }), 238 quality, 239 }) 240 } 241 242 // Find and concatenate valid parts of a keys 243 let (parts, concatenated) = { 244 let mut parts = Vec::with_capacity(4); 245 let mut concatenated = String::with_capacity(subject.len().min(PREFIXED_SIZE + 10)); 246 parts.push(0u32); 247 for part in subject.as_bytes().split(|b| !b.is_ascii_alphanumeric()) { 248 if !part.is_empty() { 249 // SAFETY: part are all valid ASCII alphanumeric 250 concatenated.push_str(unsafe { std::str::from_utf8_unchecked(part) }); 251 parts.push(concatenated.len() as u32); 252 } 253 } 254 (parts, concatenated) 255 }; 256 257 // Find best candidates 258 let mut best: Option<(IncomingType, EddsaPublicKey, Base32Quality, u32)> = None; 259 // For each part as a starting point 260 for (i, &start) in parts.iter().enumerate() { 261 // Use progressively longer concatenation 262 for &end in parts[i..].iter().skip(1) { 263 let len = (end - start) as usize; 264 // Until they are to long to be a key 265 if len > PREFIXED_SIZE { 266 break; 267 } else if len != KEY_SIZE && len != PREFIXED_SIZE && len != ADMIN_BALANCE_ADJUST.len() { 268 continue; 269 } 270 271 // Parse the concatenated parts 272 // SAFETY: we now end.end <= concatenated.len 273 let slice = unsafe { &concatenated.get_unchecked(start as usize..end as usize) }; 274 if let Some(new) = parse_single(slice) { 275 let (nty, nkey) = match new.subject { 276 IncomingSubject::AdminBalanceAdjust => { 277 return Ok(IncomingSubject::AdminBalanceAdjust); 278 } 279 IncomingSubject::Key(IncomingKey { ty, key }) => (ty, key), 280 }; 281 // On success update best candidate 282 match best { 283 Some((bty, bkey, bquality, bstart)) => { 284 // A 55-char prefixed slice starting at the same offset as an already 285 // matched 52-char reserve key would strip "KYC"/"MAP" from the key 286 // itself and glue on trailing text; ignore it 287 if bty == IncomingType::reserve 288 && matches!(nty, IncomingType::kyc | IncomingType::map) 289 && start == bstart 290 { 291 continue; 292 } 293 if new.quality > bquality // We prefer high quality keys 294 || matches!( // We prefer prefixed keys over reserve keys 295 (bty, nty), 296 (IncomingType::reserve, IncomingType::kyc | IncomingType::map) 297 ) 298 { 299 best = Some((nty, nkey, new.quality, start)) 300 } else if bkey != nkey // If keys are different 301 && bquality == new.quality // Of same quality 302 && !matches!( // And prefixing is different 303 (bty, nty), 304 (IncomingType::kyc | IncomingType::map, IncomingType::reserve) 305 ) 306 { 307 return Err(IncomingSubjectErr::Ambiguous); 308 } 309 } 310 None => best = Some((nty, nkey, new.quality, start)), 311 } 312 } 313 } 314 } 315 316 if let Some((ty, key, _, _)) = best { 317 Ok(IncomingSubject::Key(IncomingKey { ty, key })) 318 } else { 319 Err(IncomingSubjectErr::Missing) 320 } 321 } 322 323 // Modulo 10 Recursive 324 fn mod10_recursive(bytes: &[u8]) -> u8 { 325 const LOOKUP_TABLE: [u8; 10] = [0, 9, 4, 6, 8, 2, 7, 1, 3, 5]; 326 // Modulo 10 Recursive calculation 327 let mut carry = 0u8; 328 for &b in bytes { 329 // ASCII '0'-'9' is 0x30-0x39. Subtracting b'0' (48) gives the integer. 330 let digit = b - b'0'; 331 carry = LOOKUP_TABLE[((carry + digit) % 10) as usize]; 332 } 333 carry 334 } 335 336 /// Encode a public key as a QR-Bill reference 337 pub fn subject_fmt_qr_bill(key_bytes: &[u8]) -> String { 338 // High-Entropy Hash (SHA-256) to ensure even distribution 339 let hash = digest(&SHA256, key_bytes); 340 341 // Compute hash % 10^26 342 let hash_mod = hash.as_ref().chunks(3).fold(0u128, |rem, chunk| { 343 chunk.iter().fold(rem, |r, &b| r * 256 + b as u128) % 10u128.pow(26) 344 }); 345 346 // Format to 26 digits with leading zeros 347 let reference_base = format!("{:0>26}", hash_mod); 348 349 // Modulo 10 Recursive calculation 350 let carry = mod10_recursive(reference_base.as_bytes()); 351 let checksum = (10 - carry) % 10; 352 353 // Combine base (26) + checksum (1) = 27 characters 354 format!("{}{}", reference_base, checksum) 355 } 356 357 /// Check if a string is a valid QR-Bill reference 358 pub fn subject_is_qr_bill(reference: &str) -> bool { 359 // Quick length and numeric check 360 if reference.len() != 27 || !reference.chars().all(|c| c.is_ascii_digit()) { 361 return false; 362 } 363 364 // If the check digit is correct, the final carry will be 0 365 mod10_recursive(reference.as_bytes()) == 0 366 } 367 368 #[cfg(test)] 369 mod test { 370 use std::str::FromStr as _; 371 372 use taler_common::{ 373 api::{EddsaPublicKey, ShortHashCode}, 374 db::IncomingType, 375 types::url, 376 }; 377 378 use crate::subject::{ 379 Base32Quality, IncomingKey, IncomingSubject, IncomingSubjectErr, OutgoingSubject, 380 fmt_out_subject, mod10_recursive, parse_incoming_unstructured, parse_outgoing, 381 subject_fmt_qr_bill, subject_is_qr_bill, 382 }; 383 384 #[test] 385 fn qrbill() { 386 let reference = "210000000003139471430009017"; 387 388 let input = "21000000000313947143000901"; 389 let carry = mod10_recursive(input.as_bytes()); 390 let checksum = (10 - carry) % 10; 391 assert_eq!(checksum, 7); 392 393 assert_eq!(mod10_recursive(reference.as_bytes()), 0); 394 assert!(subject_is_qr_bill(reference)); 395 assert!(!subject_is_qr_bill(input)); 396 assert!(!subject_is_qr_bill("")); 397 assert!(!subject_is_qr_bill("210000000003139471430009019")); 398 assert!(!subject_is_qr_bill("21000000000313947143000901A")); 399 400 let key = "4MZT6RS3RVB3B0E2RDMYW0YRA3Y0VPHYV0CYDE6XBB0YMPFXCEG0"; 401 let key = EddsaPublicKey::from_str(key).unwrap(); 402 assert_eq!( 403 subject_fmt_qr_bill(key.as_ref()), 404 "442862674560948379842733643" 405 ); 406 } 407 408 #[test] 409 fn quality() { 410 assert_eq!( 411 Base32Quality::measure("4MZT6RS3RVB3B0E2RDMYW0YRA3Y0VPHYV0CYDE6XBB0YMPFXCEG0"), 412 Base32Quality::UpperStandard 413 ); 414 assert_eq!( 415 Base32Quality::measure("4MZT6RS3RVB3B0E2RDMYW0YRA3Y0UPHYV0CYDE6XBB0YMPFXCEG0"), 416 Base32Quality::Upper 417 ); 418 assert_eq!( 419 Base32Quality::measure("4mZT6RS3RVB3B0E2RDMYW0YRA3Y0VPHYV0CYDE6XBB0YMPFXCEG0"), 420 Base32Quality::Standard 421 ); 422 assert_eq!( 423 Base32Quality::measure("4mZT6RS3RVB3B0E2RDMYW0YRA3Y0UPHYV0CYDE6XBB0YMPFXCEG0"), 424 Base32Quality::Mixed 425 ); 426 } 427 428 #[test] 429 /** Test parsing logic */ 430 fn incoming_parse() { 431 let key = "4MZT6RS3RVB3B0E2RDMYW0YRA3Y0VPHYV0CYDE6XBB0YMPFXCEG0"; 432 let other = "00Q979QSMJ29S7BJT3DDAVC5A0DR5Z05B7N0QT1RCBQ8FXJPZ6RG"; 433 434 // Common checks 435 for ty in [IncomingType::reserve, IncomingType::kyc, IncomingType::map] { 436 let prefix = match ty { 437 IncomingType::reserve => "", 438 IncomingType::kyc => "KYC", 439 IncomingType::map => "MAP", 440 }; 441 let standard = &format!("{prefix}{key}"); 442 let (standard_l, standard_r) = standard.split_at(standard.len() / 2); 443 let mixed = &format!("{prefix}4mzt6RS3rvb3b0e2rdmyw0yra3y0vphyv0cyde6xbb0ympfxceg0"); 444 let (mixed_l, mixed_r) = mixed.split_at(mixed.len() / 2); 445 let other_standard = &format!("{prefix}{other}"); 446 let other_mixed = 447 &format!("{prefix}TEGY6d9mh9pgwvwpgs0z0095z854xegfy7jj202yd0esp8p0za60"); 448 let key = EddsaPublicKey::from_str(key).unwrap(); 449 let result = Ok(IncomingSubject::Key(IncomingKey { ty, key })); 450 451 // Check succeed if standard or mixed 452 for case in [standard, mixed] { 453 for test in [ 454 format!("noise {case} noise"), 455 format!("{case} noise to the right"), 456 format!("noise to the left {case}"), 457 format!(" {case} "), 458 format!("noise\n{case}\nnoise"), 459 format!("Test+{case}"), 460 ] { 461 assert_eq!(parse_incoming_unstructured(&test), result); 462 } 463 } 464 465 // Check succeed if standard or mixed and split 466 for (l, r) in [(standard_l, standard_r), (mixed_l, mixed_r)] { 467 for case in [ 468 format!("left {l}{r} right"), 469 format!("left {l} {r} right"), 470 format!("left {l}-{r} right"), 471 format!("left {l}+{r} right"), 472 format!("left {l}\n{r} right"), 473 format!("left {l}-+\n{r} right"), 474 format!("left {l} - {r} right"), 475 format!("left {l} + {r} right"), 476 format!("left {l} \n {r} right"), 477 format!("left {l} - + \n {r} right"), 478 ] { 479 assert_eq!(parse_incoming_unstructured(&case), result); 480 } 481 } 482 483 // Check concat parts 484 for chunk_size in 1..standard.len() { 485 let chunked: String = standard 486 .as_bytes() 487 .chunks(chunk_size) 488 .flat_map(|c| [std::str::from_utf8(c).unwrap(), " "]) 489 .collect(); 490 for case in [chunked.clone(), format!("left {chunked} right")] { 491 assert_eq!(parse_incoming_unstructured(&case), result); 492 } 493 } 494 495 // Check failed when multiple key 496 for case in [ 497 format!("{standard} {other_standard}"), 498 format!("{mixed} {other_mixed}"), 499 ] { 500 assert_eq!( 501 parse_incoming_unstructured(&case), 502 Err(IncomingSubjectErr::Ambiguous) 503 ); 504 } 505 506 // Check accept redundant key 507 for case in [ 508 format!("{standard} {standard} {mixed} {mixed}"), // Accept redundant key 509 format!("{standard} {other_mixed}"), // Prefer high quality 510 ] { 511 assert_eq!(parse_incoming_unstructured(&case), result); 512 } 513 514 // Check prefer prefixed over simple ones 515 for case in [ 516 format!("{standard_l}-{standard_r} {mixed_l}-{mixed_r}"), 517 format!("{mixed_l}-{mixed_r} {standard_l}-{standard_r}"), 518 ] { 519 let res = parse_incoming_unstructured(&case); 520 if !(ty == IncomingType::reserve 521 && matches!(res, Err(IncomingSubjectErr::Ambiguous))) 522 { 523 assert_eq!(res, result); 524 } 525 } 526 527 // Check failure if malformed or missing 528 for case in [ 529 "does not contain any reserve", // Check fail if none 530 &standard[1..], // Check fail if missing char 531 // "2MZT6RS3RVB3B0E2RDMYW0YRA3Y0VPHYV0CYDE6XBB0YMPFXCEG0", // Check fail if not a valid key TODO aws-lc does not check 532 ] { 533 assert_eq!( 534 parse_incoming_unstructured(case), 535 Err(IncomingSubjectErr::Missing) 536 ); 537 } 538 539 if ty == IncomingType::kyc || ty == IncomingType::map { 540 // Prefer prefixed over unprefixed 541 for case in [format!("{other} {standard}"), format!("{other} {mixed}")] { 542 assert_eq!(parse_incoming_unstructured(&case), result); 543 } 544 } 545 } 546 } 547 548 #[test] 549 /** Test parsing logic using real cases */ 550 fn real() { 551 // Good reserve case 552 for (subject, key) in [ 553 ( 554 "Taler TEGY6d9mh9pgwvwpgs0z0095z854xegfy7j j202yd0esp8p0za60", 555 "TEGY6d9mh9pgwvwpgs0z0095z854xegfy7jj202yd0esp8p0za60", 556 ), 557 ( 558 "00Q979QSMJ29S7BJT3DDAVC5A0DR5Z05B7N 0QT1RCBQ8FXJPZ6RG", 559 "00Q979QSMJ29S7BJT3DDAVC5A0DR5Z05B7N0QT1RCBQ8FXJPZ6RG", 560 ), 561 ( 562 "Taler NDDCAM9XN4HJZFTBD8V6FNE2FJE8G Y734PJ5AGQMY06C8D4HB3Z0", 563 "NDDCAM9XN4HJZFTBD8V6FNE2FJE8GY734PJ5AGQMY06C8D4HB3Z0", 564 ), 565 ( 566 "KYCVEEXTBXBEMCS5R64C24GFNQVWBN5R2F9QSQ7PN8QXAP1NG4NG", 567 "KYCVEEXTBXBEMCS5R64C24GFNQVWBN5R2F9QSQ7PN8QXAP1NG4NG", 568 ), 569 // Reserve key starting with KYC followed by a 3-letter word must not be clobbered 570 ( 571 "KYCVEEXTBXBEMCS5R64C24GFNQVWBN5R2F9QSQ7PN8QXAP1NG4NG EUR", 572 "KYCVEEXTBXBEMCS5R64C24GFNQVWBN5R2F9QSQ7PN8QXAP1NG4NG", 573 ), 574 ( 575 "KYCVEEXTBXBEMCS5R64C24GFNQVWBN5R2F9QSQ7PN8QXAP1NG4NG G00", 576 "KYCVEEXTBXBEMCS5R64C24GFNQVWBN5R2F9QSQ7PN8QXAP1NG4NG", 577 ), 578 ] { 579 assert_eq!( 580 Ok(IncomingSubject::Key(IncomingKey::reserve( 581 EddsaPublicKey::from_str(key).unwrap(), 582 ))), 583 parse_incoming_unstructured(subject) 584 ) 585 } 586 // Good kyc case 587 for (subject, key) in [ 588 ( 589 "KYC JW398X85FWPKKMS0EYB6TQ1799RMY5DDXTZ FPW4YC3WJ2DWSJT70", 590 "JW398X85FWPKKMS0EYB6TQ1799RMY5DDXTZFPW4YC3WJ2DWSJT70", 591 ), 592 ( 593 "kyc: JW398X85FWPKKMS0EYB6TQ1799RMY5DDXTZFPW4YC3WJ2DWSJT70", 594 "JW398X85FWPKKMS0EYB6TQ1799RMY5DDXTZFPW4YC3WJ2DWSJT70", 595 ), 596 ( 597 "Kyc JW398X85FWPKKMS0EYB6TQ1799RMY5DDXTZFPW4YC3WJ2DWSJT70", 598 "JW398X85FWPKKMS0EYB6TQ1799RMY5DDXTZFPW4YC3WJ2DWSJT70", 599 ), 600 ] { 601 assert_eq!( 602 Ok(IncomingSubject::Key(IncomingKey::kyc( 603 EddsaPublicKey::from_str(key).unwrap(), 604 ))), 605 parse_incoming_unstructured(subject) 606 ) 607 } 608 // Case-insensitive MAP prefix 609 assert_eq!( 610 Ok(IncomingSubject::Key(IncomingKey::map( 611 EddsaPublicKey::from_str("JW398X85FWPKKMS0EYB6TQ1799RMY5DDXTZFPW4YC3WJ2DWSJT70") 612 .unwrap(), 613 ))), 614 parse_incoming_unstructured( 615 "map: JW398X85FWPKKMS0EYB6TQ1799RMY5DDXTZFPW4YC3WJ2DWSJT70" 616 ) 617 ); 618 // 52-char non-Taler English prose must be rejected 619 assert_eq!( 620 parse_incoming_unstructured("Monthly rent payment for apartment twelve building one"), 621 Err(IncomingSubjectErr::Missing) 622 ); 623 } 624 625 #[test] 626 fn outgoing() { 627 let wtid = ShortHashCode::rand(); 628 629 // Without metadata 630 let subject = format!("{wtid} http://exchange.example.com/"); 631 let parsed = parse_outgoing(&subject).unwrap(); 632 assert_eq!( 633 parsed, 634 OutgoingSubject { 635 wtid, 636 exchange_base_url: url("http://exchange.example.com/"), 637 metadata: None 638 } 639 ); 640 assert_eq!( 641 subject, 642 fmt_out_subject( 643 &parsed.wtid, 644 &parsed.exchange_base_url, 645 parsed.metadata.as_deref() 646 ) 647 ); 648 649 // With metadata 650 let subject = format!("Accounting:id.4 {wtid} http://exchange.example.com/"); 651 let parsed = parse_outgoing(&subject).unwrap(); 652 assert_eq!( 653 parsed, 654 OutgoingSubject { 655 wtid, 656 exchange_base_url: url("http://exchange.example.com/"), 657 metadata: Some("Accounting:id.4".into()) 658 } 659 ); 660 assert_eq!( 661 subject, 662 fmt_out_subject( 663 &parsed.wtid, 664 &parsed.exchange_base_url, 665 parsed.metadata.as_deref() 666 ) 667 ); 668 } 669 }