|
| 1 | +use std::fmt::{self, Display}; |
| 2 | + |
| 3 | +use bech32::primitives::decode::CheckedHrpstring; |
| 4 | +use bech32::Bech32m; |
| 5 | +use error_stack::{bail, ensure, Report, ResultExt}; |
| 6 | +use regex::Regex; |
| 7 | + |
| 8 | +use super::Error; |
| 9 | + |
| 10 | +#[derive(Debug)] |
| 11 | +pub struct Bech32mFormat { |
| 12 | + pub encoded: String, |
| 13 | +} |
| 14 | + |
| 15 | +impl Bech32mFormat { |
| 16 | + pub fn new(encoded: String) -> Self { |
| 17 | + Self { encoded } |
| 18 | + } |
| 19 | + |
| 20 | + pub fn from_str(prefix: &str, length: usize, message_id: &str) -> Result<Self, Report<Error>> { |
| 21 | + // The Bech32m prefix should be between 1 and 83 characters |
| 22 | + ensure!( |
| 23 | + !prefix.is_empty() && prefix.len() <= 83, |
| 24 | + Error::InvalidBech32mFormat("Prefix size should be between 1 and 83".to_string()) |
| 25 | + ); |
| 26 | + |
| 27 | + let data_part_length = length.saturating_sub(prefix.len()).saturating_sub(1); |
| 28 | + ensure!( |
| 29 | + data_part_length >= 6, |
| 30 | + Error::InvalidBech32mFormat( |
| 31 | + "The data part should be at least 6 characters long".to_string() |
| 32 | + ) |
| 33 | + ); |
| 34 | + |
| 35 | + ensure!( |
| 36 | + prefix.chars().all(|c| { c.is_alphanumeric() }), |
| 37 | + Error::InvalidBech32mFormat( |
| 38 | + "The prefix should contain only Bech32m valid characters".to_string() |
| 39 | + ) |
| 40 | + ); |
| 41 | + |
| 42 | + let pattern = format!("^({prefix}1[02-9ac-hj-np-z]{{{data_part_length}}})$"); |
| 43 | + |
| 44 | + let regex = Regex::new(pattern.as_str()).change_context(Error::InvalidBech32mFormat( |
| 45 | + "Failed to create regex".to_string(), |
| 46 | + ))?; |
| 47 | + |
| 48 | + let (_, [string]) = regex |
| 49 | + .captures(message_id) |
| 50 | + .ok_or(Error::InvalidMessageID { |
| 51 | + id: message_id.to_string(), |
| 52 | + expected_format: format!("Bech32m with '{}' prefix", prefix), |
| 53 | + })? |
| 54 | + .extract(); |
| 55 | + |
| 56 | + verify_bech32m(string, prefix)?; |
| 57 | + |
| 58 | + Ok(Self { |
| 59 | + encoded: string.to_string(), |
| 60 | + }) |
| 61 | + } |
| 62 | +} |
| 63 | + |
| 64 | +impl Display for Bech32mFormat { |
| 65 | + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { |
| 66 | + write!(f, "{}", self.encoded) |
| 67 | + } |
| 68 | +} |
| 69 | + |
| 70 | +fn verify_bech32m(input: &str, expected_prefix: &str) -> Result<(), Report<Error>> { |
| 71 | + let checked_bech32m = CheckedHrpstring::new::<Bech32m>(input) |
| 72 | + .change_context(Error::InvalidBech32m(input.to_string()))?; |
| 73 | + |
| 74 | + ensure!( |
| 75 | + checked_bech32m.hrp().as_str() == expected_prefix, |
| 76 | + Error::InvalidBech32m(format!( |
| 77 | + "Expected prefix '{expected_prefix}' not found: '{input}'" |
| 78 | + )) |
| 79 | + ); |
| 80 | + |
| 81 | + if checked_bech32m.data_part_ascii_no_checksum().is_empty() { |
| 82 | + bail!(Error::InvalidBech32m(format!( |
| 83 | + "Message Id is missing the data part: '{input}'" |
| 84 | + ))); |
| 85 | + } |
| 86 | + |
| 87 | + Ok(()) |
| 88 | +} |
| 89 | + |
| 90 | +#[cfg(test)] |
| 91 | +mod test { |
| 92 | + use bech32::Hrp; |
| 93 | + use rand::Rng; |
| 94 | + |
| 95 | + use super::*; |
| 96 | + use crate::assert_err_contains; |
| 97 | + |
| 98 | + #[test] |
| 99 | + fn should_pass_bech32m() { |
| 100 | + let mut rng = rand::thread_rng(); |
| 101 | + |
| 102 | + const CHARS: [char; 32] = [ |
| 103 | + 'q', 'p', 'z', 'r', 'y', '9', 'x', '8', 'g', 'f', '2', 't', 'v', 'd', 'w', '0', 's', |
| 104 | + '3', 'j', 'n', '5', '4', 'k', 'h', 'c', 'e', '6', 'm', 'u', 'a', '7', 'l', |
| 105 | + ]; |
| 106 | + let char_set = CHARS.len(); |
| 107 | + |
| 108 | + for _ in 0..100 { |
| 109 | + let hrp_str = (0..rng.gen_range(1..=83)) |
| 110 | + .map(|_| CHARS[rng.gen_range(0..char_set)]) |
| 111 | + .collect::<String>(); |
| 112 | + |
| 113 | + let data = (0..80) |
| 114 | + .map(|_| char::from(rng.gen_range(32..=126))) |
| 115 | + .collect::<String>(); |
| 116 | + |
| 117 | + let hrp = Hrp::parse(hrp_str.as_str()).expect("valid hrp"); |
| 118 | + let string = |
| 119 | + bech32::encode::<Bech32m>(hrp, data.as_bytes()).expect("failed to encode string"); |
| 120 | + |
| 121 | + assert!(Bech32mFormat::from_str(hrp.as_str(), string.len(), string.as_str()).is_ok()); |
| 122 | + } |
| 123 | + } |
| 124 | + |
| 125 | + #[test] |
| 126 | + fn should_pass_edge_cases() { |
| 127 | + let mut rng = rand::thread_rng(); |
| 128 | + let data = (0..80) |
| 129 | + .map(|_| char::from(rng.gen_range(32..=126))) |
| 130 | + .collect::<String>(); |
| 131 | + |
| 132 | + // Minimum prefix length |
| 133 | + let hrp_str = "a"; |
| 134 | + let hrp = Hrp::parse(hrp_str).expect("valid hrp"); |
| 135 | + let string = |
| 136 | + bech32::encode::<Bech32m>(hrp, data.as_bytes()).expect("failed to encode string"); |
| 137 | + |
| 138 | + assert!(Bech32mFormat::from_str(hrp.as_str(), string.len(), string.as_str()).is_ok()); |
| 139 | + |
| 140 | + // Maximum prefix length |
| 141 | + let hrp_string = "a".repeat(83); |
| 142 | + let hrp = Hrp::parse(hrp_string.as_str()).expect("valid hrp"); |
| 143 | + let string = |
| 144 | + bech32::encode::<Bech32m>(hrp, data.as_bytes()).expect("failed to encode string"); |
| 145 | + assert!(Bech32mFormat::from_str(hrp.as_str(), string.len(), string.as_str()).is_ok()); |
| 146 | + } |
| 147 | + |
| 148 | + #[test] |
| 149 | + fn should_fail_with_invalid_message_id() { |
| 150 | + let string = "at1hs0xk375g4kvw53rcem9nyjsdw5lsv94fl065n77cpt0774nsyysdecaju"; |
| 151 | + let hrp = "at"; |
| 152 | + |
| 153 | + assert_err_contains!( |
| 154 | + Bech32mFormat::from_str(hrp, string.len() + 1, string), |
| 155 | + Error, |
| 156 | + Error::InvalidMessageID { .. } |
| 157 | + ); |
| 158 | + |
| 159 | + assert_err_contains!( |
| 160 | + Bech32mFormat::from_str(hrp, string.len() - 1, string), |
| 161 | + Error, |
| 162 | + Error::InvalidMessageID { .. } |
| 163 | + ); |
| 164 | + |
| 165 | + assert_err_contains!( |
| 166 | + Bech32mFormat::from_str("au", string.len(), string), |
| 167 | + Error, |
| 168 | + Error::InvalidMessageID { .. } |
| 169 | + ); |
| 170 | + } |
| 171 | + |
| 172 | + #[test] |
| 173 | + fn should_not_pass_empty_data_part() { |
| 174 | + let hrp_string = "a"; |
| 175 | + let hrp = Hrp::parse(hrp_string).expect("valid hrp"); |
| 176 | + let string = "a1"; |
| 177 | + assert_err_contains!( |
| 178 | + Bech32mFormat::from_str(hrp.as_str(), string.len(), string), |
| 179 | + Error, |
| 180 | + Error::InvalidBech32mFormat(..) |
| 181 | + ); |
| 182 | + |
| 183 | + // Minimum data part length |
| 184 | + let data = ""; |
| 185 | + let hrp_string = "a"; |
| 186 | + let hrp = Hrp::parse(hrp_string).expect("valid hrp"); |
| 187 | + let string = |
| 188 | + bech32::encode::<Bech32m>(hrp, data.as_bytes()).expect("failed to encode string"); |
| 189 | + |
| 190 | + assert_err_contains!( |
| 191 | + Bech32mFormat::from_str(hrp.as_str(), string.len(), string.as_str()), |
| 192 | + Error, |
| 193 | + Error::InvalidBech32m(..) |
| 194 | + ); |
| 195 | + } |
| 196 | +} |
0 commit comments