baseh 1.1.0

baseH codec: fixed-length, checksummed, optionally permuted human-readable identifiers
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
//! Full encode/decode flow (spec sections 3, 8, 9, 10, 11, 12 and 18).

use std::collections::HashSet;

use num_bigint::BigUint;

use crate::basen::{decode_base_n, encode_base_n};
use crate::checksum::calculate_checksum;
use crate::error::{BasehError, ErrorCode};
use crate::feistel::{inverse_permute, permute};
use crate::profile::{prepare_profile, Permutation, PreparedProfile, Profile};

/// Built-in spoken-confusion candidate maps (spec 3.3).
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum ConfusionProfile {
    /// No candidates: correction always fails with INVALID_CHECKSUM.
    /// This is the default, matching the reference decoder.
    #[default]
    None,
    /// B/D and P/T.
    Light,
    /// Light plus M/N and V/W.
    Medium,
    /// Medium plus F/S and C/G.
    Heavy,
}

impl ConfusionProfile {
    fn map(self) -> &'static [(char, &'static [char])] {
        match self {
            ConfusionProfile::None => &[],
            ConfusionProfile::Light => {
                &[('B', &['D']), ('D', &['B']), ('P', &['T']), ('T', &['P'])]
            }
            ConfusionProfile::Medium => &[
                ('B', &['D']),
                ('D', &['B']),
                ('P', &['T']),
                ('T', &['P']),
                ('M', &['N']),
                ('N', &['M']),
                ('V', &['W']),
                ('W', &['V']),
            ],
            ConfusionProfile::Heavy => &[
                ('B', &['D']),
                ('D', &['B']),
                ('P', &['T']),
                ('T', &['P']),
                ('M', &['N']),
                ('N', &['M']),
                ('V', &['W']),
                ('W', &['V']),
                ('F', &['S']),
                ('S', &['F']),
                ('C', &['G']),
                ('G', &['C']),
            ],
        }
    }
}

/// Decode options (spec 12.2). Defaults: strict input, no correction.
#[derive(Debug, Clone, PartialEq, Eq, Default)]
pub struct DecodeOptions {
    /// Remove ASCII spaces during normalization in addition to separators.
    pub accept_spaces: bool,
    /// Attempt single-symbol spoken-confusion correction after a checksum failure.
    pub try_correction: bool,
    pub confusion_profile: ConfusionProfile,
    /// 0 or 1 in version 1. Anything above 1 is treated as 1.
    pub max_corrections: u32,
}

impl DecodeOptions {
    pub fn strict() -> Self {
        DecodeOptions::default()
    }
}

/// Successful decode result (spec 12.2).
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct DecodeResult {
    pub id: BigUint,
    pub canonical_code: String,
    /// True when the normalized input differed from the canonical code.
    pub corrected: bool,
}

/// Non-throwing validation result (spec 12.4). Never carries an internal ID.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ValidateOutcome {
    pub valid: bool,
    pub canonical_code: Option<String>,
    pub reason: Option<ErrorCode>,
}

const MAX_CANDIDATES: usize = 64;

fn is_ascii_ws(c: char) -> bool {
    matches!(c, '\t' | '\n' | '\x0B' | '\x0C' | '\r' | ' ')
}

/// Spec 3.1 normalization, steps 1-7. Returns the raw unformatted chars.
fn normalize(
    input: &str,
    profile: &PreparedProfile,
    accept_spaces: bool,
) -> Result<Vec<char>, BasehError> {
    let trimmed = input.trim_matches(is_ascii_ws);
    let mut s: String = if profile.profile.separator.is_empty() {
        trimmed.to_string()
    } else {
        trimmed.replace(&profile.profile.separator, "")
    };
    if accept_spaces {
        s = s.replace(' ', "");
    }
    let p = &profile.profile;
    let normalized: Vec<char> = s
        .chars()
        .map(|c| {
            let c = if p.case_sensitive {
                c
            } else {
                c.to_ascii_uppercase()
            };
            *profile.aliases_norm.get(&c).unwrap_or(&c)
        })
        .collect();
    // Spec 3.1 step 6 runs before spec 3.4 re-padding, so padded zero
    // symbols never raise INVALID_CHARACTER.
    let allowed: HashSet<char> = profile
        .body_alphabet_norm
        .iter()
        .chain(profile.checksum_alphabet_norm.iter())
        .copied()
        .collect();
    for ch in &normalized {
        if !allowed.contains(ch) {
            return Err(BasehError::customer(
                ErrorCode::InvalidCharacter,
                format!("Symbol {ch:?} is not accepted"),
            ));
        }
    }
    let expected = p.body_length + p.checksum_length;
    // Spec 3.4: a code that lost leading zero body symbols is re-padded with
    // the body zero symbol. The checksum symbols always remain, so the split
    // point is unambiguous. A fully stripped no-checksum code would be empty
    // and stays a length error.
    let mut normalized = normalized;
    if normalized.len() < expected && normalized.len() >= p.checksum_length.max(1) {
        let zero = profile.body_alphabet_norm[0];
        let mut padded = vec![zero; expected - normalized.len()];
        padded.extend(normalized);
        normalized = padded;
    }
    if normalized.len() != expected {
        return Err(BasehError::customer(
            ErrorCode::InvalidLength,
            format!("Expected {} symbols, got {}", expected, normalized.len()),
        ));
    }
    Ok(normalized)
}

