Skip to main content

libkeri/cesr/
mod.rs

1use crate::errors::MatterError;
2use crate::keri::KERIError;
3use base64::{engine::general_purpose, Engine};
4use num_bigint::BigUint;
5use num_traits::ToPrimitive;
6use once_cell::sync::Lazy;
7use std::any::Any;
8use std::collections::HashMap;
9use std::fmt::Display;
10use std::{fmt, str};
11
12pub mod bexter;
13pub mod cigar;
14pub mod counting;
15pub mod dater;
16pub mod diger;
17pub mod ilker;
18pub mod indexing;
19pub mod labeler;
20pub mod number;
21pub mod pather;
22pub mod prefixer;
23pub mod saider;
24pub mod seqner;
25pub mod signing;
26pub mod tagger;
27pub mod texter;
28pub mod tholder;
29pub mod verfer;
30
31#[derive(Debug, Clone, PartialEq)]
32pub struct Versionage {
33    pub major: u32,
34    pub minor: u32,
35}
36pub const VERSION: Versionage = Versionage { major: 1, minor: 0 };
37#[allow(dead_code)]
38pub const VRSN_1_0: Versionage = Versionage { major: 1, minor: 0 };
39#[allow(dead_code)]
40pub const VRSN_2_0: Versionage = Versionage { major: 2, minor: 0 };
41
42pub const PAD: &str = "_";
43
44impl Display for Versionage {
45    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
46        write!(f, "{}.{}", self.major, self.minor)
47    }
48}
49
50impl From<String> for Versionage {
51    fn from(version_str: String) -> Self {
52        // Try to extract version information from the string
53        if let Ok(versionage) = Self::parse_version_string(&version_str) {
54            return versionage;
55        }
56
57        // Default to version 1.0 if string can't be parsed
58        Versionage { major: 1, minor: 0 }
59    }
60}
61
62impl From<&str> for Versionage {
63    fn from(version_str: &str) -> Self {
64        Self::from(version_str.to_string())
65    }
66}
67
68impl Versionage {
69    pub fn to_vec(&self) -> Vec<u8> {
70        let mut vec = Vec::new();
71        vec.push(self.major as u8);
72        vec.push(self.minor as u8);
73        vec
74    }
75
76    /// Extracts version information from a KERI version string
77    /// Expects string in format like "KERI10JSON000000_" where
78    /// the first digit after KERI is the major version and the second is minor
79    fn parse_version_string(version_str: &str) -> Result<Self, KERIError> {
80        // Ensure the string is long enough to contain version info
81        if version_str.len() < 6 {
82            return Err(KERIError::VersionError(format!(
83                "Version string too short: {}",
84                version_str
85            )));
86        }
87
88        // Check for "KERI" prefix
89        if !version_str.starts_with("KERI") {
90            return Err(KERIError::VersionError(format!(
91                "Invalid version string prefix: {}",
92                version_str
93            )));
94        }
95
96        // Extract the major and minor version numbers (at positions 4 and 5)
97        let major_char = version_str.chars().nth(4).unwrap();
98        let minor_char = version_str.chars().nth(5).unwrap();
99
100        // Convert from hex character to integer
101        let major = u32::from_str_radix(&major_char.to_string(), 16).map_err(|_| {
102            KERIError::VersionError(format!("Invalid major version: {}", major_char))
103        })?;
104
105        let minor = u32::from_str_radix(&minor_char.to_string(), 16).map_err(|_| {
106            KERIError::VersionError(format!("Invalid minor version: {}", minor_char))
107        })?;
108
109        Ok(Versionage { major, minor })
110    }
111}
112
113/// Maps Base64 index to corresponding character
114pub static B64_CHR_BY_IDX: Lazy<HashMap<u8, char>> = Lazy::new(|| {
115    let mut map = HashMap::new();
116
117    // A-Z: ASCII 65-90, indices 0-25
118    for (idx, c) in (65u8..91u8).enumerate() {
119        map.insert(idx as u8, c as char);
120    }
121
122    // a-z: ASCII 97-122, indices 26-51
123    for (idx, c) in (97u8..123u8).enumerate() {
124        map.insert((idx + 26) as u8, c as char);
125    }
126
127    // 0-9: ASCII 48-57, indices 52-61
128    for (idx, c) in (48u8..58u8).enumerate() {
129        map.insert((idx + 52) as u8, c as char);
130    }
131
132    // Special characters
133    map.insert(62, '-');
134    map.insert(63, '_');
135
136    map
137});
138
139/// Security tiers for secret derivation
140#[derive(Debug, Clone, PartialEq, Eq, Hash)]
141pub enum Tiers {
142    /// Low security tier
143    LOW,
144    /// Medium security tier
145    MED,
146    /// High security tier
147    HIGH,
148}
149
150impl Tiers {
151    /// String value for the tier
152    pub const LOW: &'static str = "low";
153    /// String value for the tier
154    pub const MED: &'static str = "med";
155    /// String value for the tier
156    pub const HIGH: &'static str = "high";
157}
158
159impl From<&str> for Tiers {
160    fn from(s: &str) -> Self {
161        match s {
162            "low" => Tiers::LOW,
163            "med" => Tiers::MED,
164            "high" => Tiers::HIGH,
165            _ => Tiers::LOW, // Default to LOW for unrecognized values
166        }
167    }
168}
169
170impl Display for Tiers {
171    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
172        let str = match self {
173            Tiers::LOW => "low",
174            Tiers::MED => "med",
175            Tiers::HIGH => "high",
176        };
177        write!(f, "{}", str)
178    }
179}
180
181/// Maps Base64 character to corresponding index
182#[allow(dead_code)]
183pub static B64_IDX_BY_CHR: Lazy<HashMap<char, u8>> = Lazy::new(|| {
184    let mut map = HashMap::new();
185
186    // Invert the B64_CHR_BY_IDX mapping
187    for (&idx, &c) in B64_CHR_BY_IDX.iter() {
188        map.insert(c, idx);
189    }
190
191    map
192});
193
194#[allow(dead_code)]
195pub mod cold_dex {
196    use once_cell::sync::Lazy;
197    use std::collections::HashMap;
198
199    // Constants for code type values
200    pub const ANB64: u8 = 0o0; // Annotated CESR B64
201    pub const CTB64: u8 = 0o1; // CountCode Base64
202    pub const OPB64: u8 = 0o2; // OpCode Base64
203    pub const JSON: u8 = 0o3; // JSON Map Event Start
204    pub const MGPK1: u8 = 0o4; // MGPK Fixed Map Event Start
205    pub const CBOR: u8 = 0o5; // CBOR Map Event Start
206    pub const MGPK2: u8 = 0o6; // MGPK Big 16 or 32 Map Event Start
207    pub const CTOPB2: u8 = 0o7; // CountCode or OpCode Base2
208
209    // Map of code types by value
210    pub static MAP: Lazy<HashMap<&'static str, u8>> = Lazy::new(|| {
211        let mut map = HashMap::new();
212        map.insert("ANB64", ANB64);
213        map.insert("CTB64", CTB64);
214        map.insert("OPB64", OPB64);
215        map.insert("JSON,", JSON);
216        map.insert("MGPK1", MGPK1);
217        map.insert("CBOR,", CBOR);
218        map.insert("MGPK2", MGPK2);
219        map.insert("CTOPB2", CTOPB2);
220        map
221    });
222
223    // Tuple of code values only
224    pub static TUPLE: Lazy<Vec<u8>> =
225        Lazy::new(|| vec![ANB64, CTB64, OPB64, JSON, MGPK1, CBOR, MGPK2, CTOPB2]);
226}
227
228#[derive(Debug, Clone, PartialEq)]
229pub struct Coldage {
230    pub msg: &'static str,
231    pub txt: &'static str,
232    pub bny: &'static str,
233    pub ano: &'static str,
234}
235
236impl Coldage {
237    pub fn new(msg: &'static str, txt: &'static str, bny: &'static str, ano: &'static str) -> Self {
238        Self { msg, txt, bny, ano }
239    }
240}
241
242impl Default for Coldage {
243    fn default() -> Self {
244        Self {
245            msg: "msg",
246            txt: "txt",
247            bny: "bny",
248            ano: "ano",
249        }
250    }
251}
252
253impl Display for Coldage {
254    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
255        write!(
256            f,
257            "Coldage(msg='{}', txt='{}', bny='{}', ano='{}')",
258            self.msg, self.txt, self.bny, self.ano
259        )
260    }
261}
262
263// Define a constant similar to Colds in Python
264pub const COLDS: Coldage = Coldage {
265    msg: "msg",
266    txt: "txt",
267    bny: "bny",
268    ano: "ano",
269};
270
271/// Returns status string of cold start of stream ims bytearray by looking
272/// at first triplet of first byte to determine if message or counter code
273/// and if counter code whether Base64 or Base2 representation
274///
275/// First three bits:
276/// 0o0 = 000 annotated cesr
277/// 0o1 = 001 cntcode B64
278/// 0o2 = 010 opcode B64
279/// 0o3 = 011 json
280/// 0o4 = 100 mgpk
281/// 0o5 = 101 cbor
282/// 0o6 = 110 mgpk
283/// 0o7 = 111 cntcode B2 or opcode B2
284///
285/// counter B64 in (0o1, 0o2) return 'txt'
286/// counter B2 in (0o7)  return 'bny'
287/// event in (0o3, 0o4, 0o5, 0o6)  return 'msg'
288/// annotated in (0o0)  return 'ano'
289pub fn sniff(ims: &[u8]) -> Result<&'static str, MatterError> {
290    if ims.is_empty() {
291        return Err(MatterError::ShortageError("Need more bytes.".to_string()));
292    }
293
294    // Extract the first 3 bits (tritet) by shifting right 5 bits
295    let tritet = ims[0] >> 5;
296
297    if tritet == cold_dex::JSON
298        || tritet == cold_dex::MGPK1
299        || tritet == cold_dex::CBOR
300        || tritet == cold_dex::MGPK2
301    {
302        return Ok(COLDS.msg);
303    }
304
305    if tritet == cold_dex::CTB64 || tritet == cold_dex::OPB64 {
306        return Ok(COLDS.txt);
307    }
308
309    if tritet == cold_dex::CTOPB2 {
310        return Ok(COLDS.bny);
311    }
312
313    if tritet == cold_dex::ANB64 {
314        return Ok(COLDS.ano);
315    }
316
317    Err(MatterError::ColdStartError(format!(
318        "Unexpected tritet={} at stream start.",
319        tritet
320    )))
321}
322
323#[allow(dead_code)]
324pub mod trait_dex {
325    use once_cell::sync::Lazy;
326    use std::collections::HashMap;
327
328    /// EstOnly - Only allow establishment events. Inception only.
329    pub const EST_ONLY: &str = "EO";
330
331    /// DoNotDelegate - Do not allow delegated identifiers. Inception only.
332    pub const DO_NOT_DELEGATE: &str = "DND";
333
334    /// RegistrarBackers - Registrar backer provided in Registrar seal in this event
335    pub const REGISTRAR_BACKERS: &str = "RB";
336
337    /// NoBackers - Do not allow any (registrar backers). Inception and Rotation in v2.
338    pub const NO_BACKERS: &str = "NB";
339
340    /// NoRegistrarBackers - Do not allow any registrar backers. Inception and Rotation.
341    pub const NO_REGISTRAR_BACKERS: &str = "NRB";
342
343    /// DelegateIsDelegator - Treat delegate AIDs same as their delegator. Inception only
344    pub const DELEGATE_IS_DELEGATOR: &str = "DID";
345
346    // Create a HashMap from name to value
347    pub static MAP: Lazy<HashMap<&'static str, &'static str>> = Lazy::new(|| {
348        let mut map = HashMap::new();
349        map.insert("EST_ONLY", EST_ONLY);
350        map.insert("DO_NOT_DELEGATE", DO_NOT_DELEGATE);
351        map.insert("REGISTRAR_BACKERS", REGISTRAR_BACKERS);
352        map.insert("NO_BACKERS", NO_BACKERS);
353        map.insert("NO_REGISTRAR_BACKERS", NO_REGISTRAR_BACKERS);
354        map.insert("DELEGATE_IS_DELEGATOR", DELEGATE_IS_DELEGATOR);
355
356        map
357    });
358
359    pub static TUPLE: [&'static str; 6] = [
360        EST_ONLY,
361        DO_NOT_DELEGATE,
362        REGISTRAR_BACKERS,
363        NO_BACKERS,
364        NO_REGISTRAR_BACKERS,
365        DELEGATE_IS_DELEGATOR,
366    ];
367}
368
369/// Various derivation codes for Matter types
370#[allow(dead_code)]
371pub mod mtr_dex {
372    pub const ED25519_SEED: &str = "A"; // Ed25519 256 bit random seed for private key
373    pub const ED25519N: &str = "B"; // Ed25519 verification key non-transferable, basic derivation
374    pub const X25519: &str = "C"; // X25519 public encryption key, may be converted from Ed25519 or Ed25519N
375    pub const ED25519: &str = "D"; // Ed25519 verification key basic derivation
376    pub const BLAKE3_256: &str = "E"; // Blake3 256 bit digest self-addressing derivation
377    pub const BLAKE2B_256: &str = "F"; // Blake2b 256 bit digest self-addressing derivation
378    pub const BLAKE2S_256: &str = "G"; // Blake2s 256 bit digest self-addressing derivation
379    pub const SHA3_256: &str = "H"; // SHA3 256 bit digest self-addressing derivation
380    pub const SHA2_256: &str = "I"; // SHA2 256 bit digest self-addressing derivation
381    pub const ECDSA_256K1_SEED: &str = "J"; // ECDSA secp256k1 256 bit random Seed for private key
382    pub const ED448_SEED: &str = "K"; // Ed448 448 bit random Seed for private key
383    pub const X448: &str = "L"; // X448 public encryption key, converted from Ed448
384    pub const SHORT: &str = "M"; // Short 2 byte b2 number
385    pub const BIG: &str = "N"; // Big 8 byte b2 number
386    pub const X25519_PRIVATE: &str = "O"; // X25519 private decryption key/seed, may be converted from Ed25519
387    pub const X25519_CIPHER_SEED: &str = "P"; // X25519 sealed box 124 char qb64 Cipher of 44 char qb64 Seed
388    pub const ECDSA_256R1_SEED: &str = "Q"; // ECDSA secp256r1 256 bit random Seed for private key
389    pub const TALL: &str = "R"; // Tall 5 byte b2 number
390    pub const LARGE: &str = "S"; // Large 11 byte b2 number
391    pub const GREAT: &str = "T"; // Great 14 byte b2 number
392    pub const VAST: &str = "U"; // Vast 17 byte b2 number
393    pub const LABEL1: &str = "V"; // Label1 1 bytes for label lead size 1
394    pub const LABEL2: &str = "W"; // Label2 2 bytes for label lead size 0
395    pub const TAG3: &str = "X"; // Tag3  3 B64 encoded chars for special values
396    pub const TAG7: &str = "Y"; // Tag7  7 B64 encoded chars for special values
397    pub const BLIND: &str = "Z"; // Blinding factor 256 bits, Cryptographic strength deterministically generated from random salt
398    pub const SALT_128: &str = "0A"; // random salt/seed/nonce/private key or number of length 128 bits (Huge)
399    pub const ED25519_SIG: &str = "0B"; // Ed25519 signature
400    pub const ECDSA_256K1_SIG: &str = "0C"; // ECDSA secp256k1 signature
401    pub const BLAKE3_512: &str = "0D"; // Blake3 512 bit digest self-addressing derivation
402    pub const BLAKE2B_512: &str = "0E"; // Blake2b 512 bit digest self-addressing derivation
403    pub const SHA3_512: &str = "0F"; // SHA3 512 bit digest self-addressing derivation
404    pub const SHA2_512: &str = "0G"; // SHA2 512 bit digest self-addressing derivation
405    pub const LONG: &str = "0H"; // Long 4 byte b2 number
406    pub const ECDSA_256R1_SIG: &str = "0I"; // ECDSA secp256r1 signature
407    pub const TAG1: &str = "0J"; // Tag1 1 B64 encoded char + 1 prepad for special values
408    pub const TAG2: &str = "0K"; // Tag2 2 B64 encoded chars for for special values
409    pub const TAG5: &str = "0L"; // Tag5 5 B64 encoded chars + 1 prepad for special values
410    pub const TAG6: &str = "0M"; // Tag6 6 B64 encoded chars for special values
411    pub const TAG9: &str = "0N"; // Tag9 9 B64 encoded chars + 1 prepad for special values
412    pub const TAG10: &str = "0O"; // Tag10 10 B64 encoded chars for special values
413    pub const GRAM_HEAD_NECK: &str = "0P"; // GramHeadNeck 32 B64 chars memogram head with neck
414    pub const GRAM_HEAD: &str = "0Q"; // GramHead 28 B64 chars memogram head only
415    pub const GRAM_HEAD_AID_NECK: &str = "0R"; // GramHeadAIDNeck 76 B64 chars memogram head with AID and neck
416    pub const GRAM_HEAD_AID: &str = "0S"; // GramHeadAID 72 B64 chars memogram head with AID only
417    pub const ECDSA_256K1N: &str = "1AAA"; // ECDSA secp256k1 verification key non-transferable, basic derivation
418    pub const ECDSA_256K1: &str = "1AAB"; // ECDSA public verification or encryption key, basic derivation
419    pub const ED448N: &str = "1AAC"; // Ed448 non-transferable prefix public signing verification key. Basic derivation
420    pub const ED448: &str = "1AAD"; // Ed448 public signing verification key. Basic derivation
421    pub const ED448_SIG: &str = "1AAE"; // Ed448 signature. Self-signing derivation
422    pub const TAG4: &str = "1AAF"; // Tag4 4 B64 encoded chars for special values
423    pub const DATE_TIME: &str = "1AAG"; // Base64 custom encoded 32 char ISO-8601 DateTime
424    pub const X25519_CIPHER_SALT: &str = "1AAH"; // X25519 sealed box 100 char qb64 Cipher of 24 char qb64 Salt
425    pub const ECDSA_256R1N: &str = "1AAI"; // ECDSA secp256r1 verification key non-transferable, basic derivation
426    pub const ECDSA_256R1: &str = "1AAJ"; // ECDSA secp256r1 verification or encryption key, basic derivation
427    pub const NULL: &str = "1AAK"; // Null None or empty value
428    pub const NO: &str = "1AAL"; // No Falsey Boolean value
429    pub const YES: &str = "1AAM"; // Yes Truthy Boolean value
430    pub const TAG8: &str = "1AAN"; // Tag8 8 B64 encoded chars for special values
431    pub const TBD0S: &str = "1__-"; // Testing purposes only, fixed special values with non-empty raw lead size 0
432    pub const TBD0: &str = "1___"; // Testing purposes only, fixed with lead size 0
433    pub const TBD1S: &str = "2__-"; // Testing purposes only, fixed special values with non-empty raw lead size 1
434    pub const TBD1: &str = "2___"; // Testing purposes only, fixed with lead size 1
435    pub const TBD2S: &str = "3__-"; // Testing purposes only, fixed special values with non-empty raw lead size 2
436    pub const TBD2: &str = "3___"; // Testing purposes only, fixed with lead size 2
437    pub const STR_B64_L0: &str = "4A"; // String Base64 only lead size 0
438    pub const STR_B64_L1: &str = "5A"; // String Base64 only lead size 1
439    pub const STR_B64_L2: &str = "6A"; // String Base64 only lead size 2
440    pub const STR_B64_BIG_L0: &str = "7AAA"; // String Base64 only big lead size 0
441    pub const STR_B64_BIG_L1: &str = "8AAA"; // String Base64 only big lead size 1
442    pub const STR_B64_BIG_L2: &str = "9AAA"; // String Base64 only big lead size 2
443    pub const BYTES_L0: &str = "4B"; // Byte String lead size 0
444    pub const BYTES_L1: &str = "5B"; // Byte String lead size 1
445    pub const BYTES_L2: &str = "6B"; // Byte String lead size 2
446    pub const BYTES_BIG_L0: &str = "7AAB"; // Byte String big lead size 0
447    pub const BYTES_BIG_L1: &str = "8AAB"; // Byte String big lead size 1
448    pub const BYTES_BIG_L2: &str = "9AAB"; // Byte String big lead size 2
449    pub const X25519_CIPHER_L0: &str = "4C"; // X25519 sealed box cipher bytes of sniffable stream plaintext lead size 0
450    pub const X25519_CIPHER_L1: &str = "5C"; // X25519 sealed box cipher bytes of sniffable stream plaintext lead size 1
451    pub const X25519_CIPHER_L2: &str = "6C"; // X25519 sealed box cipher bytes of sniffable stream plaintext lead size 2
452    pub const X25519_CIPHER_BIG_L0: &str = "7AAC"; // X25519 sealed box cipher bytes of sniffable stream plaintext big lead size 0
453    pub const X25519_CIPHER_BIG_L1: &str = "8AAC"; // X25519 sealed box cipher bytes of sniffable stream plaintext big lead size 1
454    pub const X25519_CIPHER_BIG_L2: &str = "9AAC"; // X25519 sealed box cipher bytes of sniffable stream plaintext big lead size 2
455    pub const X25519_CIPHER_QB64_L0: &str = "4D"; // X25519 sealed box cipher bytes of QB64 plaintext lead size 0
456    pub const X25519_CIPHER_QB64_L1: &str = "5D"; // X25519 sealed box cipher bytes of QB64 plaintext lead size 1
457    pub const X25519_CIPHER_QB64_L2: &str = "6D"; // X25519 sealed box cipher bytes of QB64 plaintext lead size 2
458    pub const X25519_CIPHER_QB64_BIG_L0: &str = "7AAD"; // X25519 sealed box cipher bytes of QB64 plaintext big lead size 0
459    pub const X25519_CIPHER_QB64_BIG_L1: &str = "8AAD"; // X25519 sealed box cipher bytes of QB64 plaintext big lead size 1
460    pub const X25519_CIPHER_QB64_BIG_L2: &str = "9AAD"; // X25519 sealed box cipher bytes of QB64 plaintext big lead size 2
461    pub const X25519_CIPHER_QB2_L0: &str = "4E"; // X25519 sealed box cipher bytes of QB2 plaintext lead size 0
462    pub const X25519_CIPHER_QB2_L1: &str = "5E"; // X25519 sealed box cipher bytes of QB2 plaintext lead size 1
463    pub const X25519_CIPHER_QB2_L2: &str = "6E"; // X25519 sealed box cipher bytes of QB2 plaintext lead size 2
464    pub const X25519_CIPHER_QB2_BIG_L0: &str = "7AAE"; // X25519 sealed box cipher bytes of QB2 plaintext big lead size 0
465    pub const X25519_CIPHER_QB2_BIG_L1: &str = "8AAE"; // X25519 sealed box cipher bytes of QB2 plaintext big lead size 1
466    pub const X25519_CIPHER_QB2_BIG_L2: &str = "9AAE"; // X25519 sealed box cipher bytes of QB2 plaintext big lead size 2
467}
468
469// Create a HashMap from name to value
470#[allow(dead_code)]
471pub static MTR_DEX_MAP: Lazy<HashMap<&'static str, &'static str>> = Lazy::new(|| {
472    let mut map = HashMap::new();
473    map.insert("ED25519_SEED", mtr_dex::ED25519_SEED);
474    map.insert("ED25519N", mtr_dex::ED25519N);
475    map.insert("X25519", mtr_dex::X25519);
476    map.insert("ED25519", mtr_dex::ED25519);
477    map.insert("BLAKE3_256", mtr_dex::BLAKE3_256);
478    map.insert("BLAKE2B_256", mtr_dex::BLAKE2B_256);
479    map.insert("BLAKE2S_256", mtr_dex::BLAKE2S_256);
480    map.insert("SHA3_256", mtr_dex::SHA3_256);
481    map.insert("SHA2_256", mtr_dex::SHA2_256);
482    map.insert("ECDSA_256K1_SEED", mtr_dex::ECDSA_256K1_SEED);
483    map.insert("ED448_SEED", mtr_dex::ED448_SEED);
484    map.insert("X448", mtr_dex::X448);
485    map.insert("SHORT", mtr_dex::SHORT);
486    map.insert("BIG", mtr_dex::BIG);
487    map.insert("X25519_PRIVATE", mtr_dex::X25519_PRIVATE);
488    map.insert("X25519_CIPHER_SEED", mtr_dex::X25519_CIPHER_SEED);
489    map.insert("ECDSA_256R1_SEED", mtr_dex::ECDSA_256R1_SEED);
490    map.insert("TALL", mtr_dex::TALL);
491    map.insert("LARGE", mtr_dex::LARGE);
492    map.insert("GREAT", mtr_dex::GREAT);
493    map.insert("VAST", mtr_dex::VAST);
494    map.insert("LABEL1", mtr_dex::LABEL1);
495    map.insert("LABEL2", mtr_dex::LABEL2);
496    map.insert("TAG3", mtr_dex::TAG3);
497    map.insert("TAG7", mtr_dex::TAG7);
498    map.insert("BLIND", mtr_dex::BLIND);
499    map.insert("SALT_128", mtr_dex::SALT_128);
500    map.insert("ED25519_SIG", mtr_dex::ED25519_SIG);
501    map.insert("ECDSA_256K1_SIG", mtr_dex::ECDSA_256K1_SIG);
502    map.insert("BLAKE3_512", mtr_dex::BLAKE3_512);
503    map.insert("BLAKE2B_512", mtr_dex::BLAKE2B_512);
504    map.insert("SHA3_512", mtr_dex::SHA3_512);
505    map.insert("SHA2_512", mtr_dex::SHA2_512);
506    map.insert("LONG", mtr_dex::LONG);
507    map.insert("ECDSA_256R1_SIG", mtr_dex::ECDSA_256R1_SIG);
508    map.insert("TAG1", mtr_dex::TAG1);
509    map.insert("TAG2", mtr_dex::TAG2);
510    map.insert("TAG5", mtr_dex::TAG5);
511    map.insert("TAG6", mtr_dex::TAG6);
512    map.insert("TAG9", mtr_dex::TAG9);
513    map.insert("TAG10", mtr_dex::TAG10);
514    map.insert("GRAM_HEAD_NECK", mtr_dex::GRAM_HEAD_NECK);
515    map.insert("GRAM_HEAD", mtr_dex::GRAM_HEAD);
516    map.insert("GRAM_HEAD_AID_NECK", mtr_dex::GRAM_HEAD_AID_NECK);
517    map.insert("GRAM_HEAD_AID", mtr_dex::GRAM_HEAD_AID);
518    map.insert("ECDSA_256K1N", mtr_dex::ECDSA_256K1N);
519    map.insert("ECDSA_256K1", mtr_dex::ECDSA_256K1);
520    map.insert("ED448N", mtr_dex::ED448N);
521    map.insert("ED448", mtr_dex::ED448);
522    map.insert("ED448_SIG", mtr_dex::ED448_SIG);
523    map.insert("TAG4", mtr_dex::TAG4);
524    map.insert("DATE_TIME", mtr_dex::DATE_TIME);
525    map.insert("X25519_CIPHER_SALT", mtr_dex::X25519_CIPHER_SALT);
526    map.insert("ECDSA_256R1N", mtr_dex::ECDSA_256R1N);
527    map.insert("ECDSA_256R1", mtr_dex::ECDSA_256R1);
528    map.insert("NULL", mtr_dex::NULL);
529    map.insert("NO", mtr_dex::NO);
530    map.insert("YES", mtr_dex::YES);
531    map.insert("TAG8", mtr_dex::TAG8);
532    map.insert("TBD0S", mtr_dex::TBD0S);
533    map.insert("TBD0", mtr_dex::TBD0);
534    map.insert("TBD1S", mtr_dex::TBD1S);
535    map.insert("TBD1", mtr_dex::TBD1);
536    map.insert("TBD2S", mtr_dex::TBD2S);
537    map.insert("TBD2", mtr_dex::TBD2);
538    map.insert("STR_B64_L0", mtr_dex::STR_B64_L0);
539    map.insert("STR_B64_L1", mtr_dex::STR_B64_L1);
540    map.insert("STR_B64_L2", mtr_dex::STR_B64_L2);
541    map.insert("STR_B64_BIG_L0", mtr_dex::STR_B64_BIG_L0);
542    map.insert("STR_B64_BIG_L1", mtr_dex::STR_B64_BIG_L1);
543    map.insert("STR_B64_BIG_L2", mtr_dex::STR_B64_BIG_L2);
544    map.insert("BYTES_L0", mtr_dex::BYTES_L0);
545    map.insert("BYTES_L1", mtr_dex::BYTES_L1);
546    map.insert("BYTES_L2", mtr_dex::BYTES_L2);
547    map.insert("BYTES_BIG_L0", mtr_dex::BYTES_BIG_L0);
548    map.insert("BYTES_BIG_L1", mtr_dex::BYTES_BIG_L1);
549    map.insert("BYTES_BIG_L2", mtr_dex::BYTES_BIG_L2);
550    map.insert("X25519_CIPHER_L0", mtr_dex::X25519_CIPHER_L0);
551    map.insert("X25519_CIPHER_L1", mtr_dex::X25519_CIPHER_L1);
552    map.insert("X25519_CIPHER_L2", mtr_dex::X25519_CIPHER_L2);
553    map.insert("X25519_CIPHER_BIG_L0", mtr_dex::X25519_CIPHER_BIG_L0);
554    map.insert("X25519_CIPHER_BIG_L1", mtr_dex::X25519_CIPHER_BIG_L1);
555    map.insert("X25519_CIPHER_BIG_L2", mtr_dex::X25519_CIPHER_BIG_L2);
556    map.insert("X25519_CIPHER_QB64_L0", mtr_dex::X25519_CIPHER_QB64_L0);
557    map.insert("X25519_CIPHER_QB64_L1", mtr_dex::X25519_CIPHER_QB64_L1);
558    map.insert("X25519_CIPHER_QB64_L2", mtr_dex::X25519_CIPHER_QB64_L2);
559    map.insert(
560        "X25519_CIPHER_QB64_BIG_L0",
561        mtr_dex::X25519_CIPHER_QB64_BIG_L0,
562    );
563    map.insert(
564        "X25519_CIPHER_QB64_BIG_L1",
565        mtr_dex::X25519_CIPHER_QB64_BIG_L1,
566    );
567    map.insert(
568        "X25519_CIPHER_QB64_BIG_L2",
569        mtr_dex::X25519_CIPHER_QB64_BIG_L2,
570    );
571    map.insert("X25519_CIPHER_QB2_L0", mtr_dex::X25519_CIPHER_QB2_L0);
572    map.insert("X25519_CIPHER_QB2_L1", mtr_dex::X25519_CIPHER_QB2_L1);
573    map.insert("X25519_CIPHER_QB2_L2", mtr_dex::X25519_CIPHER_QB2_L2);
574    map.insert(
575        "X25519_CIPHER_QB2_BIG_L0",
576        mtr_dex::X25519_CIPHER_QB2_BIG_L0,
577    );
578    map.insert(
579        "X25519_CIPHER_QB2_BIG_L1",
580        mtr_dex::X25519_CIPHER_QB2_BIG_L1,
581    );
582    map.insert(
583        "X25519_CIPHER_QB2_BIG_L2",
584        mtr_dex::X25519_CIPHER_QB2_BIG_L2,
585    );
586    map
587});
588
589#[allow(dead_code)]
590pub mod small_vrz_dex {
591    use once_cell::sync::Lazy;
592    use std::collections::HashMap;
593
594    pub const LEAD0: &str = "4"; // First Selector Character for all ls == 0 codes
595    pub const LEAD1: &str = "5"; // First Selector Character for all ls == 1 codes
596    pub const LEAD2: &str = "6"; // First Selector Character for all ls == 2 codes
597
598    // Create a HashMap from name to value
599    pub static MAP: Lazy<HashMap<&'static str, &'static str>> = Lazy::new(|| {
600        let mut map = HashMap::new();
601        map.insert("LEAD0", LEAD0);
602        map.insert("LEAD1", LEAD1);
603        map.insert("LEAD2", LEAD2);
604        map
605    });
606
607    pub static TUPLE: [&'static str; 3] = [LEAD0, LEAD1, LEAD2];
608}
609
610#[allow(dead_code)]
611pub mod large_vrz_dex {
612    use once_cell::sync::Lazy;
613    use std::collections::HashMap;
614
615    pub const LEAD0_BIG: &str = "7"; // First Selector Character for all ls == 0 codes
616    pub const LEAD1_BIG: &str = "8"; // First Selector Character for all ls == 1 codes
617    pub const LEAD2_BIG: &str = "9"; // First Selector Character for all ls == 2 codes
618
619    // Create a HashMap from name to value for large_vrz_dex
620    pub static MAP: Lazy<HashMap<&'static str, &'static str>> = Lazy::new(|| {
621        let mut map = HashMap::new();
622        map.insert("LEAD0_BIG", LEAD0_BIG);
623        map.insert("LEAD1_BIG", LEAD1_BIG);
624        map.insert("LEAD2_BIG", LEAD2_BIG);
625        map
626    });
627
628    pub static TUPLE: [&'static str; 3] = [LEAD0_BIG, LEAD1_BIG, LEAD2_BIG];
629}
630
631/// BextCodex is codex of all variable sized Base64 Text (Bext) derivation codes.
632/// Only provides defined codes.
633/// Undefined are left out so that inclusion(exclusion) via contains works.
634#[allow(dead_code)]
635pub mod bex_dex {
636    /// String Base64 Only Leader Size 0
637    pub const STR_B64_L0: &str = "4A";
638
639    /// String Base64 Only Leader Size 1
640    pub const STR_B64_L1: &str = "5A";
641
642    /// String Base64 Only Leader Size 2
643    pub const STR_B64_L2: &str = "6A";
644
645    /// String Base64 Only Big Leader Size 0
646    pub const STR_B64_BIG_L0: &str = "7AAA";
647
648    /// String Base64 Only Big Leader Size 1
649    pub const STR_B64_BIG_L1: &str = "8AAA";
650
651    /// String Base64 Only Big Leader Size 2
652    pub const STR_B64_BIG_L2: &str = "9AAA";
653
654    /// Map of code to size of code (in characters) in Base64
655    pub const MAP: once_cell::sync::Lazy<std::collections::HashMap<&'static str, usize>> =
656        once_cell::sync::Lazy::new(|| {
657            let mut map = std::collections::HashMap::new();
658            map.insert(STR_B64_L0, 2);
659            map.insert(STR_B64_L1, 2);
660            map.insert(STR_B64_L2, 2);
661            map.insert(STR_B64_BIG_L0, 4);
662            map.insert(STR_B64_BIG_L1, 4);
663            map.insert(STR_B64_BIG_L2, 4);
664            map
665        });
666
667    /// Tuple of string constants in order of definition
668    pub const TUPLE: &[&str] = &[
669        STR_B64_L0,
670        STR_B64_L1,
671        STR_B64_L2,
672        STR_B64_BIG_L0,
673        STR_B64_BIG_L1,
674        STR_B64_BIG_L2,
675    ];
676}
677
678/// TextCodex is codex of all variable sized byte string (Text) derivation codes.
679/// Only provides defined codes.
680/// Undefined are left out so that inclusion(exclusion) via contains works.
681#[allow(dead_code)]
682pub mod tex_dex {
683    /// Byte String lead size 0
684    pub const BYTES_L0: &str = "4B";
685
686    /// Byte String lead size 1
687    pub const BYTES_L1: &str = "5B";
688
689    /// Byte String lead size 2
690    pub const BYTES_L2: &str = "6B";
691
692    /// Byte String big lead size 0
693    pub const BYTES_BIG_L0: &str = "7AAB";
694
695    /// Byte String big lead size 1
696    pub const BYTES_BIG_L1: &str = "8AAB";
697
698    /// Byte String big lead size 2
699    pub const BYTES_BIG_L2: &str = "9AAB";
700
701    /// Map of code to size of code (in characters) in Base64
702    pub const MAP: once_cell::sync::Lazy<std::collections::HashMap<&'static str, usize>> =
703        once_cell::sync::Lazy::new(|| {
704            let mut map = std::collections::HashMap::new();
705            map.insert(BYTES_L0, 2);
706            map.insert(BYTES_L1, 2);
707            map.insert(BYTES_L2, 2);
708            map.insert(BYTES_BIG_L0, 4);
709            map.insert(BYTES_BIG_L1, 4);
710            map.insert(BYTES_BIG_L2, 4);
711            map
712        });
713
714    /// Tuple of string constants in order of definition
715    pub const TUPLE: &[&str] = &[
716        BYTES_L0,
717        BYTES_L1,
718        BYTES_L2,
719        BYTES_BIG_L0,
720        BYTES_BIG_L1,
721        BYTES_BIG_L2,
722    ];
723}
724
725/// DigCodex is codex of all digest derivation codes. This is needed to ensure
726/// delegated inception using a self-addressing derivation i.e. digest derivation
727/// code.
728/// Only provides defined codes.
729/// Undefined are left out so that inclusion(exclusion) via contains works.
730#[allow(dead_code)]
731pub mod dig_dex {
732    use once_cell::sync::Lazy;
733    use std::collections::HashMap;
734
735    /// Blake3 256 bit digest self-addressing derivation
736    pub const BLAKE3_256: &str = "E";
737
738    /// Blake2b 256 bit digest self-addressing derivation
739    pub const BLAKE2B_256: &str = "F";
740
741    /// Blake2s 256 bit digest self-addressing derivation
742    pub const BLAKE2S_256: &str = "G";
743
744    /// SHA3 256 bit digest self-addressing derivation
745    pub const SHA3_256: &str = "H";
746
747    /// SHA2 256 bit digest self-addressing derivation
748    pub const SHA2_256: &str = "I";
749
750    /// Blake3 512 bit digest self-addressing derivation
751    pub const BLAKE3_512: &str = "0D";
752
753    /// Blake2b 512 bit digest self-addressing derivation
754    pub const BLAKE2B_512: &str = "0E";
755
756    /// SHA3 512 bit digest self-addressing derivation
757    pub const SHA3_512: &str = "0F";
758
759    /// SHA2 512 bit digest self-addressing derivation
760    pub const SHA2_512: &str = "0G";
761
762    #[allow(dead_code)]
763    pub static MAP: Lazy<HashMap<&'static str, &'static str>> = Lazy::new(|| {
764        let mut map = HashMap::new();
765        map.insert("BLAKE3_256", BLAKE3_256);
766        map.insert("BLAKE2B_256", BLAKE2B_256);
767        map.insert("BLAKE2S_256", BLAKE2S_256);
768        map.insert("SHA3_256", SHA3_256);
769        map.insert("SHA2_256", SHA2_256);
770        map.insert("BLAKE3_512", BLAKE3_512);
771        map.insert("BLAKE2B_512", BLAKE2B_512);
772        map.insert("SHA3_512", SHA3_512);
773        map.insert("SHA2_512", SHA2_512);
774        map
775    });
776
777    pub static TUPLE: [&'static str; 9] = [
778        BLAKE3_256,
779        BLAKE2B_256,
780        BLAKE2S_256,
781        SHA3_256,
782        SHA2_256,
783        BLAKE3_512,
784        BLAKE2B_512,
785        SHA3_512,
786        SHA2_512,
787    ];
788}
789
790/// NumCodex is codex of Base64 derivation codes for compactly representing
791/// numbers across a wide rage of sizes.
792///
793/// Only provides defined codes.
794/// Undefined are left out so that inclusion(exclusion) via contains works.
795#[allow(dead_code)]
796pub mod num_dex {
797    use once_cell::sync::Lazy;
798    use std::collections::HashMap;
799
800    /// Short 2 byte b2 number
801    pub const SHORT: &str = "M";
802
803    /// Long 4 byte b2 number
804    pub const LONG: &str = "0H";
805
806    /// Tall 5 byte b2 number
807    pub const TALL: &str = "R";
808
809    /// Big 8 byte b2 number
810    pub const BIG: &str = "N";
811
812    /// Large 11 byte b2 number
813    pub const LARGE: &str = "S";
814
815    /// Great 14 byte b2 number
816    pub const GREAT: &str = "T";
817
818    /// Huge 16 byte b2 number (same as Salt_128)
819    pub const HUGE: &str = "0A";
820
821    /// Vast 17 byte b2 number
822    pub const VAST: &str = "U";
823
824    pub static MAP: Lazy<HashMap<&'static str, &'static str>> = Lazy::new(|| {
825        let mut map = HashMap::new();
826        map.insert(SHORT, "SHORT");
827        map.insert(LONG, "LONG");
828        map.insert(TALL, "TALL");
829        map.insert(BIG, "BIG");
830        map.insert(LARGE, "LARGE");
831        map.insert(GREAT, "GREAT");
832        map.insert(HUGE, "HUGE");
833        map.insert(VAST, "VAST");
834        map
835    });
836
837    pub static TUPLE: [&'static str; 8] = [SHORT, LONG, TALL, BIG, LARGE, GREAT, HUGE, VAST];
838}
839
840/// TagCodex is codex of Base64 derivation codes for compactly representing
841/// various small Base64 tag values as special code soft part values.
842///
843/// Only provides defined codes.
844/// Undefined are left out so that inclusion(exclusion) via contains works.
845#[allow(dead_code)]
846pub mod tag_dex {
847    use once_cell::sync::Lazy;
848    use std::collections::HashMap;
849
850    /// 1 B64 char tag with 1 pre pad
851    pub const TAG1: &str = "0J";
852
853    /// 2 B64 char tag
854    pub const TAG2: &str = "0K";
855
856    /// 3 B64 char tag
857    pub const TAG3: &str = "X";
858
859    /// 4 B64 char tag
860    pub const TAG4: &str = "1AAF";
861
862    /// 5 B64 char tag with 1 pre pad
863    pub const TAG5: &str = "0L";
864
865    /// 6 B64 char tag
866    pub const TAG6: &str = "0M";
867
868    /// 7 B64 char tag
869    pub const TAG7: &str = "Y";
870
871    /// 8 B64 char tag
872    pub const TAG8: &str = "1AAN";
873
874    /// 9 B64 char tag with 1 pre pad
875    pub const TAG9: &str = "0N";
876
877    /// 10 B64 char tag
878    pub const TAG10: &str = "0O";
879
880    pub static MAP: Lazy<HashMap<&'static str, &'static str>> = Lazy::new(|| {
881        let mut map = HashMap::new();
882        map.insert("TAG1", TAG1);
883        map.insert("TAG2", TAG2);
884        map.insert("TAG3", TAG3);
885        map.insert("TAG4", TAG4);
886        map.insert("TAG5", TAG5);
887        map.insert("TAG6", TAG6);
888        map.insert("TAG7", TAG7);
889        map.insert("TAG8", TAG8);
890        map.insert("TAG9", TAG9);
891        map.insert("TAG10", TAG10);
892        map
893    });
894}
895
896/// LabelCodex is codex of.
897///
898/// Only provides defined codes.
899/// Undefined are left out so that inclusion(exclusion) via contains works.
900#[allow(dead_code)]
901pub mod label_dex {
902    use once_cell::sync::Lazy;
903    use std::collections::HashMap;
904
905    /// 1 B64 char tag with 1 pre pad
906    pub const TAG1: &str = "0J";
907
908    /// 2 B64 char tag
909    pub const TAG2: &str = "0K";
910
911    /// 3 B64 char tag
912    pub const TAG3: &str = "X";
913
914    /// 4 B64 char tag
915    pub const TAG4: &str = "1AAF";
916
917    /// 5 B64 char tag with 1 pre pad
918    pub const TAG5: &str = "0L";
919
920    /// 6 B64 char tag
921    pub const TAG6: &str = "0M";
922
923    /// 7 B64 char tag
924    pub const TAG7: &str = "Y";
925
926    /// 8 B64 char tag
927    pub const TAG8: &str = "1AAN";
928
929    /// 9 B64 char tag with 1 pre pad
930    pub const TAG9: &str = "0N";
931
932    /// 10 B64 char tag
933    pub const TAG10: &str = "0O";
934
935    /// String Base64 Only Leader Size 0
936    pub const STRB64_L0: &str = "4A";
937
938    /// String Base64 Only Leader Size 1
939    pub const STRB64_L1: &str = "5A";
940
941    /// String Base64 Only Leader Size 2
942    pub const STRB64_L2: &str = "6A";
943
944    /// String Base64 Only Big Leader Size 0
945    pub const STRB64_BIG_L0: &str = "7AAA";
946
947    /// String Base64 Only Big Leader Size 1
948    pub const STRB64_BIG_L1: &str = "8AAA";
949
950    /// String Base64 Only Big Leader Size 2
951    pub const STRB64_BIG_L2: &str = "9AAA";
952
953    /// Label1 1 bytes for label lead size 1
954    pub const LABEL1: &str = "V";
955
956    /// Label2 2 bytes for label lead size 0
957    pub const LABEL2: &str = "W";
958
959    /// Byte String lead size 0
960    pub const BYTES_L0: &str = "4B";
961
962    /// Byte String lead size 1
963    pub const BYTES_L1: &str = "5B";
964
965    /// Byte String lead size 2
966    pub const BYTES_L2: &str = "6B";
967
968    /// Byte String big lead size 0
969    pub const BYTES_BIG_L0: &str = "7AAB";
970
971    /// Byte String big lead size 1
972    pub const BYTES_BIG_L1: &str = "8AAB";
973
974    /// Byte String big lead size 2
975    pub const BYTES_BIG_L2: &str = "9AAB";
976
977    pub static MAP: Lazy<HashMap<&'static str, &'static str>> = Lazy::new(|| {
978        let mut map = HashMap::new();
979        map.insert("TAG1", TAG1);
980        map.insert("TAG2", TAG2);
981        map.insert("TAG3", TAG3);
982        map.insert("TAG4", TAG4);
983        map.insert("TAG5", TAG5);
984        map.insert("TAG6", TAG6);
985        map.insert("TAG7", TAG7);
986        map.insert("TAG8", TAG8);
987        map.insert("TAG9", TAG9);
988        map.insert("TAG10", TAG10);
989        map.insert("STRB64_L0", STRB64_L0);
990        map.insert("STRB64_L1", STRB64_L1);
991        map.insert("STRB64_L2", STRB64_L2);
992        map.insert("STRB64_BIG_L0", STRB64_BIG_L0);
993        map.insert("STRB64_BIG_L1", STRB64_BIG_L1);
994        map.insert("STRB64_BIG_L2", STRB64_BIG_L2);
995        map.insert("LABEL1", LABEL1);
996        map.insert("LABEL2", LABEL2);
997        map.insert("BYTES_L0", BYTES_L0);
998        map.insert("BYTES_L1", BYTES_L1);
999        map.insert("BYTES_L2", BYTES_L2);
1000        map.insert("BYTES_BIG_L0", BYTES_BIG_L0);
1001        map.insert("BYTES_BIG_L1", BYTES_BIG_L1);
1002        map.insert("BYTES_BIG_L2", BYTES_BIG_L2);
1003        map
1004    });
1005}
1006
1007/// PreCodex is codex of all identifier prefix derivation codes.
1008/// This is needed to verify valid inception events.
1009/// Only provides defined codes.
1010/// Undefined are left out so that inclusion(exclusion) via contains works.
1011#[allow(dead_code)]
1012pub mod pre_dex {
1013    use once_cell::sync::Lazy;
1014    use std::collections::HashMap;
1015
1016    /// Ed25519 verification key non-transferable, basic derivation
1017    pub const ED25519N: &str = "B";
1018
1019    /// Ed25519 verification key, basic derivation
1020    pub const ED25519: &str = "D";
1021
1022    /// Blake3 256 bit digest self-addressing derivation
1023    pub const BLAKE3_256: &str = "E";
1024
1025    /// Blake2b 256 bit digest self-addressing derivation
1026    pub const BLAKE2B_256: &str = "F";
1027
1028    /// Blake2s 256 bit digest self-addressing derivation
1029    pub const BLAKE2S_256: &str = "G";
1030
1031    /// SHA3 256 bit digest self-addressing derivation
1032    pub const SHA3_256: &str = "H";
1033
1034    /// SHA2 256 bit digest self-addressing derivation
1035    pub const SHA2_256: &str = "I";
1036
1037    /// Blake3 512 bit digest self-addressing derivation
1038    pub const BLAKE3_512: &str = "0D";
1039
1040    /// Blake2b 512 bit digest self-addressing derivation
1041    pub const BLAKE2B_512: &str = "0E";
1042
1043    /// SHA3 512 bit digest self-addressing derivation
1044    pub const SHA3_512: &str = "0F";
1045
1046    /// SHA2 512 bit digest self-addressing derivation
1047    pub const SHA2_512: &str = "0G";
1048
1049    /// ECDSA secp256k1 verification key non-transferable, basic derivation
1050    pub const ECDSA_256K1N: &str = "1AAA";
1051
1052    /// ECDSA public verification or encryption key, basic derivation
1053    pub const ECDSA_256K1: &str = "1AAB";
1054
1055    /// Ed448 verification key non-transferable, basic derivation
1056    pub const ED448N: &str = "1AAC";
1057
1058    /// Ed448 verification key, basic derivation
1059    pub const ED448: &str = "1AAD";
1060
1061    /// Ed448 signature. Self-signing derivation
1062    pub const ED448_SIG: &str = "1AAE";
1063
1064    /// ECDSA secp256r1 verification key non-transferable, basic derivation
1065    pub const ECDSA_256R1N: &str = "1AAI";
1066
1067    /// ECDSA secp256r1 verification or encryption key, basic derivation
1068    pub const ECDSA_256R1: &str = "1AAJ";
1069
1070    pub static MAP: Lazy<HashMap<&'static str, &'static str>> = Lazy::new(|| {
1071        let mut map = HashMap::new();
1072        map.insert("ED25519N", ED25519N);
1073        map.insert("ED25519", ED25519);
1074        map.insert("BLAKE3_256", BLAKE3_256);
1075        map.insert("BLAKE2B_256", BLAKE2B_256);
1076        map.insert("BLAKE2S_256", BLAKE2S_256);
1077        map.insert("SHA3_256", SHA3_256);
1078        map.insert("SHA2_256", SHA2_256);
1079        map.insert("BLAKE3_512", BLAKE3_512);
1080        map.insert("BLAKE2B_512", BLAKE2B_512);
1081        map.insert("SHA3_512", SHA3_512);
1082        map.insert("SHA2_512", SHA2_512);
1083        map.insert("ECDSA_256K1N", ECDSA_256K1N);
1084        map.insert("ECDSA_256K1", ECDSA_256K1);
1085        map.insert("ED448N", ED448N);
1086        map.insert("ED448", ED448);
1087        map.insert("ED448_SIG", ED448_SIG);
1088        map.insert("ECDSA_256R1N", ECDSA_256R1N);
1089        map.insert("ECDSA_256R1", ECDSA_256R1);
1090        map
1091    });
1092
1093    pub static TUPLE: [&'static str; 18] = [
1094        ED25519N,
1095        ED25519,
1096        BLAKE3_256,
1097        BLAKE2B_256,
1098        BLAKE2S_256,
1099        SHA3_256,
1100        SHA2_256,
1101        BLAKE3_512,
1102        BLAKE2B_512,
1103        SHA3_512,
1104        SHA2_512,
1105        ECDSA_256K1N,
1106        ECDSA_256K1,
1107        ED448N,
1108        ED448,
1109        ED448_SIG,
1110        ECDSA_256R1N,
1111        ECDSA_256R1,
1112    ];
1113}
1114
1115/// NonTransCodex is codex of all non-transferable derivation codes
1116/// Only provides defined codes.
1117/// Undefined are left out so that inclusion(exclusion) via contains works.
1118#[allow(dead_code)]
1119pub mod non_trans_dex {
1120    use once_cell::sync::Lazy;
1121    use std::collections::HashMap;
1122
1123    /// Ed25519 verification key non-transferable, basic derivation
1124    pub const ED25519N: &str = "B";
1125
1126    /// ECDSA secp256k1 verification key non-transferable, basic derivation
1127    pub const ECDSA_256K1N: &str = "1AAA";
1128
1129    /// Ed448 verification key non-transferable, basic derivation
1130    pub const ED448N: &str = "1AAC";
1131
1132    /// ECDSA secp256r1 verification key non-transferable, basic derivation
1133    pub const ECDSA_256R1N: &str = "1AAI";
1134
1135    pub static MAP: Lazy<HashMap<&'static str, &'static str>> = Lazy::new(|| {
1136        let mut map = HashMap::new();
1137        map.insert("ED25519N", ED25519N);
1138        map.insert("ECDSA_256K1N", ECDSA_256K1N);
1139        map.insert("ED448N", ED448N);
1140        map.insert("ECDSA_256R1N", ECDSA_256R1N);
1141        map
1142    });
1143
1144    pub static TUPLE: [&'static str; 4] = [ED25519N, ECDSA_256K1N, ED448N, ECDSA_256R1N];
1145}
1146
1147/// PreNonDigCodex is codex of all prefixive but non-digestive derivation codes
1148/// Only provides defined codes.
1149/// Undefined are left out so that inclusion(exclusion) via contains works.
1150#[allow(dead_code)]
1151pub mod pre_non_dig_dex {
1152    use once_cell::sync::Lazy;
1153    use std::collections::HashMap;
1154
1155    /// Ed25519 verification key non-transferable, basic derivation
1156    pub const ED25519N: &str = "B";
1157
1158    /// Ed25519 verification key, basic derivation
1159    pub const ED25519: &str = "D";
1160
1161    /// ECDSA secp256k1 verification key non-transferable, basic derivation
1162    pub const ECDSA_256K1N: &str = "1AAA";
1163
1164    /// ECDSA public verification or encryption key, basic derivation
1165    pub const ECDSA_256K1: &str = "1AAB";
1166
1167    /// Ed448 verification key non-transferable, basic derivation
1168    pub const ED448N: &str = "1AAC";
1169
1170    /// Ed448 verification key, basic derivation
1171    pub const ED448: &str = "1AAD";
1172
1173    /// ECDSA secp256r1 verification key non-transferable, basic derivation
1174    pub const ECDSA_256R1N: &str = "1AAI";
1175
1176    /// ECDSA secp256r1 verification or encryption key, basic derivation
1177    pub const ECDSA_256R1: &str = "1AAJ";
1178
1179    pub static MAP: Lazy<HashMap<&'static str, &'static str>> = Lazy::new(|| {
1180        let mut map = HashMap::new();
1181        map.insert("ED25519N", ED25519N);
1182        map.insert("ED25519", ED25519);
1183        map.insert("ECDSA_256K1N", ECDSA_256K1N);
1184        map.insert("ECDSA_256K1", ECDSA_256K1);
1185        map.insert("ED448N", ED448N);
1186        map.insert("ED448", ED448);
1187        map.insert("ECDSA_256R1N", ECDSA_256R1N);
1188        map.insert("ECDSA_256R1", ECDSA_256R1);
1189        map
1190    });
1191}
1192
1193#[derive(Clone, Copy, Debug)]
1194pub struct Sizage {
1195    pub hs: u32,         // header size
1196    pub ss: u32,         // section size
1197    pub xs: u32,         // extra size
1198    pub fs: Option<u32>, // field size
1199    pub ls: u32,         // list size
1200}
1201
1202pub fn get_sizes() -> HashMap<&'static str, Sizage> {
1203    let mut sizes = HashMap::new();
1204
1205    // Adding all the size entries
1206    sizes.insert(
1207        "A",
1208        Sizage {
1209            hs: 1,
1210            ss: 0,
1211            xs: 0,
1212            fs: Some(44),
1213            ls: 0,
1214        },
1215    ); // Ed25519_Seed
1216    sizes.insert(
1217        "B",
1218        Sizage {
1219            hs: 1,
1220            ss: 0,
1221            xs: 0,
1222            fs: Some(44),
1223            ls: 0,
1224        },
1225    ); // Ed25519N
1226    sizes.insert(
1227        "C",
1228        Sizage {
1229            hs: 1,
1230            ss: 0,
1231            xs: 0,
1232            fs: Some(44),
1233            ls: 0,
1234        },
1235    ); // X25519
1236    sizes.insert(
1237        "D",
1238        Sizage {
1239            hs: 1,
1240            ss: 0,
1241            xs: 0,
1242            fs: Some(44),
1243            ls: 0,
1244        },
1245    ); // Ed25519
1246    sizes.insert(
1247        "E",
1248        Sizage {
1249            hs: 1,
1250            ss: 0,
1251            xs: 0,
1252            fs: Some(44),
1253            ls: 0,
1254        },
1255    ); // Blake3_256
1256    sizes.insert(
1257        "F",
1258        Sizage {
1259            hs: 1,
1260            ss: 0,
1261            xs: 0,
1262            fs: Some(44),
1263            ls: 0,
1264        },
1265    ); // Blake2b_256
1266    sizes.insert(
1267        "G",
1268        Sizage {
1269            hs: 1,
1270            ss: 0,
1271            xs: 0,
1272            fs: Some(44),
1273            ls: 0,
1274        },
1275    ); // Blake2s_256
1276    sizes.insert(
1277        "H",
1278        Sizage {
1279            hs: 1,
1280            ss: 0,
1281            xs: 0,
1282            fs: Some(44),
1283            ls: 0,
1284        },
1285    ); // SHA3_256
1286    sizes.insert(
1287        "I",
1288        Sizage {
1289            hs: 1,
1290            ss: 0,
1291            xs: 0,
1292            fs: Some(44),
1293            ls: 0,
1294        },
1295    ); // SHA2_256
1296    sizes.insert(
1297        "J",
1298        Sizage {
1299            hs: 1,
1300            ss: 0,
1301            xs: 0,
1302            fs: Some(44),
1303            ls: 0,
1304        },
1305    ); // ECDSA_256k1N
1306    sizes.insert(
1307        "K",
1308        Sizage {
1309            hs: 1,
1310            ss: 0,
1311            xs: 0,
1312            fs: Some(76),
1313            ls: 0,
1314        },
1315    ); // ECDSA_256r1N
1316    sizes.insert(
1317        "L",
1318        Sizage {
1319            hs: 1,
1320            ss: 0,
1321            xs: 0,
1322            fs: Some(76),
1323            ls: 0,
1324        },
1325    ); // X448
1326    sizes.insert(
1327        "M",
1328        Sizage {
1329            hs: 1,
1330            ss: 0,
1331            xs: 0,
1332            fs: Some(4),
1333            ls: 0,
1334        },
1335    ); // SHA3_512
1336    sizes.insert(
1337        "N",
1338        Sizage {
1339            hs: 1,
1340            ss: 0,
1341            xs: 0,
1342            fs: Some(12),
1343            ls: 0,
1344        },
1345    ); // SHA2_512
1346    sizes.insert(
1347        "O",
1348        Sizage {
1349            hs: 1,
1350            ss: 0,
1351            xs: 0,
1352            fs: Some(44),
1353            ls: 0,
1354        },
1355    ); // ECDSA_256k1
1356    sizes.insert(
1357        "P",
1358        Sizage {
1359            hs: 1,
1360            ss: 0,
1361            xs: 0,
1362            fs: Some(124),
1363            ls: 0,
1364        },
1365    ); // ECDSA_256r1
1366    sizes.insert(
1367        "Q",
1368        Sizage {
1369            hs: 1,
1370            ss: 0,
1371            xs: 0,
1372            fs: Some(44),
1373            ls: 0,
1374        },
1375    ); // Ed448N
1376    sizes.insert(
1377        "R",
1378        Sizage {
1379            hs: 1,
1380            ss: 0,
1381            xs: 0,
1382            fs: Some(8),
1383            ls: 0,
1384        },
1385    ); // Ed448
1386    sizes.insert(
1387        "S",
1388        Sizage {
1389            hs: 1,
1390            ss: 0,
1391            xs: 0,
1392            fs: Some(16),
1393            ls: 0,
1394        },
1395    ); // Ed448_Sig
1396    sizes.insert(
1397        "U",
1398        Sizage {
1399            hs: 1,
1400            ss: 0,
1401            xs: 0,
1402            fs: Some(20),
1403            ls: 0,
1404        },
1405    ); // Blake3_512
1406    sizes.insert(
1407        "V",
1408        Sizage {
1409            hs: 1,
1410            ss: 0,
1411            xs: 0,
1412            fs: Some(24),
1413            ls: 0,
1414        },
1415    ); // Blake2b_512
1416    sizes.insert(
1417        "W",
1418        Sizage {
1419            hs: 1,
1420            ss: 0,
1421            xs: 0,
1422            fs: Some(4),
1423            ls: 0,
1424        },
1425    ); // ECDSA_256k1_Sig
1426    sizes.insert(
1427        "X",
1428        Sizage {
1429            hs: 1,
1430            ss: 3,
1431            xs: 0,
1432            fs: Some(4),
1433            ls: 0,
1434        },
1435    ); // ECDSA_256r1_Sig
1436    sizes.insert(
1437        "Y",
1438        Sizage {
1439            hs: 1,
1440            ss: 7,
1441            xs: 0,
1442            fs: Some(4),
1443            ls: 0,
1444        },
1445    ); // ECDSA_256k1_Seed
1446    sizes.insert(
1447        "Z",
1448        Sizage {
1449            hs: 1,
1450            ss: 0,
1451            xs: 0,
1452            fs: Some(8),
1453            ls: 0,
1454        },
1455    ); // ECDSA_256r1_Seed
1456    sizes.insert(
1457        "0A",
1458        Sizage {
1459            hs: 2,
1460            ss: 0,
1461            xs: 0,
1462            fs: Some(24),
1463            ls: 0,
1464        },
1465    );
1466    sizes.insert(
1467        "0B",
1468        Sizage {
1469            hs: 2,
1470            ss: 0,
1471            xs: 0,
1472            fs: Some(88),
1473            ls: 0,
1474        },
1475    );
1476    sizes.insert(
1477        "0C",
1478        Sizage {
1479            hs: 2,
1480            ss: 0,
1481            xs: 0,
1482            fs: Some(88),
1483            ls: 0,
1484        },
1485    );
1486    sizes.insert(
1487        "0D",
1488        Sizage {
1489            hs: 2,
1490            ss: 0,
1491            xs: 0,
1492            fs: Some(88),
1493            ls: 0,
1494        },
1495    );
1496    sizes.insert(
1497        "0E",
1498        Sizage {
1499            hs: 2,
1500            ss: 0,
1501            xs: 0,
1502            fs: Some(88),
1503            ls: 0,
1504        },
1505    );
1506    sizes.insert(
1507        "0F",
1508        Sizage {
1509            hs: 2,
1510            ss: 0,
1511            xs: 0,
1512            fs: Some(88),
1513            ls: 0,
1514        },
1515    );
1516    sizes.insert(
1517        "0G",
1518        Sizage {
1519            hs: 2,
1520            ss: 0,
1521            xs: 0,
1522            fs: Some(88),
1523            ls: 0,
1524        },
1525    );
1526    sizes.insert(
1527        "0H",
1528        Sizage {
1529            hs: 2,
1530            ss: 0,
1531            xs: 0,
1532            fs: Some(8),
1533            ls: 0,
1534        },
1535    );
1536    sizes.insert(
1537        "0I",
1538        Sizage {
1539            hs: 2,
1540            ss: 0,
1541            xs: 0,
1542            fs: Some(88),
1543            ls: 0,
1544        },
1545    );
1546    sizes.insert(
1547        "0J",
1548        Sizage {
1549            hs: 2,
1550            ss: 2,
1551            xs: 1,
1552            fs: Some(4),
1553            ls: 0,
1554        },
1555    );
1556    sizes.insert(
1557        "0K",
1558        Sizage {
1559            hs: 2,
1560            ss: 2,
1561            xs: 0,
1562            fs: Some(4),
1563            ls: 0,
1564        },
1565    );
1566    sizes.insert(
1567        "0L",
1568        Sizage {
1569            hs: 2,
1570            ss: 6,
1571            xs: 1,
1572            fs: Some(8),
1573            ls: 0,
1574        },
1575    );
1576    sizes.insert(
1577        "0M",
1578        Sizage {
1579            hs: 2,
1580            ss: 6,
1581            xs: 0,
1582            fs: Some(8),
1583            ls: 0,
1584        },
1585    );
1586    sizes.insert(
1587        "0N",
1588        Sizage {
1589            hs: 2,
1590            ss: 10,
1591            xs: 1,
1592            fs: Some(12),
1593            ls: 0,
1594        },
1595    );
1596    sizes.insert(
1597        "0O",
1598        Sizage {
1599            hs: 2,
1600            ss: 10,
1601            xs: 0,
1602            fs: Some(12),
1603            ls: 0,
1604        },
1605    );
1606    sizes.insert(
1607        "0P",
1608        Sizage {
1609            hs: 2,
1610            ss: 22,
1611            xs: 0,
1612            fs: Some(32),
1613            ls: 0,
1614        },
1615    );
1616    sizes.insert(
1617        "0Q",
1618        Sizage {
1619            hs: 2,
1620            ss: 22,
1621            xs: 0,
1622            fs: Some(28),
1623            ls: 0,
1624        },
1625    );
1626    sizes.insert(
1627        "0R",
1628        Sizage {
1629            hs: 2,
1630            ss: 22,
1631            xs: 0,
1632            fs: Some(76),
1633            ls: 0,
1634        },
1635    );
1636    sizes.insert(
1637        "0S",
1638        Sizage {
1639            hs: 2,
1640            ss: 22,
1641            xs: 0,
1642            fs: Some(72),
1643            ls: 0,
1644        },
1645    );
1646
1647    sizes.insert(
1648        "1AAA",
1649        Sizage {
1650            hs: 4,
1651            ss: 0,
1652            xs: 0,
1653            fs: Some(48),
1654            ls: 0,
1655        },
1656    );
1657    sizes.insert(
1658        "1AAB",
1659        Sizage {
1660            hs: 4,
1661            ss: 0,
1662            xs: 0,
1663            fs: Some(48),
1664            ls: 0,
1665        },
1666    );
1667    sizes.insert(
1668        "1AAC",
1669        Sizage {
1670            hs: 4,
1671            ss: 0,
1672            xs: 0,
1673            fs: Some(80),
1674            ls: 0,
1675        },
1676    );
1677    sizes.insert(
1678        "1AAD",
1679        Sizage {
1680            hs: 4,
1681            ss: 0,
1682            xs: 0,
1683            fs: Some(80),
1684            ls: 0,
1685        },
1686    );
1687    sizes.insert(
1688        "1AAE",
1689        Sizage {
1690            hs: 4,
1691            ss: 0,
1692            xs: 0,
1693            fs: Some(156),
1694            ls: 0,
1695        },
1696    );
1697    sizes.insert(
1698        "1AAF",
1699        Sizage {
1700            hs: 4,
1701            ss: 4,
1702            xs: 0,
1703            fs: Some(8),
1704            ls: 0,
1705        },
1706    );
1707    sizes.insert(
1708        "1AAG",
1709        Sizage {
1710            hs: 4,
1711            ss: 0,
1712            xs: 0,
1713            fs: Some(36),
1714            ls: 0,
1715        },
1716    );
1717    sizes.insert(
1718        "1AAH",
1719        Sizage {
1720            hs: 4,
1721            ss: 0,
1722            xs: 0,
1723            fs: Some(100),
1724            ls: 0,
1725        },
1726    );
1727    sizes.insert(
1728        "1AAI",
1729        Sizage {
1730            hs: 4,
1731            ss: 0,
1732            xs: 0,
1733            fs: Some(48),
1734            ls: 0,
1735        },
1736    );
1737    sizes.insert(
1738        "1AAJ",
1739        Sizage {
1740            hs: 4,
1741            ss: 0,
1742            xs: 0,
1743            fs: Some(48),
1744            ls: 0,
1745        },
1746    );
1747    sizes.insert(
1748        "1AAK",
1749        Sizage {
1750            hs: 4,
1751            ss: 0,
1752            xs: 0,
1753            fs: Some(4),
1754            ls: 0,
1755        },
1756    );
1757    sizes.insert(
1758        "1AAL",
1759        Sizage {
1760            hs: 4,
1761            ss: 0,
1762            xs: 0,
1763            fs: Some(4),
1764            ls: 0,
1765        },
1766    );
1767    sizes.insert(
1768        "1AAM",
1769        Sizage {
1770            hs: 4,
1771            ss: 0,
1772            xs: 0,
1773            fs: Some(4),
1774            ls: 0,
1775        },
1776    );
1777    sizes.insert(
1778        "1AAN",
1779        Sizage {
1780            hs: 4,
1781            ss: 8,
1782            xs: 0,
1783            fs: Some(12),
1784            ls: 0,
1785        },
1786    );
1787
1788    sizes.insert(
1789        "1__-",
1790        Sizage {
1791            hs: 4,
1792            ss: 2,
1793            xs: 0,
1794            fs: Some(12),
1795            ls: 0,
1796        },
1797    );
1798    sizes.insert(
1799        "1___",
1800        Sizage {
1801            hs: 4,
1802            ss: 0,
1803            xs: 0,
1804            fs: Some(8),
1805            ls: 0,
1806        },
1807    );
1808    sizes.insert(
1809        "2__-",
1810        Sizage {
1811            hs: 4,
1812            ss: 2,
1813            xs: 1,
1814            fs: Some(12),
1815            ls: 1,
1816        },
1817    );
1818    sizes.insert(
1819        "2___",
1820        Sizage {
1821            hs: 4,
1822            ss: 0,
1823            xs: 0,
1824            fs: Some(8),
1825            ls: 1,
1826        },
1827    );
1828    sizes.insert(
1829        "3__-",
1830        Sizage {
1831            hs: 4,
1832            ss: 2,
1833            xs: 0,
1834            fs: Some(12),
1835            ls: 2,
1836        },
1837    );
1838    sizes.insert(
1839        "3___",
1840        Sizage {
1841            hs: 4,
1842            ss: 0,
1843            xs: 0,
1844            fs: Some(8),
1845            ls: 2,
1846        },
1847    );
1848
1849    sizes.insert(
1850        "4A",
1851        Sizage {
1852            hs: 2,
1853            ss: 2,
1854            xs: 0,
1855            fs: None,
1856            ls: 0,
1857        },
1858    );
1859    sizes.insert(
1860        "5A",
1861        Sizage {
1862            hs: 2,
1863            ss: 2,
1864            xs: 0,
1865            fs: None,
1866            ls: 1,
1867        },
1868    );
1869    sizes.insert(
1870        "6A",
1871        Sizage {
1872            hs: 2,
1873            ss: 2,
1874            xs: 0,
1875            fs: None,
1876            ls: 2,
1877        },
1878    );
1879    sizes.insert(
1880        "7AAA",
1881        Sizage {
1882            hs: 4,
1883            ss: 4,
1884            xs: 0,
1885            fs: None,
1886            ls: 0,
1887        },
1888    );
1889    sizes.insert(
1890        "8AAA",
1891        Sizage {
1892            hs: 4,
1893            ss: 4,
1894            xs: 0,
1895            fs: None,
1896            ls: 1,
1897        },
1898    );
1899    sizes.insert(
1900        "9AAA",
1901        Sizage {
1902            hs: 4,
1903            ss: 4,
1904            xs: 0,
1905            fs: None,
1906            ls: 2,
1907        },
1908    );
1909
1910    sizes.insert(
1911        "4B",
1912        Sizage {
1913            hs: 2,
1914            ss: 2,
1915            xs: 0,
1916            fs: None,
1917            ls: 0,
1918        },
1919    );
1920    sizes.insert(
1921        "5B",
1922        Sizage {
1923            hs: 2,
1924            ss: 2,
1925            xs: 0,
1926            fs: None,
1927            ls: 1,
1928        },
1929    );
1930    sizes.insert(
1931        "6B",
1932        Sizage {
1933            hs: 2,
1934            ss: 2,
1935            xs: 0,
1936            fs: None,
1937            ls: 2,
1938        },
1939    );
1940    sizes.insert(
1941        "7AAB",
1942        Sizage {
1943            hs: 4,
1944            ss: 4,
1945            xs: 0,
1946            fs: None,
1947            ls: 0,
1948        },
1949    );
1950    sizes.insert(
1951        "8AAB",
1952        Sizage {
1953            hs: 4,
1954            ss: 4,
1955            xs: 0,
1956            fs: None,
1957            ls: 1,
1958        },
1959    );
1960    sizes.insert(
1961        "9AAB",
1962        Sizage {
1963            hs: 4,
1964            ss: 4,
1965            xs: 0,
1966            fs: None,
1967            ls: 2,
1968        },
1969    );
1970
1971    sizes.insert(
1972        "4C",
1973        Sizage {
1974            hs: 2,
1975            ss: 2,
1976            xs: 0,
1977            fs: None,
1978            ls: 0,
1979        },
1980    );
1981    sizes.insert(
1982        "5C",
1983        Sizage {
1984            hs: 2,
1985            ss: 2,
1986            xs: 0,
1987            fs: None,
1988            ls: 1,
1989        },
1990    );
1991    sizes.insert(
1992        "6C",
1993        Sizage {
1994            hs: 2,
1995            ss: 2,
1996            xs: 0,
1997            fs: None,
1998            ls: 2,
1999        },
2000    );
2001    sizes.insert(
2002        "7AAC",
2003        Sizage {
2004            hs: 4,
2005            ss: 4,
2006            xs: 0,
2007            fs: None,
2008            ls: 0,
2009        },
2010    );
2011    sizes.insert(
2012        "8AAC",
2013        Sizage {
2014            hs: 4,
2015            ss: 4,
2016            xs: 0,
2017            fs: None,
2018            ls: 1,
2019        },
2020    );
2021    sizes.insert(
2022        "9AAC",
2023        Sizage {
2024            hs: 4,
2025            ss: 4,
2026            xs: 0,
2027            fs: None,
2028            ls: 2,
2029        },
2030    );
2031
2032    sizes.insert(
2033        "4D",
2034        Sizage {
2035            hs: 2,
2036            ss: 2,
2037            xs: 0,
2038            fs: None,
2039            ls: 0,
2040        },
2041    );
2042    sizes.insert(
2043        "5D",
2044        Sizage {
2045            hs: 2,
2046            ss: 2,
2047            xs: 0,
2048            fs: None,
2049            ls: 1,
2050        },
2051    );
2052    sizes.insert(
2053        "6D",
2054        Sizage {
2055            hs: 2,
2056            ss: 2,
2057            xs: 0,
2058            fs: None,
2059            ls: 2,
2060        },
2061    );
2062    sizes.insert(
2063        "7AAD",
2064        Sizage {
2065            hs: 4,
2066            ss: 4,
2067            xs: 0,
2068            fs: None,
2069            ls: 0,
2070        },
2071    );
2072    sizes.insert(
2073        "8AAD",
2074        Sizage {
2075            hs: 4,
2076            ss: 4,
2077            xs: 0,
2078            fs: None,
2079            ls: 1,
2080        },
2081    );
2082    sizes.insert(
2083        "9AAD",
2084        Sizage {
2085            hs: 4,
2086            ss: 4,
2087            xs: 0,
2088            fs: None,
2089            ls: 2,
2090        },
2091    );
2092
2093    sizes.insert(
2094        "4E",
2095        Sizage {
2096            hs: 2,
2097            ss: 2,
2098            xs: 0,
2099            fs: None,
2100            ls: 0,
2101        },
2102    );
2103    sizes.insert(
2104        "5E",
2105        Sizage {
2106            hs: 2,
2107            ss: 2,
2108            xs: 0,
2109            fs: None,
2110            ls: 1,
2111        },
2112    );
2113    sizes.insert(
2114        "6E",
2115        Sizage {
2116            hs: 2,
2117            ss: 2,
2118            xs: 0,
2119            fs: None,
2120            ls: 2,
2121        },
2122    );
2123    sizes.insert(
2124        "7AAE",
2125        Sizage {
2126            hs: 4,
2127            ss: 4,
2128            xs: 0,
2129            fs: None,
2130            ls: 0,
2131        },
2132    );
2133    sizes.insert(
2134        "8AAE",
2135        Sizage {
2136            hs: 4,
2137            ss: 4,
2138            xs: 0,
2139            fs: None,
2140            ls: 1,
2141        },
2142    );
2143    sizes.insert(
2144        "9AAE",
2145        Sizage {
2146            hs: 4,
2147            ss: 4,
2148            xs: 0,
2149            fs: None,
2150            ls: 2,
2151        },
2152    );
2153
2154    sizes
2155}
2156
2157/// Map of hard characters to their respective values
2158///
2159/// Includes:
2160/// - Uppercase letters (A-Z): value 1
2161/// - Lowercase letters (a-z): value 1
2162/// - Digits with varying values:
2163///   - '0','4','5','6': value 2
2164///   - '1','2','3','7','8','9': value 4
2165pub fn hards() -> HashMap<u8, i32> {
2166    let mut map: HashMap<u8, i32> = (b'A'..=b'Z').map(|c| (c, 1)).collect();
2167
2168    // Add lowercase letters with value 1
2169    map.extend((b'a'..=b'z').map(|c| (c, 1)));
2170
2171    // Add digits with specific values
2172    map.extend([
2173        (b'0', 2),
2174        (b'1', 4),
2175        (b'2', 4),
2176        (b'3', 4),
2177        (b'4', 2),
2178        (b'5', 2),
2179        (b'6', 2),
2180        (b'7', 4),
2181        (b'8', 4),
2182        (b'9', 4),
2183    ]);
2184
2185    map
2186}
2187
2188/// Converts a base64 character to its binary quadlet (2-bit) representation
2189fn code_b64_to_b2(c: u8) -> u8 {
2190    match c {
2191        b'A'..=b'Z' | b'a'..=b'z' | b'0'..=b'9' | b'+' | b'/' => {
2192            let val = match c {
2193                b'A'..=b'Z' => c - b'A',
2194                b'a'..=b'z' => c - b'a' + 26,
2195                b'0'..=b'9' => c - b'0' + 52,
2196                b'+' => 62,
2197                b'/' => 63,
2198                _ => unreachable!(),
2199            };
2200            val
2201        }
2202        _ => b'0',
2203    }
2204}
2205
2206/// Map of binary quadlet characters to their hardness values
2207/// This converts the base64 characters in the Hards map to their binary
2208/// representation and maps them to the same hardness values
2209pub fn get_bards() -> HashMap<u8, i32> {
2210    let hards = hards();
2211    let mut bards: HashMap<u8, i32> = hards
2212        .iter()
2213        .map(|(&c, &hs)| (code_b64_to_b2(c), hs))
2214        .collect();
2215
2216    // Add specific mapping for SALT_128 code which starts with '0'
2217    // The binary sextet representation of '0' in qb2 format is 0xd0 (208)
2218    bards.insert(0xd0, 2); // '0' has a hard size of 2
2219
2220    bards
2221}
2222
2223/// Matter is a trait for fully qualified cryptographic material.
2224/// Implementations provide various specialized crypto material types.
2225pub trait Matter: Any {
2226    /// Returns the hard part of the derivation code
2227    fn code(&self) -> &str;
2228
2229    /// Returns raw crypto material (without derivation code)
2230    fn raw(&self) -> &[u8];
2231
2232    /// Returns base64 fully qualified representation
2233    fn qb64(&self) -> String;
2234
2235    /// Returns base64 fully qualified representation
2236    fn qb64b(&self) -> Vec<u8>;
2237
2238    /// Returns binary fully qualified representation
2239    fn qb2(&self) -> Vec<u8>;
2240
2241    /// Soft portion of qb64 value
2242    fn soft(&self) -> &str;
2243
2244    /// Return the full size of this Matter instance
2245    fn full_size(&self) -> usize;
2246
2247    /// Calculate the populated size
2248    fn size(&self) -> usize;
2249
2250    /// Returns whether the derivation code is transferable
2251    fn is_transferable(&self) -> bool;
2252
2253    /// Returns whether the code represents a digest
2254    fn is_digestive(&self) -> bool;
2255
2256    /// Returns whether the code represents a prefix
2257    fn is_prefixive(&self) -> bool;
2258
2259    /// Returns whether the code represents a prefix
2260    fn is_special(&self) -> bool;
2261
2262    fn as_any(&self) -> &dyn Any;
2263}
2264
2265/// Trait that must be implemented by types that can be parsed
2266pub trait Parsable: Sized {
2267    fn from_qb64b(data: &mut Vec<u8>, strip: Option<bool>) -> Result<Self, MatterError>;
2268    fn from_qb2(data: &mut Vec<u8>, strip: Option<bool>) -> Result<Self, MatterError>;
2269}
2270
2271/// Common implementation for all Matter types.
2272#[derive(Debug, Clone)]
2273pub struct BaseMatter {
2274    code: String,
2275    soft: String,
2276    raw: Vec<u8>,
2277}
2278
2279impl TryFrom<Vec<u8>> for BaseMatter {
2280    type Error = MatterError;
2281
2282    fn try_from(value: Vec<u8>) -> Result<Self, Self::Error> {
2283        BaseMatter::from_qb64b(&mut value.clone(), None)
2284    }
2285}
2286
2287impl BaseMatter {
2288    /// Creates a new BaseMatter from raw bytes and a code
2289    pub fn new(
2290        raw: Option<&[u8]>,
2291        code: Option<&str>,
2292        soft: Option<&str>,
2293        rize: Option<usize>,
2294    ) -> Result<Self, MatterError> {
2295        let code = code.ok_or_else(|| {
2296            MatterError::EmptyMaterial(
2297                "Improper initialization need either (raw not None and code) or \
2298             (code and soft) or qb64b or qb64 or qb2."
2299                    .to_string(),
2300            )
2301        })?;
2302
2303        let raw =
2304            raw.ok_or_else(|| MatterError::TypeError(String::from("Raw data must be provided")))?;
2305
2306        let sizes = get_sizes();
2307        // Check if code is supported
2308        if !sizes.contains_key(code) {
2309            return Err(MatterError::InvalidCode(format!(
2310                "Unsupported code={}",
2311                code
2312            )));
2313        }
2314
2315        // Get sizes for this code
2316        let size = sizes[code].clone(); // Assumes valid sizes from unit tests
2317        let (_, ss, xs, fs, _) = (size.hs, size.ss, size.xs, size.fs, size.ls);
2318        let hs;
2319        let rize_val;
2320        let mut soft_val = String::new();
2321        let mut code_val = code.to_string();
2322
2323        if fs.is_none() {
2324            // Variable sized - code[0] should be in SmallVrzDex or LargeVrzDex
2325            // Determine the size of raw data to use
2326            rize_val = match rize {
2327                Some(r) => r,
2328                None => raw.len(),
2329            };
2330
2331            // Calculate actual lead (pad) size
2332            let ls = ((3 - (rize_val % 3)) % 3) as u32;
2333            // Calculate size in triplets
2334            let size = (rize_val + ls as usize) / 3;
2335
2336            // Handle small vs large variable size codes
2337            if small_vrz_dex::TUPLE.contains(&&code[0..1]) {
2338                if size <= (64_usize.pow(2) - 1) {
2339                    // ss = 2
2340                    hs = 2;
2341                    let s = small_vrz_dex::TUPLE[ls as usize];
2342                    code_val = format!("{}{}", s, &code[1..hs as usize]);
2343                    soft_val = int_to_b64(size as u32, 2);
2344                } else if size <= (64_usize.pow(4) - 1) {
2345                    // ss = 4 make big version
2346                    hs = 4;
2347                    let s = large_vrz_dex::TUPLE[ls as usize];
2348                    code_val = format!("{}{}{}", s, "A".repeat(hs as usize - 2), &code[1..2]);
2349                    soft_val = int_to_b64(size as u32, 4);
2350                } else {
2351                    return Err(MatterError::InvalidVarRawSize(format!(
2352                        "Unsupported raw size for code={}",
2353                        code
2354                    )));
2355                }
2356            } else if large_vrz_dex::TUPLE.contains(&&code[0..1]) {
2357                if size <= (64_usize.pow(4) - 1) {
2358                    // ss = 4
2359                    hs = 4;
2360                    let s = large_vrz_dex::TUPLE[ls as usize];
2361                    code_val = format!("{}{}", s, &code[1..hs as usize]);
2362                    soft_val = int_to_b64(size as u32, 4);
2363                } else {
2364                    return Err(MatterError::InvalidVarRawSize(format!(
2365                        "Unsupported raw size for large code={}. {} <= {}",
2366                        code,
2367                        size,
2368                        64_usize.pow(4) - 1
2369                    )));
2370                }
2371            } else {
2372                return Err(MatterError::InvalidVarRawSize(format!(
2373                    "Unsupported variable raw size code={}",
2374                    code
2375                )));
2376            }
2377        } else {
2378            // Fixed size
2379            rize_val = raw_size(&code_val)?;
2380
2381            if ss > 0 {
2382                // Special soft size, so soft must be provided
2383                let soft_str = soft.unwrap_or("");
2384                let trimmed_soft =
2385                    &soft_str[..std::cmp::min(soft_str.len(), ss as usize - xs as usize)];
2386
2387                if trimmed_soft.len() != ss as usize - xs as usize {
2388                    return Err(MatterError::SoftMaterial(format!(
2389                        "Not enough chars in soft={} with ss={} xs={} for code={}",
2390                        soft_str, ss, xs, code
2391                    )));
2392                }
2393
2394                // Check if all characters are Base64
2395                if !trimmed_soft
2396                    .chars()
2397                    .all(|c| c.is_ascii_alphanumeric() || c == '+' || c == '/' || c == '=')
2398                {
2399                    return Err(MatterError::InvalidSoft(format!(
2400                        "Non Base64 chars in soft={}",
2401                        trimmed_soft
2402                    )));
2403                }
2404
2405                soft_val = trimmed_soft.to_string();
2406            }
2407        }
2408
2409        // Ensure raw has exactly the right size
2410        if raw.len() < rize_val {
2411            return Err(MatterError::RawMaterial(format!(
2412                "Not enough raw bytes for code={} expected rize={} got {}",
2413                code,
2414                rize_val,
2415                raw.len()
2416            )));
2417        }
2418
2419        // Clone only the exact size needed from raw
2420        let raw_val = Vec::from(&raw[..rize_val]);
2421
2422        Ok(BaseMatter {
2423            code: code_val,
2424            soft: soft_val,
2425            raw: raw_val,
2426            // Add other fields as needed
2427        })
2428    }
2429
2430    pub fn from_raw(raw: Option<&[u8]>) -> Result<Self, MatterError> {
2431        BaseMatter::new(raw, Some(mtr_dex::ED25519N), None, None)
2432    }
2433
2434    /// Creates a new BaseMatter from a qb64 string
2435    pub fn from_qb64(qb64: &str) -> Result<Self, MatterError> {
2436        if qb64.is_empty() {
2437            return Err(MatterError::ShortageError(
2438                "Empty qb64, invalid".to_string(),
2439            ));
2440        }
2441
2442        let first = &qb64[0..1];
2443
2444        let hards = hards();
2445        let sizes = get_sizes();
2446        // Check if first character is in Hards
2447        if !hards.contains_key(&first.bytes().next().unwrap_or(b'A')) {
2448            return if first == "-" {
2449                Err(MatterError::UnexpectedCountCodeError(
2450                    "Unexpected count code start while extracting Matter.".to_string(),
2451                ))
2452            } else if first == "_" {
2453                Err(MatterError::UnexpectedOpCodeError(
2454                    "Unexpected op code start while extracting Matter.".to_string(),
2455                ))
2456            } else {
2457                Err(MatterError::UnexpectedCodeError(format!(
2458                    "Unsupported code start char={}",
2459                    first
2460                )))
2461            };
2462        }
2463
2464        let hs = *hards.get(&first.bytes().next().unwrap_or(b'A')).unwrap(); // get hard code size
2465
2466        if qb64.len() < hs as usize {
2467            return Err(MatterError::ShortageError(format!(
2468                "Need {} more characters.",
2469                hs - qb64.len() as i32
2470            )));
2471        }
2472
2473        let hard = &qb64[0..hs as usize];
2474
2475        if !sizes.contains_key(hard) {
2476            return Err(MatterError::UnexpectedCodeError(format!(
2477                "Unsupported code ={}",
2478                hard
2479            )));
2480        }
2481
2482        let size = *sizes.get(hard).unwrap();
2483        let cs = hs as u32 + size.ss; // both hs and ss
2484
2485        // Extract soft chars including xtra, empty when ss==0 and xs == 0
2486        let soft = if size.ss > 0 {
2487            &qb64[hs as usize..(hs as u32 + size.ss) as usize]
2488        } else {
2489            ""
2490        };
2491        let xtra = if size.xs > 0 {
2492            &soft[0..size.xs as usize]
2493        } else {
2494            ""
2495        };
2496        let soft_without_xtra = if size.xs > 0 {
2497            &soft[size.xs as usize..]
2498        } else {
2499            soft
2500        };
2501
2502        if size.xs > 0 && xtra != &"A".repeat(size.xs as usize) {
2503            return Err(MatterError::UnexpectedCodeError(format!(
2504                "Invalid prepad xtra ={}",
2505                xtra
2506            )));
2507        }
2508
2509        let fs = if size.fs.is_none() {
2510            // compute fs from soft from ss part which provides size B64
2511            (b64_to_int(soft_without_xtra) * 4) + cs
2512        } else {
2513            size.fs.unwrap()
2514        };
2515
2516        if qb64.len() < fs as usize {
2517            return Err(MatterError::ShortageError(format!(
2518                "Need {} more chars.",
2519                fs - qb64.len() as u32
2520            )));
2521        }
2522
2523        let qb64 = &qb64[0..fs as usize]; // fully qualified primitive code plus material
2524
2525        // Check for non-zeroed pad bits and/or lead bytes
2526        let ps = cs % 4; // net prepad bytes to ensure 24 bit align when encodeB64
2527        let base = "A".repeat(ps as usize) + &qb64[cs as usize..]; // prepad ps 'A's to B64 of (lead + raw)
2528        let paw = decode_b64(&base)?;
2529
2530        // Ensure midpad bytes are zero
2531        let midpad = &paw[0..(ps + size.ls) as usize];
2532        let pi = u32::from_be_bytes([
2533            if midpad.len() > 0 { midpad[0] } else { 0 },
2534            if midpad.len() > 1 { midpad[1] } else { 0 },
2535            if midpad.len() > 2 { midpad[2] } else { 0 },
2536            if midpad.len() > 3 { midpad[3] } else { 0 },
2537        ]);
2538
2539        if pi != 0 {
2540            return Err(MatterError::ConversionError(format!(
2541                "Nonzero midpad bytes=0x{:0width$x}.",
2542                pi,
2543                width = (ps + size.ls) as usize * 2
2544            )));
2545        }
2546
2547        // Remove prepad midpat bytes to invert back to raw
2548        let raw = paw[(ps + size.ls) as usize..].to_vec();
2549
2550        let expected_len = ((qb64.len() - cs as usize) * 3 / 4) - size.ls as usize;
2551        if raw.len() != expected_len {
2552            return Err(MatterError::ConversionError(format!(
2553                "Improperly qualified material = {}",
2554                qb64
2555            )));
2556        }
2557
2558        Ok(Self {
2559            code: hard.to_string(),
2560            soft: soft.to_string(),
2561            raw,
2562        })
2563    }
2564
2565    pub fn bexfil(qb2: &[u8]) -> Result<Self, MatterError> {
2566        if qb2.is_empty() {
2567            return Err(MatterError::Shortage(
2568                "Empty material, Need more bytes.".into(),
2569            ));
2570        }
2571
2572        // Extract first sextet as code selector
2573        let first = nab_sextets(qb2, 1)?;
2574
2575        let bards = get_bards();
2576        let hs = match bards.get(&first[0]) {
2577            Some(hs) => *hs,
2578            None => {
2579                return if first[0] == 0xf8 {
2580                    // b64ToB2('-')
2581                    Err(MatterError::UnexpectedCountCode(
2582                        "Unexpected count code start while extracting Matter.".into(),
2583                    ))
2584                } else if first[0] == 0xfc {
2585                    // b64ToB2('_')
2586                    Err(MatterError::UnexpectedOpCode(
2587                        "Unexpected op code start while extracting Matter.".into(),
2588                    ))
2589                } else {
2590                    Err(MatterError::UnexpectedCode(format!(
2591                        "Unsupported code start sextet={:02x?}.",
2592                        first
2593                    )))
2594                };
2595            }
2596        };
2597
2598        // bhs is min bytes to hold hs sextets
2599        let bhs = ((hs as f64) * 3.0 / 4.0).ceil() as usize;
2600        if qb2.len() < bhs {
2601            return Err(MatterError::Shortage(format!(
2602                "Need {} more bytes.",
2603                bhs - qb2.len()
2604            )));
2605        }
2606
2607        // Extract and convert hard part of code
2608        let hard = code_b2_to_b64(qb2, hs as usize)?;
2609
2610        let sizes = get_sizes();
2611        let size = sizes[hard.as_str()].clone();
2612        let (hs, ss, xs, fs, ls) = (size.hs, size.ss, size.xs, size.fs, size.ls);
2613        let cs = hs + ss; // both hs and ss
2614
2615        // bcs is min bytes to hold cs sextets
2616        let bcs = ((cs as f64) * 3.0 / 4.0).ceil() as usize;
2617        if qb2.len() < bcs {
2618            return Err(MatterError::Shortage(format!(
2619                "Need {} more bytes.",
2620                bcs - qb2.len()
2621            )));
2622        }
2623
2624        // Extract and convert both hard and soft part of code
2625        let both = code_b2_to_b64(qb2, cs as usize)?;
2626
2627        // Extract soft chars including xtra, empty when ss==0 and xs == 0
2628        // Assumes that when ss == 0 then xs must be 0
2629        let mut soft = both[hs as usize..].to_string();
2630        let xtra = if xs > 0 {
2631            soft[..xs as usize].to_string()
2632        } else {
2633            String::new()
2634        };
2635
2636        if xs > 0 {
2637            soft = soft[xs as usize..].to_string();
2638        }
2639
2640        // Check for valid padding in xtra
2641        if xs > 0 && xtra != PAD.to_string().repeat(xs as usize) {
2642            return Err(MatterError::UnexpectedCode(format!(
2643                "Invalid prepad xtra ={}",
2644                xtra
2645            )));
2646        }
2647
2648        // Calculate the full size (fs)
2649        let calculated_fs = if fs.unwrap_or(0) == 0 {
2650            // Compute fs from size chars in ss part of code
2651            if qb2.len() < bcs {
2652                return Err(MatterError::Shortage(format!(
2653                    "Need {} more bytes.",
2654                    bcs - qb2.len()
2655                )));
2656            }
2657
2658            // Compute size as int from soft part given by ss B64 chars
2659            let soft_int = b64_to_int(&soft);
2660            (soft_int * 4) + cs
2661        } else {
2662            fs.unwrap_or(0)
2663        };
2664
2665        // bfs is min bytes to hold fs sextets
2666        let bfs = ((calculated_fs as f64) * 3.0 / 4.0).ceil() as usize;
2667        if qb2.len() < bfs {
2668            return Err(MatterError::Shortage(format!(
2669                "Need {} more bytes.",
2670                bfs - qb2.len()
2671            )));
2672        }
2673
2674        let qb2 = &qb2[..bfs]; // Extract qb2 fully qualified primitive code plus material
2675
2676        // Check for nonzero trailing full code mid pad bits
2677        let ps = cs % 4; // Full code (both) net pad size for 24 bit alignment
2678        let pbs = 2 * ps; // Mid pad bits = 2 per net pad
2679
2680        if pbs > 0 {
2681            // Get pad bits in last byte of full code
2682            let pi = qb2[bcs - 1];
2683            let mask = (1 << pbs) - 1; // Mask with 1's in pad bit locations
2684            if pi & mask != 0 {
2685                // Not zero so raise error
2686                return Err(MatterError::Conversion(format!(
2687                    "Nonzero code mid pad bits=0b{:0width$b}.",
2688                    pi & mask,
2689                    width = pbs as usize
2690                )));
2691            }
2692        }
2693
2694        // Check nonzero leading mid pad lead bytes in lead + raw
2695        if ls > 0 {
2696            let mut lead_bytes = vec![0u8; ls as usize];
2697            lead_bytes.copy_from_slice(&qb2[bcs..bcs + ls as usize]);
2698
2699            let mut is_zero = true;
2700            for byte in &lead_bytes {
2701                if *byte != 0 {
2702                    is_zero = false;
2703                    break;
2704                }
2705            }
2706
2707            if !is_zero {
2708                return Err(MatterError::Conversion(format!(
2709                    "Nonzero lead midpad bytes={:0width$x?}.",
2710                    lead_bytes,
2711                    width = (ls * 2) as usize
2712                )));
2713            }
2714        }
2715
2716        // Strip code and leader bytes from qb2 to get raw
2717        let raw = if (bcs + ls as usize) < qb2.len() {
2718            qb2[bcs + ls as usize..].to_vec()
2719        } else {
2720            Vec::new()
2721        };
2722
2723        if raw.len() != (qb2.len() - bcs - ls as usize) {
2724            return Err(MatterError::Conversion(format!(
2725                "Improperly qualified material = {:?}",
2726                qb2
2727            )));
2728        }
2729
2730        // Update the struct fields
2731        Ok(Self {
2732            code: hard.to_string(),
2733            soft,
2734            raw,
2735        })
2736    }
2737
2738    /// Creates a new BaseMatter instance from soft and code components
2739    ///
2740    /// # Arguments
2741    /// * `soft` - The soft part of the code as a string slice
2742    /// * `code` - The hard part of the code as a string slice
2743    ///
2744    /// # Returns
2745    /// * `Result<Self, MatterError>` - A BaseMatter instance or an error
2746    fn from_soft_and_code(soft: &str, code: &str) -> Result<Self, MatterError> {
2747        // Get the sizes associated with the given code
2748        let sizes = get_sizes();
2749        let size = sizes[code].clone();
2750        let (hs, ss, xs, fs, ls) = (size.hs, size.ss, size.xs, size.fs.unwrap_or(0), size.ls);
2751
2752        // Check if code is a variable sized code
2753        if fs == 0 {
2754            return Err(MatterError::InvalidSoftError(format!(
2755                "Unsupported variable sized code={} with fs={} for special soft={}.",
2756                code, fs, soft
2757            )));
2758        }
2759
2760        // Check if it's not a special soft - validate ss, fs, hs, and ls
2761        if !(ss > 0) || (fs == hs + ss && ls != 0) {
2762            return Err(MatterError::InvalidSoftError(format!(
2763                "Invalid soft size={} or lead={} or code={} fs={} when special soft.",
2764                ss, ls, code, fs
2765            )));
2766        }
2767
2768        // Trim soft to correct length
2769        let trimmed_soft = if soft.len() >= (ss - xs) as usize {
2770            &soft[0..(ss - xs) as usize]
2771        } else {
2772            return Err(MatterError::SoftMaterialError(format!(
2773                "Not enough chars in soft={} with ss={} xs={} for code={}.",
2774                soft, ss, xs, code
2775            )));
2776        };
2777
2778        // Validate that soft contains only Base64 characters
2779        if !is_base64(trimmed_soft) {
2780            return Err(MatterError::InvalidSoftError(format!(
2781                "Non Base64 chars in soft={}.",
2782                trimmed_soft
2783            )));
2784        }
2785
2786        // Return populated BaseMatter struct
2787        Ok(BaseMatter {
2788            code: code.to_string(),
2789            soft: trimmed_soft.to_string(),
2790            raw: Vec::new(), // Empty raw bytes as in Python: self._raw = b''
2791        })
2792    }
2793
2794    fn infil(&self) -> Result<String, MatterError> {
2795        let code = &self.code; // hard part of full code == codex value
2796        let both = format!("{}{}", self.code, self.soft); // code + soft, soft may be empty
2797        let raw = &self.raw; // bytes, raw may be empty
2798        let rs = raw.len(); // raw size
2799
2800        // Get sizes from the Sizes table based on the code
2801        let sizes = get_sizes();
2802        let size = sizes[code.as_str()];
2803        let (hs, ss, xs, fs, ls) = (size.hs, size.ss, size.xs, size.fs, size.ls);
2804        let cs = hs + ss;
2805
2806        // Verify the code size is valid
2807        if cs != both.len() as u32 {
2808            return Err(MatterError::InvalidCodeSize(format!(
2809                "Invalid full code={} for sizes hs={} and ss={}.",
2810                both, hs, ss
2811            )));
2812        }
2813
2814        let full = if fs.unwrap_or(0) == 0 {
2815            // Variable sized
2816            // Ensure that (ls + rs) % 3 == 0 and cs % 4 == 0
2817            if (ls + rs as u32) % 3 != 0 || cs % 4 != 0 {
2818                return Err(MatterError::InvalidCodeSize(format!(
2819                    "Invalid full code both={} with variable raw size={} given cs={}, hs={}, ss={}, fs={}, and ls={}.",
2820                    both, rs, cs, hs, ss, fs.unwrap_or(0), ls
2821                )));
2822            }
2823
2824            // Prepad raw with ls zero bytes and convert
2825            let mut padded_raw = vec![0; ls as usize];
2826            padded_raw.extend_from_slice(raw);
2827            let encoded = encode_b64(&padded_raw);
2828
2829            format!("{}{}", both, encoded)
2830        } else {
2831            // Fixed size
2832            let ps = (3 - ((rs + ls as usize) % 3)) % 3; // net pad size given raw with lead
2833
2834            // Check if pad size matches code size remainder
2835            if ps != (cs % 4) as usize {
2836                return Err(MatterError::InvalidCodeSize(format!(
2837                    "Invalid full code both={} with fixed raw size={} given cs={}, hs={}, ss={}, fs={}, and ls={}.",
2838                    both, rs, cs, hs, ss, fs.unwrap_or(0), ls
2839                )));
2840            }
2841
2842            // Prepad raw with ps+ls zero bytes
2843            let mut padded_raw = vec![0; ps + ls as usize];
2844            padded_raw.extend_from_slice(raw);
2845            let encoded = encode_b64(&padded_raw);
2846
2847            // Skip first ps == cs % 4 of the converted characters
2848            format!("{}{}", both, &encoded[ps..])
2849        };
2850
2851        // Final validation
2852        if (full.len() % 4 != 0) || (fs.unwrap_or(0) > 0 && full.len() != fs.unwrap_or(0) as usize)
2853        {
2854            return Err(MatterError::InvalidCodeSize(format!(
2855                "Invalid full size given code both={} with raw size={}, cs={}, hs={}, ss={}, xs={}, fs={}, and ls={}.",
2856                both, rs, cs, hs, ss, xs, fs.unwrap_or(0), ls
2857            )));
2858        }
2859
2860        Ok(full)
2861    }
2862
2863    /// Create binary domain representation
2864    ///
2865    /// Returns bytes of fully qualified base2 bytes, that is .qb2
2866    /// self.code converted to Base2 + self.raw left shifted with pad bits
2867    /// equivalent of Base64 decode of .qb64 into .qb2
2868    pub fn binfil(&self) -> Result<Vec<u8>, MatterError> {
2869        let code = &self.code; // hard part of full code == codex value
2870        let both = format!("{}{}", &self.code, &self.soft); // code + soft, soft may be empty
2871        let raw = &self.raw; // bytes may be empty
2872
2873        // Get sizes from the Sizes table based on the code
2874        let sizes = get_sizes();
2875        let size = sizes[code.as_str()];
2876        let (hs, ss, fs, ls) = (size.hs, size.ss, size.fs, size.ls);
2877        let cs = hs + ss;
2878        // assumes unit tests on BaseMatter.get_sizes ensure valid size entries
2879
2880        // Number of b2 bytes to hold b64 code
2881        let n = ((cs * 3) as f64 / 4.0).ceil() as usize; // sceil equivalent
2882
2883        // Convert code both to right align b2 int then left shift in pad bits
2884        // then convert to bytes
2885        let b64_int = b64_to_int(&both);
2886        let shift = 2 * (cs % 4);
2887        let b64_shifted = b64_int << shift;
2888
2889        // Create bytes from the shifted integer
2890        let bcode = b64_shifted.to_be_bytes()[b64_shifted.to_be_bytes().len() - n..].to_vec();
2891
2892        // Combine bcode with lead bytes and raw data
2893        let mut full = Vec::new();
2894        full.extend_from_slice(&bcode);
2895        full.extend_from_slice(&vec![0; ls as usize]);
2896        full.extend_from_slice(raw);
2897
2898        let bfs = full.len();
2899
2900        // Compute fs if not provided (variable size)
2901        let calculated_fs = if fs.unwrap_or(0) == 0 {
2902            hs + ss + ((raw.len() as u32 + ls) * 4) / 3
2903        } else {
2904            fs.unwrap()
2905        };
2906
2907        // Validate size
2908        if bfs % 3 != 0 || ((bfs * 4) / 3) != calculated_fs as usize {
2909            return Err(MatterError::InvalidCodeSize(format!(
2910                "Invalid full code={} for raw size={}.",
2911                both,
2912                raw.len()
2913            )));
2914        }
2915
2916        Ok(full)
2917    }
2918}
2919
2920impl Parsable for BaseMatter {
2921    fn from_qb64b(data: &mut Vec<u8>, strip: Option<bool>) -> Result<Self, MatterError> {
2922        let qb64b = data.as_slice();
2923        let qb64 = str::from_utf8(qb64b).ok();
2924        let mtr = BaseMatter::from_qb64(qb64.unwrap_or(""))?;
2925        if strip.unwrap_or(false) {
2926            let fs = mtr.full_size();
2927            data.drain(..fs);
2928        }
2929        Ok(mtr)
2930    }
2931
2932    /// Creates a new BaseMatter from qb2 bytes
2933    fn from_qb2(data: &mut Vec<u8>, strip: Option<bool>) -> Result<Self, MatterError> {
2934        let qb2 = data.as_slice();
2935        let mtr = BaseMatter::bexfil(qb2)?;
2936        if strip.unwrap_or(false) {
2937            let fs = mtr.full_size();
2938            data.drain(..fs);
2939        }
2940        Ok(mtr)
2941    }
2942}
2943
2944// Helper function to decode base64 string to bytes
2945fn decode_b64(data: &str) -> Result<Vec<u8>, MatterError> {
2946    general_purpose::URL_SAFE_NO_PAD
2947        .decode(data)
2948        .map_err(|_| MatterError::InvalidBase64)
2949}
2950
2951fn encode_b64(data: &[u8]) -> String {
2952    general_purpose::URL_SAFE_NO_PAD.encode(data)
2953}
2954
2955// Helper function to convert base64 string to integer
2956pub fn b64_to_int(b64_str: &str) -> u32 {
2957    let mut result = 0u32;
2958    for c in b64_str.chars() {
2959        result = result * 64
2960            + match c {
2961                'A'..='Z' => c as u32 - 'A' as u32,
2962                'a'..='z' => c as u32 - 'a' as u32 + 26,
2963                '0'..='9' => c as u32 - '0' as u32 + 52,
2964                '+' | '-' => 62,
2965                '/' | '_' => 63,
2966                _ => 0,
2967            };
2968    }
2969    result
2970}
2971
2972// Helper function to convert integer to base64 string
2973pub fn int_to_b64(num: u32, length: usize) -> String {
2974    const B64_CHARS: &[u8] = b"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_";
2975
2976    let mut result = String::with_capacity(length);
2977    let mut n = num;
2978
2979    for _ in 0..length {
2980        let idx = (n % 64) as usize;
2981        result.insert(0, B64_CHARS[idx] as char);
2982        n /= 64;
2983    }
2984
2985    result
2986}
2987
2988pub fn raw_size(code: &str) -> Result<usize, MatterError> {
2989    // Implementation would access self.sizes to get the raw size for this code
2990    // For this example, we'll return a placeholder
2991    // In the actual implementation, this would look up the size from the Sizes map
2992    let sizes = get_sizes();
2993    let size = sizes[code].clone();
2994    let cs = size.hs + size.ss;
2995    let fs = size
2996        .fs
2997        .ok_or_else(|| MatterError::InvalidCode(code.to_string()))?;
2998
2999    Ok((((fs - cs) * 3 / 4) - size.ls) as usize)
3000}
3001
3002/// Nab l sextets from front of b
3003///
3004/// # Returns
3005/// Bytes containing first l sextets from front (left) of b as a Vec<u8>.
3006/// Length of bytes returned is minimum sufficient to hold all l sextets.
3007/// Last byte returned is right bit padded with zeros which is compatible
3008/// with mid padded codes on front of primitives.
3009///
3010/// # Parameters
3011/// * `b`: target from which to nab sextets
3012/// * `l`: number of sextets to nab from front of b
3013///
3014/// # Errors
3015/// Returns an error message if there aren't enough bytes in b to nab l sextets.
3016pub fn nab_sextets(b: &[u8], l: usize) -> Result<Vec<u8>, MatterError> {
3017    // Calculate number of bytes needed for l sextets (ceiling of l*3/4)
3018    let n = (l * 3 + 3) / 4; // Equivalent to ceiling of l*3/4
3019
3020    if n > b.len() {
3021        return Err(MatterError::ShortageError(format!(
3022            "Not enough bytes in {:?} to nab {} sextets.",
3023            b, l
3024        )));
3025    }
3026
3027    // Extract the first n bytes and convert to a BigUint
3028    let bytes = &b[..n];
3029    let mut i = BigUint::from_bytes_be(bytes);
3030
3031    // Calculate padding bits based on l % 4
3032    let p = 2 * (l % 4);
3033
3034    if p > 0 {
3035        // Apply bit shifting operations
3036        // i >>= p  (strip off last bits)
3037        i >>= p;
3038
3039        // i <<= p  (pad with empty bits)
3040        i <<= p;
3041    }
3042
3043    // Convert back to bytes
3044    let mut result = i.to_bytes_be();
3045
3046    // Ensure the result is exactly n bytes by padding with zeros if needed
3047    if result.len() < n {
3048        let padding = vec![0; n - result.len()];
3049        let mut padded_result = padding;
3050        padded_result.extend(result);
3051        result = padded_result;
3052    }
3053
3054    Ok(result)
3055}
3056
3057/// Convert l sextets from base2 b to base64
3058///
3059/// # Returns
3060/// A String containing the conversion (encode) of l Base2 sextets from front of b
3061/// to Base64 chars. One char for each of l sextets from front (left) of b.
3062///
3063/// This is useful for encoding as code characters, sextets from the front of
3064/// a Base2 bytes. Must provide l because of ambiguity between l=3
3065/// and l=4. Both require 3 bytes in b. Trailing pad bits are removed so
3066/// returned sextets as characters are right aligned.
3067///
3068/// # Parameters
3069/// * `b`: target from which to nab sextets
3070/// * `l`: number of sextets to convert from front of b
3071///
3072/// # Errors
3073/// Returns an error message if there aren't enough bytes in b to nab l sextets.
3074pub fn code_b2_to_b64(b: &[u8], l: usize) -> Result<String, MatterError> {
3075    // Calculate number of bytes needed for l sextets (ceiling of l*3/4)
3076    let n = (l * 3 + 3) / 4; // Equivalent to ceiling of l*3/4
3077
3078    if n > b.len() {
3079        return Err(MatterError::ShortageError(format!(
3080            "Not enough bytes in {:?} to nab {} sextets.",
3081            b, l
3082        )));
3083    }
3084
3085    // Extract the first n bytes and convert to a BigUint
3086    let bytes = &b[..n];
3087    let i = BigUint::from_bytes_be(bytes);
3088
3089    // Calculate trailing bit size in bits
3090    let tbs = 2 * (l % 4);
3091
3092    // Right shift out trailing bits to make right aligned
3093    let adjusted_i = if tbs > 0 { i >> tbs } else { i };
3094
3095    let result = adjusted_i.to_u64().unwrap_or_else(|| 0);
3096    // Return as Base64
3097    Ok(int_to_b64(result as u32, l))
3098}
3099
3100// Helper function to check if a string contains only Base64 characters
3101fn is_base64(s: &str) -> bool {
3102    s.chars().all(|c| {
3103        (c >= 'A' && c <= 'Z')
3104            || (c >= 'a' && c <= 'z')
3105            || (c >= '0' && c <= '9')
3106            || c == '+'
3107            || c == '/'
3108            || c == '-'
3109            || c == '_'
3110    })
3111}
3112
3113impl Matter for BaseMatter {
3114    fn code(&self) -> &str {
3115        &self.code
3116    }
3117
3118    fn raw(&self) -> &[u8] {
3119        &self.raw
3120    }
3121
3122    fn qb64(&self) -> String {
3123        let result = self.infil();
3124        result.unwrap()
3125    }
3126
3127    fn qb64b(&self) -> Vec<u8> {
3128        let result = self.infil();
3129        result.unwrap().into_bytes()
3130    }
3131
3132    fn qb2(&self) -> Vec<u8> {
3133        let result = self.binfil();
3134        result.unwrap()
3135    }
3136
3137    fn soft(&self) -> &str {
3138        &self.soft
3139    }
3140
3141    /// Returns full size of matter in bytes
3142    ///
3143    /// Fixed size codes returns fs from .Sizes
3144    /// Variable size codes where fs==None computes fs from .size and sizes
3145    ///
3146    /// # Returns
3147    /// * `usize` - Full size in bytes
3148    fn full_size(&self) -> usize {
3149        // Extract sizes from the Sizes map using the code
3150        let sizes = get_sizes();
3151        let size = sizes[self.code.as_str()];
3152        let (hs, ss, fs) = (size.hs, size.ss, size.fs);
3153
3154        // If fs is None, compute the full size
3155        match fs {
3156            Some(fixed_size) => fixed_size as usize,
3157            None => {
3158                // Compute fs from ss characters in code and self.size
3159                (hs + ss) as usize + (self.size() * 4)
3160            }
3161        }
3162    }
3163
3164    fn size(&self) -> usize {
3165        let soft = self.soft();
3166        if soft.len() == 0 {
3167            0
3168        } else {
3169            b64_to_int(self.soft()) as usize
3170        }
3171    }
3172
3173    fn is_transferable(&self) -> bool {
3174        !non_trans_dex::TUPLE.contains(&(self.code.as_str()))
3175    }
3176
3177    fn is_digestive(&self) -> bool {
3178        dig_dex::TUPLE.contains(&(self.code.as_str()))
3179    }
3180
3181    fn is_prefixive(&self) -> bool {
3182        pre_dex::TUPLE.contains(&(self.code.as_str()))
3183    }
3184
3185    fn is_special(&self) -> bool {
3186        let sizes = get_sizes();
3187        let size = sizes[self.code.as_str()];
3188
3189        match size.fs {
3190            Some(_) => size.ss > 0,
3191            None => false,
3192        }
3193    }
3194
3195    fn as_any(&self) -> &dyn Any {
3196        self
3197    }
3198}
3199
3200#[cfg(test)]
3201mod tests {
3202    use super::*;
3203
3204    #[test]
3205    fn test_base_matter_from_qb64() {
3206        // Given input qb64 string
3207        let qb64 = "BGlOiUdp5sMmfotHfCWQKEzWR91C72AH0lT84c0um-Qj";
3208
3209        // Expected raw value (in Rust byte string)
3210        let expected_raw =
3211            b"iN\x89Gi\xe6\xc3&~\x8bG|%\x90(L\xd6G\xddB\xef`\x07\xd2T\xfc\xe1\xcd.\x9b\xe4#";
3212
3213        let prebin: [u8; 33] = [
3214            0x04, 0x69, 0x4E, 0x89, 0x47, 0x69, 0xE6, 0xC3, 0x26, 0x7E, 0x8B, 0x47, 0x7C, 0x25,
3215            0x90, 0x28, 0x4C, 0xD6, 0x47, 0xDD, 0x42, 0xEF, 0x60, 0x07, 0xD2, 0x54, 0xFC, 0xE1,
3216            0xCD, 0x2E, 0x9B, 0xE4, 0x23,
3217        ];
3218
3219        // When converting from qb64
3220        let matter = BaseMatter::from_qb64(qb64).expect("Failed to create BaseMatter from qb64");
3221
3222        assert_eq!(matter.raw(), expected_raw);
3223        assert_eq!(matter.code(), "B");
3224        assert_eq!(matter.qb64(), qb64);
3225        assert_eq!(matter.qb2(), prebin.to_vec());
3226    }
3227
3228    #[test]
3229    fn test_base_matter_from_raw() {
3230        let raw = b"iN\x89Gi\xe6\xc3&~\x8bG|%\x90(L\xd6G\xddB\xef`\x07\xd2T\xfc\xe1\xcd.\x9b\xe4#";
3231        let prebin: [u8; 33] = [
3232            0x04, 0x69, 0x4E, 0x89, 0x47, 0x69, 0xE6, 0xC3, 0x26, 0x7E, 0x8B, 0x47, 0x7C, 0x25,
3233            0x90, 0x28, 0x4C, 0xD6, 0x47, 0xDD, 0x42, 0xEF, 0x60, 0x07, 0xD2, 0x54, 0xFC, 0xE1,
3234            0xCD, 0x2E, 0x9B, 0xE4, 0x23,
3235        ];
3236
3237        let matter = BaseMatter::new(Some(raw), Some("B"), None, None).unwrap();
3238        assert_eq!(matter.raw(), raw);
3239        assert_eq!(matter.code(), "B");
3240        assert_eq!(
3241            matter.qb64(),
3242            "BGlOiUdp5sMmfotHfCWQKEzWR91C72AH0lT84c0um-Qj"
3243        );
3244        assert_eq!(matter.qb2(), prebin.to_vec());
3245
3246        let matter1 = BaseMatter::from_raw(Some(raw)).unwrap();
3247        assert_eq!(matter1.raw(), raw);
3248        assert_eq!(matter1.code(), "B");
3249        assert_eq!(
3250            matter1.qb64(),
3251            "BGlOiUdp5sMmfotHfCWQKEzWR91C72AH0lT84c0um-Qj"
3252        );
3253        assert_eq!(matter1.qb2(), prebin.to_vec());
3254
3255        let matter2 = BaseMatter::from_qb2(&mut prebin.to_vec(), None).unwrap();
3256        assert_eq!(matter2.raw(), raw);
3257        assert_eq!(matter2.code(), "B");
3258        assert_eq!(
3259            matter2.qb64(),
3260            "BGlOiUdp5sMmfotHfCWQKEzWR91C72AH0lT84c0um-Qj"
3261        );
3262    }
3263
3264    #[test]
3265    fn test_matter_codex() {
3266        let sizes = get_sizes();
3267        // Test that MtrDex constants are defined correctly
3268        assert_eq!(mtr_dex::ED25519_SEED, "A");
3269        assert_eq!(mtr_dex::ED25519N, "B");
3270        assert_eq!(mtr_dex::X25519, "C");
3271        assert_eq!(mtr_dex::ED25519, "D");
3272        assert_eq!(mtr_dex::BLAKE3_256, "E");
3273        assert_eq!(mtr_dex::BLAKE2B_256, "F");
3274        assert_eq!(mtr_dex::BLAKE2S_256, "G");
3275        assert_eq!(mtr_dex::SHA3_256, "H");
3276        assert_eq!(mtr_dex::SHA2_256, "I");
3277
3278        // Test that Sizage values are correct for some codes
3279        let size = sizes[mtr_dex::ED25519_SEED];
3280        assert_eq!(size.hs, 1);
3281        assert_eq!(size.ss, 0);
3282        assert_eq!(size.xs, 0);
3283        assert_eq!(size.fs, Some(44));
3284        assert_eq!(size.ls, 0);
3285
3286        let size = sizes[mtr_dex::ED25519N];
3287        assert_eq!(size.hs, 1);
3288        assert_eq!(size.ss, 0);
3289        assert_eq!(size.xs, 0);
3290        assert_eq!(size.fs, Some(44));
3291        assert_eq!(size.ls, 0);
3292
3293        let size = sizes[mtr_dex::BLAKE3_256];
3294        assert_eq!(size.hs, 1);
3295        assert_eq!(size.ss, 0);
3296        assert_eq!(size.xs, 0);
3297        assert_eq!(size.fs, Some(44));
3298        assert_eq!(size.ls, 0);
3299
3300        // Test raw_size function
3301        assert_eq!(raw_size(mtr_dex::ED25519).unwrap(), 32);
3302        assert_eq!(raw_size(mtr_dex::ED25519N).unwrap(), 32);
3303        assert_eq!(raw_size(mtr_dex::BLAKE3_256).unwrap(), 32);
3304    }
3305
3306    #[test]
3307    fn test_matter_basic() {
3308        // Test with empty material
3309        let result = BaseMatter::new(None, None, None, None);
3310        assert!(result.is_err());
3311
3312        // Test with raw bytes but no code
3313        let verkey =
3314            b"iN\x89Gi\xe6\xc3&~\x8bG|%\x90(L\xd6G\xddB\xef`\x07\xd2T\xfc\xe1\xcd.\x9b\xe4#";
3315        let result = BaseMatter::new(Some(verkey), None, None, None);
3316        assert!(result.is_err());
3317
3318        // Test with valid raw and code
3319        let result = BaseMatter::new(Some(verkey), Some(mtr_dex::ED25519N), None, None);
3320        assert!(result.is_ok());
3321        let matter = result.unwrap();
3322        assert_eq!(matter.code(), mtr_dex::ED25519N);
3323        assert_eq!(matter.raw(), verkey);
3324
3325        // Test qb64 generation
3326        let qb64 = matter.qb64();
3327        assert_eq!(qb64, "BGlOiUdp5sMmfotHfCWQKEzWR91C72AH0lT84c0um-Qj");
3328
3329        // Test from qb64
3330        let matter2 = BaseMatter::from_qb64(&qb64).unwrap();
3331        assert_eq!(matter2.code(), mtr_dex::ED25519N);
3332        assert_eq!(matter2.raw(), verkey);
3333        assert_eq!(matter2.qb64(), qb64);
3334
3335        // Test qb2 generation and conversion
3336        let qb2 = matter.qb2();
3337        let matter3 = BaseMatter::from_qb2(&mut qb2.to_vec(), None).unwrap();
3338        assert_eq!(matter3.code(), mtr_dex::ED25519N);
3339        assert_eq!(matter3.raw(), verkey);
3340        assert_eq!(matter3.qb64(), qb64);
3341
3342        // Test transferable property
3343        assert!(!matter.is_transferable());
3344
3345        // Test with transferable code
3346        let result = BaseMatter::new(Some(verkey), Some(mtr_dex::ED25519), None, None);
3347        assert!(result.is_ok());
3348        let matter = result.unwrap();
3349        assert_eq!(matter.code(), mtr_dex::ED25519);
3350        assert!(matter.is_transferable());
3351
3352        // Test digestive property
3353        assert!(!matter.is_digestive());
3354
3355        // Test with digest code
3356        let digest = [0u8; 32];
3357        let result = BaseMatter::new(
3358            Some(digest.as_slice()),
3359            Some(mtr_dex::BLAKE3_256),
3360            None,
3361            None,
3362        );
3363        assert!(result.is_ok());
3364        let matter = result.unwrap();
3365        assert_eq!(matter.code(), mtr_dex::BLAKE3_256);
3366        assert!(matter.is_digestive());
3367
3368        // Test prefixive property
3369        assert!(matter.is_prefixive());
3370    }
3371
3372    #[test]
3373    fn test_matter_from_qb64() {
3374        let prefix = "BGlOiUdp5sMmfotHfCWQKEzWR91C72AH0lT84c0um-Qj";
3375        let matter = BaseMatter::from_qb64(prefix).unwrap();
3376        assert_eq!(matter.code(), mtr_dex::ED25519N);
3377        assert_eq!(matter.qb64(), prefix);
3378
3379        // Test with full identifier
3380        let both = format!("{}:mystuff/mypath/toresource?query=what#fragment", prefix);
3381        let matter = BaseMatter::from_qb64(&both).unwrap();
3382        assert_eq!(matter.code(), mtr_dex::ED25519N);
3383        assert_eq!(matter.qb64(), prefix);
3384        assert!(!matter.is_transferable());
3385        assert!(!matter.is_digestive());
3386        assert!(matter.is_prefixive());
3387    }
3388
3389    #[test]
3390    fn test_matter_from_qb64b() {
3391        let prefix = "BGlOiUdp5sMmfotHfCWQKEzWR91C72AH0lT84c0um-Qj";
3392        let mut prefixb = prefix.as_bytes().to_vec();
3393        let matter = BaseMatter::from_qb64b(&mut prefixb, None).unwrap();
3394        assert_eq!(matter.code(), mtr_dex::ED25519N);
3395        assert_eq!(matter.qb64(), prefix);
3396
3397        // Test with full identifier
3398        let both = format!("{}:mystuff/mypath/toresource?query=what#fragment", prefix);
3399        let mut bothb = both.as_bytes().to_vec();
3400        let matter = BaseMatter::from_qb64b(&mut bothb, None).unwrap();
3401        assert_eq!(matter.code(), mtr_dex::ED25519N);
3402        assert_eq!(matter.qb64(), prefix);
3403        assert!(!matter.is_transferable());
3404        assert!(!matter.is_digestive());
3405        assert!(matter.is_prefixive());
3406    }
3407
3408    #[test]
3409    fn test_matter_from_qb2() {
3410        let prefix = "BGlOiUdp5sMmfotHfCWQKEzWR91C72AH0lT84c0um-Qj";
3411        let matter = BaseMatter::from_qb64(prefix).unwrap();
3412        let mut qb2 = matter.qb2();
3413
3414        let matter2 = BaseMatter::from_qb2(&mut qb2, None).unwrap();
3415        assert_eq!(matter2.code(), mtr_dex::ED25519N);
3416        assert_eq!(matter2.qb64(), prefix);
3417        assert!(!matter2.is_transferable());
3418        assert!(!matter2.is_digestive());
3419        assert!(matter2.is_prefixive());
3420    }
3421
3422    #[test]
3423    fn test_matter_with_fixed_sizes() {
3424        // Test TBD0 code with fixed size and lead size 0
3425        let code = mtr_dex::TBD0;
3426        let raw = b"abc";
3427        let qb64 = "1___YWJj";
3428
3429        let matter = BaseMatter::new(Some(raw), Some(code), None, None).unwrap();
3430        assert_eq!(matter.code(), code);
3431        assert_eq!(matter.raw(), raw);
3432        assert_eq!(matter.qb64(), qb64);
3433        assert!(matter.is_transferable());
3434        assert!(!matter.is_digestive());
3435        assert!(!matter.is_prefixive());
3436
3437        let matter2 = BaseMatter::from_qb64(qb64).unwrap();
3438        assert_eq!(matter2.code(), code);
3439        assert_eq!(matter2.raw(), raw);
3440
3441        // Test TBD1 code with fixed size and lead size 1
3442        let code = mtr_dex::TBD1;
3443        let raw = b"ab";
3444        let qb64 = "2___AGFi";
3445
3446        let matter = BaseMatter::new(Some(raw), Some(code), None, None).unwrap();
3447        assert_eq!(matter.code(), code);
3448        assert_eq!(matter.raw(), raw);
3449        assert_eq!(matter.qb64(), qb64);
3450        assert!(matter.is_transferable());
3451        assert!(!matter.is_digestive());
3452        assert!(!matter.is_prefixive());
3453
3454        let matter2 = BaseMatter::from_qb64(qb64).unwrap();
3455        assert_eq!(matter2.code(), code);
3456        assert_eq!(matter2.raw(), raw);
3457
3458        // Test TBD2 code with fixed size and lead size 2
3459        let code = mtr_dex::TBD2;
3460        let raw = b"z";
3461        let qb64 = "3___AAB6";
3462
3463        let matter = BaseMatter::new(Some(raw), Some(code), None, None).unwrap();
3464        assert_eq!(matter.code(), code);
3465        assert_eq!(matter.raw(), raw);
3466        assert_eq!(matter.qb64(), qb64);
3467        assert!(matter.is_transferable());
3468        assert!(!matter.is_digestive());
3469        assert!(!matter.is_prefixive());
3470
3471        let matter2 = BaseMatter::from_qb64(qb64).unwrap();
3472        assert_eq!(matter2.code(), code);
3473        assert_eq!(matter2.raw(), raw);
3474    }
3475
3476    #[test]
3477    fn test_matter_with_variable_sizes() {
3478        // Test Bytes_L0 code with variable size and lead size 0
3479        let code = mtr_dex::BYTES_L0;
3480        let raw = b"abcdef";
3481        let qb64 = "4BACYWJjZGVm";
3482
3483        let matter = BaseMatter::new(Some(raw), Some(code), None, None).unwrap();
3484        assert_eq!(matter.code(), code);
3485        assert_eq!(matter.raw(), raw);
3486        assert_eq!(matter.qb64(), qb64);
3487        assert!(matter.is_transferable());
3488        assert!(!matter.is_digestive());
3489        assert!(!matter.is_prefixive());
3490
3491        let matter2 = BaseMatter::from_qb64(qb64).unwrap();
3492        assert_eq!(matter2.code(), code);
3493        assert_eq!(matter2.raw(), raw);
3494
3495        // Test Bytes_L1 code with variable size and lead size 1
3496        let code = mtr_dex::BYTES_L1;
3497        let raw = b"abcde";
3498        let qb64 = "5BACAGFiY2Rl";
3499
3500        let matter = BaseMatter::new(Some(raw), Some(code), None, None).unwrap();
3501        assert_eq!(matter.code(), code);
3502        assert_eq!(matter.raw(), raw);
3503        assert_eq!(matter.qb64(), qb64);
3504        assert!(matter.is_transferable());
3505        assert!(!matter.is_digestive());
3506        assert!(!matter.is_prefixive());
3507
3508        let matter2 = BaseMatter::from_qb64(qb64).unwrap();
3509        assert_eq!(matter2.code(), code);
3510        assert_eq!(matter2.raw(), raw);
3511
3512        // Test Bytes_L2 code with variable size and lead size 2
3513        let code = mtr_dex::BYTES_L2;
3514        let raw = b"abcd";
3515        let qb64 = "6BACAABhYmNk";
3516
3517        let matter = BaseMatter::new(Some(raw), Some(code), None, None).unwrap();
3518        assert_eq!(matter.code(), code);
3519        assert_eq!(matter.raw(), raw);
3520        assert_eq!(matter.qb64(), qb64);
3521        assert!(matter.is_transferable());
3522        assert!(!matter.is_digestive());
3523        assert!(!matter.is_prefixive());
3524
3525        let matter2 = BaseMatter::from_qb64(qb64).unwrap();
3526        assert_eq!(matter2.code(), code);
3527        assert_eq!(matter2.raw(), raw);
3528    }
3529
3530    #[test]
3531    fn test_matter_with_special_codes() {
3532        // Test Tag3 code with special soft value
3533        let code = mtr_dex::TAG3;
3534        let soft = "icp";
3535        let qb64 = "Xicp";
3536        let raw = b"";
3537
3538        let matter = BaseMatter::from_soft_and_code(soft, code).unwrap();
3539        assert_eq!(matter.code(), code);
3540        assert_eq!(matter.soft.as_str(), soft);
3541        assert_eq!(matter.raw(), raw);
3542        assert_eq!(matter.qb64(), qb64);
3543        assert!(matter.is_special());
3544
3545        let matter2 = BaseMatter::from_qb64(qb64).unwrap();
3546        assert_eq!(matter2.code(), code);
3547        assert_eq!(matter2.soft.as_str(), soft);
3548        assert_eq!(matter2.raw(), raw);
3549
3550        // Test TBD0S code with special soft value and non-empty raw
3551        // let code = mtr_dex::TBD0S;
3552        // let soft = "TG";
3553        // let raw = b"uvwx";
3554        // let qb64 = "1__-TGB1dnd4";
3555        //
3556        // let matter = BaseMatter::from_soft_and_code(soft, code).unwrap();
3557        // assert_eq!(matter.code(), code);
3558        // assert_eq!(matter.soft, soft);
3559        // assert_eq!(matter.raw(), b"");
3560        // assert_eq!(matter.qb64(), qb64);
3561        // assert!(matter.is_special());
3562        //
3563        // let matter2 = BaseMatter::from_qb64(qb64).unwrap();
3564        // assert_eq!(matter2.code(), code);
3565        // assert_eq!(matter2.soft, soft);
3566        // assert_eq!(matter2.raw(), raw);
3567    }
3568
3569    #[test]
3570    fn test_versionage_from_string() {
3571        // Valid version string
3572        let version_str = "KERI10JSON000000_".to_string();
3573        let versionage = Versionage::from(version_str);
3574        assert_eq!(versionage.major, 1);
3575        assert_eq!(versionage.minor, 0);
3576
3577        // Version with different numbers
3578        let version_str = "KERI25CBOR000123_".to_string();
3579        let versionage = Versionage::from(version_str);
3580        assert_eq!(versionage.major, 2);
3581        assert_eq!(versionage.minor, 5);
3582
3583        // Reference implementation
3584        let version_str = "KERI10JSON000000_";
3585        let versionage = Versionage::from(version_str);
3586        assert_eq!(versionage.major, 1);
3587        assert_eq!(versionage.minor, 0);
3588    }
3589
3590    #[test]
3591    fn test_parse_version_string() {
3592        // Valid version string
3593        let result = Versionage::parse_version_string("KERI10JSON000000_");
3594        assert!(result.is_ok());
3595        let versionage = result.unwrap();
3596        assert_eq!(versionage.major, 1);
3597        assert_eq!(versionage.minor, 0);
3598
3599        // Invalid prefix
3600        let result = Versionage::parse_version_string("XERI10JSON000000_");
3601        assert!(result.is_err());
3602
3603        // Too short
3604        let result = Versionage::parse_version_string("KERI");
3605        assert!(result.is_err());
3606
3607        // Invalid hex digits
3608        let result = Versionage::parse_version_string("KERIGZJSON000000_");
3609        assert!(result.is_err());
3610    }
3611}