/// Spec 11. Grouping is presentation only; skipped when the separator is empty.
fn format_raw(raw: &[char], profile: &PreparedProfile) -> String {
    let p = &profile.profile;
    if p.separator.is_empty() {
        return raw.iter().collect();
    }
    let mut parts: Vec<String> = Vec::with_capacity(p.grouping.len());
    let mut offset = 0;
    for size in &p.grouping {
        parts.push(raw[offset..offset + size].iter().collect());
        offset += size;
    }
    parts.join(&p.separator)
}

/// Spec 10. Substitution-only candidate generation, capped and deduplicated.
fn generate_candidates(
    body: &[char],
    confusion: &[(char, Vec<char>)],
    max_edits: u32,
) -> Result<Vec<Vec<char>>, BasehError> {
    if max_edits == 0 {
        return Ok(Vec::new());
    }
    let mut results: Vec<Vec<char>> = Vec::new();
    let mut seen: HashSet<Vec<char>> = HashSet::new();
    for pos in 0..body.len() {
        let source = body[pos];
        for (map_source, replacements) in confusion {
            if *map_source != source {
                continue;
            }
            for replacement in replacements.iter() {
                let mut candidate = body.to_vec();
                candidate[pos] = *replacement;
                if seen.insert(candidate.clone()) {
                    results.push(candidate);
                    if results.len() > MAX_CANDIDATES {
                        return Err(BasehError::new(
                            ErrorCode::TooManyCandidates,
                            "Candidate generation exceeded 64 entries",
                            false,
                        ));
                    }
                }
            }
        }
    }
    Ok(results)
}

/// A baseH codec bound to a validated profile. Pure and stateless; safe to
/// share across threads.
pub struct Baseh {
    profile: PreparedProfile,
}

impl Baseh {
    /// Validate the profile per spec 2.2 and 18 and bind it. Invalid profiles
    /// are rejected here (at startup), never on the first customer request.
    pub fn new(profile: Profile) -> Result<Baseh, BasehError> {
        Ok(Baseh {
            profile: prepare_profile(profile)?,
        })
    }

    /// Spec 4: `body_alphabet_len ^ body_length` (after any vowel stripping).
    pub fn capacity(&self) -> &BigUint {
        &self.profile.capacity
    }

    /// The validated profile this codec was built from.
    pub fn profile(&self) -> &Profile {
        &self.profile.profile
    }

    /// Spec 8, including the spec 18 blocklist scan.
    pub fn encode(&self, id: &BigUint) -> Result<String, BasehError> {
        if *id >= self.profile.capacity {
            return Err(BasehError::customer(
                ErrorCode::OutOfRange,
                format!("ID {id} is outside the profile capacity"),
            ));
        }
        let p = &self.profile.profile;
        let mut value = id.clone();
        if let Permutation::FeistelV1 {
            key_bytes, rounds, ..
        } = &p.permutation
        {
            value = permute(
                &value,
                &self.profile.capacity,
                &p.profile_id,
                key_bytes,
                *rounds,
            )?;
        }
        let body = encode_base_n(&value, &self.profile.body_alphabet_norm, p.body_length);
        let body_chars: Vec<char> = body.chars().collect();
        let checksum = calculate_checksum(&self.profile, &body_chars)?;
        let mut raw = body_chars;
        raw.extend(checksum.chars());
        // Spec 18.2: case-insensitive substring scan over the raw code.
        if !self.profile.blocklist.is_empty() {
            let upper: String = raw
                .iter()
                .map(|c| c.to_ascii_uppercase())
                .collect::<String>();
            if self.profile.blocklist.iter().any(|w| upper.contains(w)) {
                return Err(BasehError::new(
                    ErrorCode::BlockedCode,
                    "The generated reference contains a blocked substring",
                    false,
                ));
            }
        }
        Ok(format_raw(&raw, &self.profile))
    }

    /// Spec 9.
    pub fn decode(&self, input: &str, options: &DecodeOptions) -> Result<DecodeResult, BasehError> {
        let raw = normalize(input, &self.profile, options.accept_spaces)?;
        let p = &self.profile.profile;
        let mut body: Vec<char> = raw[..p.body_length].to_vec();
        let supplied_checksum: Vec<char> = raw[p.body_length..].to_vec();

        // Spec 3.1 step 6 checks the union of both alphabets (in normalize)
        // and spec 9 adds no partition-specific checks. A body position
        // holding a checksum-only symbol fails as INVALID_CHARACTER inside
        // calculate_checksum; a checksum position holding a body-only symbol
        // simply mismatches below and fails as INVALID_CHECKSUM. This
        // ordering is pinned by the frozen error vectors.
        if calculate_checksum(&self.profile, &body)? != supplied_checksum.iter().collect::<String>()
        {
            if !options.try_correction || options.max_corrections == 0 {
                return Err(BasehError::customer(
                    ErrorCode::InvalidChecksum,
                    "The reference code did not pass validation",
                ));
            }
            // Spec 10: replacements that are not body alphabet symbols are
            // dropped before candidate generation. A suggested symbol the
            // alphabet cannot contain (say a spoken drop on a stripped-
            // alphabet profile) could never validate; generating it anyway
            // would throw INVALID_CHARACTER from the checksum step instead of
            // reporting an honest INVALID_CHECKSUM.
            let body_set: HashSet<char> =
                self.profile.body_alphabet_norm.iter().copied().collect();
            let filtered_map: Vec<(char, Vec<char>)> = options
                .confusion_profile
                .map()
                .iter()
                .filter_map(|(source, replacements)| {
                    let kept: Vec<char> = replacements
                        .iter()
                        .copied()
                        .filter(|r| body_set.contains(r))
                        .collect();
                    if kept.is_empty() {
                        None
                    } else {
                        Some((*source, kept))
                    }
                })
                .collect();
            let candidates =
                generate_candidates(&body, &filtered_map, options.max_corrections)?;
            let mut valid: HashSet<Vec<char>> = HashSet::new();
            for candidate in candidates {
                let candidate_checksum = calculate_checksum(&self.profile, &candidate)?;
                if candidate_checksum == supplied_checksum.iter().collect::<String>() {
                    valid.insert(candidate);
                }
            }
            if valid.is_empty() {
                return Err(BasehError::customer(
                    ErrorCode::InvalidChecksum,
                    "The reference code did not pass validation",
                ));
            }
            if valid.len() > 1 {
                return Err(BasehError::new(
                    ErrorCode::AmbiguousInput,
                    "The reference code matches more than one record",
                    false,
                ));
            }
            body = valid
                .into_iter()
                .next()
                .expect("exactly one valid candidate");
        }

        let mut value = decode_base_n(
            &body,
            self.profile.body_alphabet_norm.len(),
            &self.profile.body_index,
        )?;
        if let Permutation::FeistelV1 {
            key_bytes, rounds, ..
        } = &p.permutation
        {
            value = inverse_permute(
                &value,
                &self.profile.capacity,
                &p.profile_id,
                key_bytes,
                *rounds,
            )?;
        }
        // Spec 18.2: the canonical re-encode may raise BLOCKED_CODE here,
        // since a blocked string could never have been issued.
        let canonical_code = self.encode(&value)?;
        let canonical_raw: Vec<char> = canonical_code
            .chars()
            .filter(|c| !p.separator.contains(*c))
            .collect();
        Ok(DecodeResult {
            id: value,
            canonical_code,
            corrected: raw != canonical_raw,
        })
    }

    /// Spec 12.4. Never fails on user input; never exposes an internal ID.
    pub fn validate(&self, input: &str, options: &DecodeOptions) -> ValidateOutcome {
        match self.decode(input, options) {
            Ok(result) => ValidateOutcome {
                valid: true,
                canonical_code: Some(result.canonical_code),
                reason: None,
            },
            Err(err) => ValidateOutcome {
                valid: false,
                canonical_code: None,
                reason: Some(err.code),
            },
        }
    }
}