Skip to main content

libkeri/keri/
mod.rs

1use crate::cesr::b64_to_int;
2use crate::cesr::{int_to_b64, Versionage};
3use crate::errors::MatterError;
4use crate::keri::db::errors::DBError;
5use crate::keri::db::koming::KomerError;
6use crate::keri::db::subing::SuberError;
7use once_cell::sync::Lazy;
8use regex::Regex;
9use std::fmt;
10use thiserror::Error;
11
12pub mod app;
13pub mod core;
14pub mod db;
15mod help;
16
17/// Format string for version
18pub const VERFMT: &str = "{}{:x}{:x}{}{:0{}x}_";
19
20/// Number of hex characters in raw serialization size in version string
21pub const VERRAWSIZE: usize = 6;
22
23/// Number of characters in full version string for version 1
24pub const VER1FULLSPAN: usize = 17;
25
26/// Terminator for version 1 string
27pub const VER1TERM: &[u8] = b"_";
28
29/// Regular expression pattern for version 1 format
30pub const VEREX1: &[u8] = b"(?P<proto1>[A-Z]{4})(?P<major1>[0-9a-f])(?P<minor1>[0-9a-f])(?P<kind1>[A-Z]{4})(?P<size1>[0-9a-f]{6})_";
31
32/// Number of characters in full version string for version 2
33pub const VER2FULLSPAN: usize = 16;
34
35/// Terminator for version 2 string
36pub const VER2TERM: &[u8] = b".";
37
38/// Regular expression pattern for version 2 format
39pub const VEREX2: &[u8] = b"(?P<proto2>[A-Z]{4})(?P<major2>[0-9A-Za-z_-])(?P<minor2>[0-9A-Za-z_-]{2})(?P<kind2>[A-Z]{4})(?P<size2>[0-9A-Za-z_-]{4})\\.";
40
41/// Combined regular expression pattern for both version formats
42pub const VEREX: &[u8] = b"(?P<proto2>[A-Z]{4})(?P<major2>[0-9A-Za-z_-])(?P<minor2>[0-9A-Za-z_-]{2})(?P<kind2>[A-Z]{4})(?P<size2>[0-9A-Za-z_-]{4})\\.|(?P<proto1>[A-Z]{4})(?P<major1>[0-9a-f])(?P<minor1>[0-9a-f])(?P<kind1>[A-Z]{4})(?P<size1>[0-9a-f]{6})_";
43
44/// Maximum number of characters in full version string
45pub const MAXVERFULLSPAN: usize = VER1FULLSPAN;
46
47/// Compiled regular expression for version detection
48pub static REVER: Lazy<Regex> = Lazy::new(|| {
49    Regex::new(std::str::from_utf8(VEREX1).expect("Invalid regex pattern"))
50        .expect("Failed to compile regex pattern")
51});
52
53/// Maximum version string offset
54pub const MAXVSOFFSET: usize = 12;
55
56/// Minimum buffer size to "smell" the version format
57pub const SMELLSIZE: usize = MAXVSOFFSET + MAXVERFULLSPAN;
58
59/// Errors related to protocol validation
60#[derive(Error, Debug)]
61pub enum ProtocolError {
62    #[error("Invalid protocol={0}.")]
63    Invalid(String),
64}
65
66/// Errors related to version validation
67#[derive(Error, Debug)]
68pub enum KERIError {
69    #[error("Value error={0}.")]
70    ValueError(String),
71
72    #[error("Incompatible vrsn={0:?} with version string.")]
73    Incompatible(Versionage),
74
75    #[error("Bad rematch.")]
76    BadRematch(),
77
78    #[error("Invalid version string = '{0}'.")]
79    VersionError(String),
80
81    #[error("Short version string = '{0}'.")]
82    Shortage(String),
83
84    #[error("Kind string error = '{0}'.")]
85    KindError(String),
86
87    #[error("Protocol error = '{0}'.")]
88    ProtocolError(String),
89
90    #[error("Field error: {0}")]
91    FieldError(String),
92
93    #[error("Deserialization error: {0}")]
94    DeserializeError(String),
95
96    #[error("Invalid version: {0}")]
97    SerderVersionError(String),
98
99    #[error("Invalid version: {0}")]
100    ValidationError(String),
101
102    #[error("Error deserializing JSON: {0}")]
103    JsonError(String),
104
105    #[error("Error deserializing MGPK: {0}")]
106    MgpkError(String),
107
108    #[error("Error deserializing CBOR: {0}")]
109    CborError(String),
110
111    #[error("Invalid deserialization kind: {0}")]
112    InvalidKind(String),
113
114    #[error("Missing required field '{0}' for ilk '{1}'")]
115    MissingRequiredField(String, String),
116
117    #[error("Unknown ilk: {0}")]
118    UnknownIlk(String),
119
120    #[error("Wrapped matter error: {0}")]
121    MatterError(String),
122
123    #[error("IO Error")]
124    Io(#[from] std::io::Error),
125
126    #[error("DBError")]
127    DBError(#[from] DBError),
128
129    #[error("Parsing Error: {0}")]
130    Parsing(String),
131
132    #[error("Database Error: {0}")]
133    DatabaseError(String),
134
135    #[error("Manager Error: {0}")]
136    ManagerError(String),
137
138    #[error("Authorization Error: {0}")]
139    AuthError(String),
140
141    #[error("Decryption Error: {0}")]
142    DecryptError(String),
143
144    #[error("Unsupported Message Version")]
145    UnsupportedMessage,
146
147    #[error("Invalid CESR Data")]
148    InvalidCesrData,
149
150    #[error("Database suber error: {0}")]
151    SuberError(#[from] SuberError),
152
153    #[error("Database komer error: {0}")]
154    KomerError(#[from] KomerError),
155
156    #[error("Serialization error: {0}")]
157    SerializationError(String),
158
159    #[error("Deserialization error: {0}")]
160    DeserializationError(String),
161
162    #[error("Out of order error: {0}")]
163    OutOfOrderError(String),
164
165    #[error("Likely duplicitious event error: {0}")]
166    LikelyDuplicitousError(String),
167
168    #[error("Unverified witness receipt event error: {0}")]
169    UnverifiedWitnessReceiptError(String),
170
171    #[error("Unverified receipt event error: {0}")]
172    UnverifiedReceiptError(String),
173
174    #[error("Query not found error: {0}")]
175    QueryNotFoundError(String),
176
177    #[error("Error configuring or initing KERI component (Controller etc)")]
178    ConfigurationError(String),
179
180    #[error("Error Missing entry or entry not found in database")]
181    MissingEntryError(String),
182
183    #[error("Missing signature on KERI event")]
184    MissingSignatureError(String),
185
186    #[error("Missing signature on KERI event")]
187    MissingWitnessError(String),
188
189    #[error("Missing witness signatures on KERI event: {0}")]
190    MissingWitnessSignatureError(String),
191
192    /// A remote event for a locally owned, witnessed or delegated identifier,
193    /// kept in the misfit escrow (keripy `MisfitEventSourceError`).
194    #[error("Misfit event source: {0}")]
195    MisfitEventSourceError(String),
196
197    /// A delegated event waiting for its local delegator's approval, kept in
198    /// the delegable escrow (keripy `MissingDelegableApprovalError`).
199    #[error("Missing delegable approval: {0}")]
200    MissingDelegableApprovalError(String),
201
202    /// A delegated event whose delegating seal is not available yet
203    /// (keripy `MissingDelegationError`).
204    #[error("Missing delegation: {0}")]
205    MissingDelegationError(String),
206
207    #[error("Counter error")]
208    CounterError(String),
209
210    #[error("Index error")]
211    IndexError(String),
212
213    #[error("Closed error")]
214    ClosedError(String),
215}
216
217impl From<MatterError> for KERIError {
218    fn from(error: MatterError) -> Self {
219        match error {
220            MatterError::InvalidCode(code) => {
221                KERIError::ValidationError(format!("Invalid Matter code: {}", code))
222            }
223
224            // Fallback for any other errors or future-added error types
225            _ => KERIError::MatterError(format!("{:?}", error)),
226        }
227    }
228}
229/// Extracts and validates version information from a regex match
230///
231/// # Arguments
232/// * `captures` - Regex captures from a version string match
233///
234/// # Returns
235/// * `Result<Smellage, Error>` - A structured version information or an error
236pub fn rematch(captures: &regex::Captures) -> Result<Smellage, KERIError> {
237    let full = captures.get(0).unwrap().as_str().as_bytes();
238
239    if full.len() == VER2FULLSPAN && full[full.len() - 1] == VER2TERM[0] {
240        // Version 2 format
241        let proto = captures.name("proto2").unwrap().as_str();
242        let major = captures.name("major2").unwrap().as_str();
243        let minor = captures.name("minor2").unwrap().as_str();
244        let kind = captures.name("kind2").unwrap().as_str();
245        let size = captures.name("size2").unwrap().as_str();
246
247        if !Protocolage::contains(proto) {
248            return Err(KERIError::VersionError(proto.to_string()));
249        }
250
251        let vrsn = Versionage {
252            major: b64_to_int(major),
253            minor: b64_to_int(minor),
254        };
255
256        let gvrsn = Versionage {
257            major: b64_to_int(major),
258            minor: b64_to_int(minor),
259        };
260
261        if vrsn.major < 2 {
262            return Err(KERIError::VersionError(format!(
263                "{}.{}",
264                vrsn.major, vrsn.minor
265            )));
266        }
267
268        if !Kinds::contains(kind) {
269            return Err(KERIError::KindError(kind.to_string()));
270        }
271
272        let size_val = b64_to_int(size);
273
274        Ok(Smellage {
275            proto: proto.to_string(),
276            vrsn: vrsn.into(),
277            gvrsn: gvrsn.into(),
278            kind: kind.to_string(),
279            size: size_val as usize,
280        })
281    } else if full.len() == VER1FULLSPAN && full[full.len() - 1] == VER1TERM[0] {
282        // Version 1 format
283        let proto = captures.name("proto1").unwrap().as_str();
284        let major = captures.name("major1").unwrap().as_str();
285        let minor = captures.name("minor1").unwrap().as_str();
286        let kind = captures.name("kind1").unwrap().as_str();
287        let size = captures.name("size1").unwrap().as_str();
288
289        if !Protocolage::contains(proto) {
290            return Err(KERIError::ProtocolError(proto.to_string()));
291        }
292
293        let vrsn = Versionage {
294            major: u32::from_str_radix(major, 16).expect("Failed to parse hex"),
295            minor: u32::from_str_radix(minor, 16).expect("Failed to parse hex"),
296        };
297
298        let gvrsn = Versionage {
299            major: u32::from_str_radix(major, 16).expect("Failed to parse hex"),
300            minor: u32::from_str_radix(minor, 16).expect("Failed to parse hex"),
301        };
302
303        if vrsn.major > 1 {
304            return Err(KERIError::Incompatible(vrsn));
305        }
306
307        if !Kinds::contains(kind) {
308            return Err(KERIError::KindError(kind.to_string()));
309        }
310
311        let size_val = u32::from_str_radix(size, 16).expect("Failed to parse hex");
312
313        Ok(Smellage {
314            proto: proto.to_string(),
315            vrsn: vrsn.into(),
316            gvrsn: gvrsn.into(),
317            kind: kind.to_string(),
318            size: size_val as usize,
319        })
320    } else {
321        Err(KERIError::VersionError(format!("{:?}", full)))
322    }
323}
324
325/// Creates a version string based on protocol, version, kind, and size
326///
327/// # Arguments
328///
329/// * `protocol` - Protocol identifier, one of the valid Protocols values
330/// * `version` - Version information consisting of major and minor parts
331/// * `kind` - Serialization kind, one of the valid Kinds values
332/// * `size` - Length of serialized map that embeds version string field
333///
334/// # Returns
335///
336/// A formatted version string according to the version format
337///
338/// # Errors
339///
340/// Returns an error if the protocol or kind is invalid
341pub fn versify(
342    protocol: &str,
343    version: &Versionage,
344    kind: &str,
345    size: u64,
346) -> Result<String, KERIError> {
347    if !Protocolage::contains(protocol) {
348        return Err(KERIError::ProtocolError(protocol.to_string()));
349    }
350    if !Kinds::contains(kind) {
351        return Err(KERIError::KindError(kind.to_string()));
352    }
353
354    if version.major < 2 {
355        // Version 1 format
356        Ok(format!(
357            "{}{:x}{:x}{}{:0width$x}_",
358            protocol,
359            version.major,
360            version.minor,
361            kind,
362            size,
363            width = VERRAWSIZE
364        ))
365    } else {
366        // Version 2+ format
367        Ok(format!(
368            "{}{}{}{}{}{}",
369            protocol,
370            int_to_b64(version.major, 1),
371            int_to_b64(version.minor, 2),
372            kind,
373            int_to_b64(size as u32, 4),
374            std::str::from_utf8(VER2TERM).unwrap()
375        ))
376    }
377}
378
379/// Extracts protocol type, version, serialization kind, and size from a version string
380///
381/// # Arguments
382///
383/// * `vs` - A version string, either as a string slice or byte slice
384///
385/// # Returns
386///
387/// A Result containing a Smellage struct with extracted information or an error
388///
389/// # Errors
390///
391/// Returns an error if the version string format is invalid
392pub fn deversify<T: AsRef<[u8]>>(vs: T) -> Result<Smellage, KERIError> {
393    // Convert input to bytes if it's not already
394    let vs_bytes = vs.as_ref();
395
396    let vs_str = std::str::from_utf8(vs_bytes)
397        .map_err(|e| KERIError::VersionError(format!("Invalid UTF-8: {}", e)))?;
398    // Match the version string against the regex pattern
399    match REVER.captures(vs_str) {
400        Some(captures) => rematch(&captures),
401        None => Err(KERIError::VersionError(
402            String::from_utf8_lossy(vs_bytes).to_string(),
403        )),
404    }
405}
406
407/// Extract and return an instance of Smellage from a version string inside raw serialization.
408///
409/// # Arguments
410///
411/// * `raw` - A byte slice containing serialized incoming message stream.
412///   Assumes start of stream is JSON, CBOR, or MGPK field map with first field
413///   is labeled 'v' and value is version string.
414///
415/// # Returns
416///
417/// A Result containing a Smellage struct with extracted information or an error
418///
419/// # Errors
420///
421/// Returns a ShortageError if the raw bytes are too short to contain a full version string.
422/// Returns a VersionError if the version string is invalid or not found within MAXVSOFFSET.
423pub fn smell(raw: &[u8]) -> Result<Smellage, KERIError> {
424    if raw.len() < SMELLSIZE {
425        return Err(KERIError::VersionError(
426            "Need more raw bytes to smell full version string.".to_string(),
427        ));
428    }
429
430    let raw_str = std::str::from_utf8(raw)
431        .map_err(|e| KERIError::VersionError(format!("Invalid UTF-8: {}", e)))?;
432    // Search for version string pattern in raw bytes
433    match REVER.find(raw_str) {
434        Some(mat) if mat.start() <= MAXVSOFFSET => {
435            // If found and within max offset, extract captures and get Smellage
436            let caps = REVER
437                .captures(raw_str)
438                .expect("Match should contain captures");
439            rematch(&caps)
440        }
441        _ => {
442            // Either not found or found outside max offset
443            Err(KERIError::VersionError(format!(
444                "Invalid version string from smelled raw = {:?}",
445                &raw[..SMELLSIZE.min(raw.len())]
446            )))
447        }
448    }
449}
450
451/// KERI/ACDC protocol packet (message) types
452#[derive(Debug, Clone, Copy, PartialEq, Eq)]
453pub struct Ilks;
454
455impl Ilks {
456    pub const ICP: &'static str = "icp";
457    pub const ROT: &'static str = "rot";
458    pub const IXN: &'static str = "ixn";
459    pub const DIP: &'static str = "dip";
460    pub const DRT: &'static str = "drt";
461    pub const RCT: &'static str = "rct";
462    pub const QRY: &'static str = "qry";
463    pub const RPY: &'static str = "rpy";
464    pub const XIP: &'static str = "xip";
465    pub const EXN: &'static str = "exn";
466    pub const PRO: &'static str = "pro";
467    pub const BAR: &'static str = "bar";
468    pub const VCP: &'static str = "vcp";
469    pub const VRT: &'static str = "vrt";
470    pub const ISS: &'static str = "iss";
471    pub const REV: &'static str = "rev";
472    pub const BIS: &'static str = "bis";
473    pub const BRV: &'static str = "brv";
474    pub const RIP: &'static str = "rip";
475    pub const UPD: &'static str = "upd";
476    pub const ACD: &'static str = "acd";
477    pub const ACE: &'static str = "ace";
478    pub const SCH: &'static str = "sch";
479    pub const ATT: &'static str = "att";
480    pub const AGG: &'static str = "agg";
481    pub const EDG: &'static str = "edg";
482    pub const RUL: &'static str = "rul";
483
484    /// Returns all Ilk values as a vector of strings
485    pub fn all() -> Vec<&'static str> {
486        vec![
487            Self::ICP,
488            Self::ROT,
489            Self::IXN,
490            Self::DIP,
491            Self::DRT,
492            Self::RCT,
493            Self::QRY,
494            Self::RPY,
495            Self::XIP,
496            Self::EXN,
497            Self::PRO,
498            Self::BAR,
499            Self::VCP,
500            Self::VRT,
501            Self::ISS,
502            Self::REV,
503            Self::BIS,
504            Self::BRV,
505            Self::RIP,
506            Self::UPD,
507            Self::ACD,
508            Self::ACE,
509            Self::SCH,
510            Self::ATT,
511            Self::AGG,
512            Self::EDG,
513            Self::RUL,
514        ]
515    }
516
517    /// Checks if a given string is a valid Ilk
518    pub fn is_valid(ilk: &str) -> bool {
519        Self::all().contains(&ilk)
520    }
521}
522
523impl std::hash::Hash for Ilk {
524    fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
525        self.as_str().hash(state);
526    }
527}
528/// Alternative representation of Ilks using an enum
529#[derive(Debug, Clone, Copy, PartialEq, Eq)]
530pub enum Ilk {
531    Icp,
532    Rot,
533    Ixn,
534    Dip,
535    Drt,
536    Rct,
537    Qry,
538    Rpy,
539    Xip,
540    Exn,
541    Pro,
542    Bar,
543    Vcp,
544    Vrt,
545    Iss,
546    Rev,
547    Bis,
548    Brv,
549    Rip,
550    Upd,
551    Acd,
552    Ace,
553    Sch,
554    Att,
555    Agg,
556    Edg,
557    Rul,
558}
559
560impl Ilk {
561    /// Convert enum variant to string representation
562    pub fn as_str(&self) -> &'static str {
563        match self {
564            Ilk::Icp => Ilks::ICP,
565            Ilk::Rot => Ilks::ROT,
566            Ilk::Ixn => Ilks::IXN,
567            Ilk::Dip => Ilks::DIP,
568            Ilk::Drt => Ilks::DRT,
569            Ilk::Rct => Ilks::RCT,
570            Ilk::Qry => Ilks::QRY,
571            Ilk::Rpy => Ilks::RPY,
572            Ilk::Xip => Ilks::XIP,
573            Ilk::Exn => Ilks::EXN,
574            Ilk::Pro => Ilks::PRO,
575            Ilk::Bar => Ilks::BAR,
576            Ilk::Vcp => Ilks::VCP,
577            Ilk::Vrt => Ilks::VRT,
578            Ilk::Iss => Ilks::ISS,
579            Ilk::Rev => Ilks::REV,
580            Ilk::Bis => Ilks::BIS,
581            Ilk::Brv => Ilks::BRV,
582            Ilk::Rip => Ilks::RIP,
583            Ilk::Upd => Ilks::UPD,
584            Ilk::Acd => Ilks::ACD,
585            Ilk::Ace => Ilks::ACE,
586            Ilk::Sch => Ilks::SCH,
587            Ilk::Att => Ilks::ATT,
588            Ilk::Agg => Ilks::AGG,
589            Ilk::Edg => Ilks::EDG,
590            Ilk::Rul => Ilks::RUL,
591        }
592    }
593
594    /// Try to create an Ilk from a string
595    pub fn from_str(s: &str) -> Option<Self> {
596        match s {
597            Ilks::ICP => Some(Ilk::Icp),
598            Ilks::ROT => Some(Ilk::Rot),
599            Ilks::IXN => Some(Ilk::Ixn),
600            Ilks::DIP => Some(Ilk::Dip),
601            Ilks::DRT => Some(Ilk::Drt),
602            Ilks::RCT => Some(Ilk::Rct),
603            Ilks::QRY => Some(Ilk::Qry),
604            Ilks::RPY => Some(Ilk::Rpy),
605            Ilks::XIP => Some(Ilk::Xip),
606            Ilks::EXN => Some(Ilk::Exn),
607            Ilks::PRO => Some(Ilk::Pro),
608            Ilks::BAR => Some(Ilk::Bar),
609            Ilks::VCP => Some(Ilk::Vcp),
610            Ilks::VRT => Some(Ilk::Vrt),
611            Ilks::ISS => Some(Ilk::Iss),
612            Ilks::REV => Some(Ilk::Rev),
613            Ilks::BIS => Some(Ilk::Bis),
614            Ilks::BRV => Some(Ilk::Brv),
615            Ilks::RIP => Some(Ilk::Rip),
616            Ilks::UPD => Some(Ilk::Upd),
617            Ilks::ACD => Some(Ilk::Acd),
618            Ilks::ACE => Some(Ilk::Ace),
619            Ilks::SCH => Some(Ilk::Sch),
620            Ilks::ATT => Some(Ilk::Att),
621            Ilks::AGG => Some(Ilk::Agg),
622            Ilks::EDG => Some(Ilk::Edg),
623            Ilks::RUL => Some(Ilk::Rul),
624            _ => None,
625        }
626    }
627}
628
629// This allows: let ilk: Ilk = "icp".try_into().unwrap();
630impl TryFrom<&str> for Ilk {
631    type Error = String;
632
633    fn try_from(s: &str) -> Result<Self, Self::Error> {
634        Self::from_str(s).ok_or_else(|| format!("Invalid ilk: {}", s))
635    }
636}
637
638// This allows: format!("{}", ilk)
639impl fmt::Display for Ilk {
640    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
641        write!(f, "{}", self.as_str())
642    }
643}
644
645#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
646pub enum Roles {
647    Controller,
648    Witness,
649    Registrar,
650    Gateway,
651    Watcher,
652    Judge,
653    Juror,
654    Peer,
655    Mailbox,
656    Agent,
657    Indexer,
658}
659
660impl Roles {
661    /// Returns the string representation of the role
662    pub fn as_str(&self) -> &'static str {
663        match self {
664            Roles::Controller => "controller",
665            Roles::Witness => "witness",
666            Roles::Registrar => "registrar",
667            Roles::Gateway => "gateway",
668            Roles::Watcher => "watcher",
669            Roles::Judge => "judge",
670            Roles::Juror => "juror",
671            Roles::Peer => "peer",
672            Roles::Mailbox => "mailbox",
673            Roles::Agent => "agent",
674            Roles::Indexer => "indexer",
675        }
676    }
677}
678
679impl std::fmt::Display for Roles {
680    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
681        write!(f, "{}", self.as_str())
682    }
683}
684
685impl std::str::FromStr for Roles {
686    type Err = String;
687
688    fn from_str(s: &str) -> Result<Self, Self::Err> {
689        match s {
690            "controller" => Ok(Roles::Controller),
691            "witness" => Ok(Roles::Witness),
692            "registrar" => Ok(Roles::Registrar),
693            "gateway" => Ok(Roles::Gateway),
694            "watcher" => Ok(Roles::Watcher),
695            "judge" => Ok(Roles::Judge),
696            "juror" => Ok(Roles::Juror),
697            "peer" => Ok(Roles::Peer),
698            "mailbox" => Ok(Roles::Mailbox),
699            "agent" => Ok(Roles::Agent),
700            "indexer" => Ok(Roles::Indexer),
701            _ => Err(format!("Unknown role: {}", s)),
702        }
703    }
704}
705
706#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
707pub enum Schemes {
708    Tcp,
709    Http,
710    Https,
711}
712
713impl Schemes {
714    /// Returns the string representation of the scheme
715    pub fn as_str(&self) -> &'static str {
716        match self {
717            Schemes::Tcp => "tcp",
718            Schemes::Http => "http",
719            Schemes::Https => "https",
720        }
721    }
722}
723
724impl std::fmt::Display for Schemes {
725    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
726        write!(f, "{}", self.as_str())
727    }
728}
729
730impl std::str::FromStr for Schemes {
731    type Err = String;
732
733    fn from_str(s: &str) -> Result<Self, Self::Err> {
734        match s {
735            "tcp" => Ok(Schemes::Tcp),
736            "http" => Ok(Schemes::Http),
737            "https" => Ok(Schemes::Https),
738            _ => Err(format!("Unknown scheme: {}", s)),
739        }
740    }
741}
742
743/// SAID field labels
744#[derive(Debug, Clone, Copy, PartialEq, Eq)]
745pub struct Saids;
746
747impl Saids {
748    pub const DOLLAR: &'static str = "$id";
749    pub const AT: &'static str = "@id";
750    pub const ID: &'static str = "id";
751    pub const I: &'static str = "i";
752    pub const D: &'static str = "d";
753
754    /// Returns all SAID field labels as a vector of strings
755    pub fn all() -> Vec<&'static str> {
756        vec![Self::DOLLAR, Self::AT, Self::ID, Self::I, Self::D]
757    }
758
759    /// Checks if a given string is a valid SAID field label
760    pub fn is_valid(label: &str) -> bool {
761        Self::all().contains(&label)
762    }
763}
764
765/// Alternative representation of SAID field labels using an enum
766#[derive(Debug, Clone, Copy, PartialEq, Eq)]
767pub enum Said {
768    Dollar,
769    At,
770    Id,
771    I,
772    D,
773}
774
775impl Said {
776    /// Convert enum variant to string representation
777    pub fn as_str(&self) -> &'static str {
778        match self {
779            Said::Dollar => Saids::DOLLAR,
780            Said::At => Saids::AT,
781            Said::Id => Saids::ID,
782            Said::I => Saids::I,
783            Said::D => Saids::D,
784        }
785    }
786
787    /// Try to create a Said from a string
788    pub fn from_str(s: &str) -> Option<Self> {
789        match s {
790            Saids::DOLLAR => Some(Said::Dollar),
791            Saids::AT => Some(Said::At),
792            Saids::ID => Some(Said::Id),
793            Saids::I => Some(Said::I),
794            Saids::D => Some(Said::D),
795            _ => None,
796        }
797    }
798}
799
800// This allows: let said: Said = "$id".try_into().unwrap();
801impl TryFrom<&str> for Said {
802    type Error = String;
803
804    fn try_from(s: &str) -> Result<Self, Self::Error> {
805        Self::from_str(s).ok_or_else(|| format!("Invalid SAID field label: {}", s))
806    }
807}
808
809// This allows: format!("{}", said)
810impl fmt::Display for Said {
811    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
812        write!(f, "{}", self.as_str())
813    }
814}
815
816/// Represents message envelope properties
817#[derive(Debug, Clone, PartialEq)]
818pub struct Smellage {
819    /// Protocol identifier
820    pub proto: String,
821    /// Version Versionage
822    pub vrsn: Versionage,
823    /// Message kind
824    pub kind: String,
825    /// Size of the message
826    pub size: usize,
827    /// KERI global version, optional with default None
828    pub gvrsn: Option<Versionage>,
829}
830
831impl Smellage {
832    /// Create a new Smellage instance
833    pub fn new(
834        proto: impl Into<String>,
835        vrsn: Versionage,
836        kind: impl Into<String>,
837        size: usize,
838    ) -> Self {
839        Self {
840            proto: proto.into(),
841            vrsn,
842            kind: kind.into(),
843            size,
844            gvrsn: None,
845        }
846    }
847
848    /// Create a new Smellage instance with all fields including gvrsn
849    pub fn with_gvrsn(
850        proto: impl Into<String>,
851        vrsn: Versionage,
852        kind: impl Into<String>,
853        size: usize,
854        gvrsn: Versionage,
855    ) -> Self {
856        Self {
857            proto: proto.into(),
858            vrsn,
859            kind: kind.into(),
860            size,
861            gvrsn: Some(gvrsn),
862        }
863    }
864}
865
866/// Builder pattern for more flexible construction
867pub struct SmellageBuilder {
868    proto: Option<String>,
869    vrsn: Option<Versionage>,
870    kind: Option<String>,
871    size: Option<usize>,
872    gvrsn: Option<Versionage>,
873}
874
875impl SmellageBuilder {
876    /// Create a new empty builder
877    pub fn new() -> Self {
878        Self {
879            proto: None,
880            vrsn: None,
881            kind: None,
882            size: None,
883            gvrsn: None,
884        }
885    }
886
887    /// Set the protocol identifier
888    pub fn proto(mut self, proto: impl Into<String>) -> Self {
889        self.proto = Some(proto.into());
890        self
891    }
892
893    /// Set the version string
894    pub fn vrsn(mut self, vrsn: Versionage) -> Self {
895        self.vrsn = Some(vrsn);
896        self
897    }
898
899    /// Set the message kind
900    pub fn kind(mut self, kind: impl Into<String>) -> Self {
901        self.kind = Some(kind.into());
902        self
903    }
904
905    /// Set the size of the message
906    pub fn size(mut self, size: usize) -> Self {
907        self.size = Some(size);
908        self
909    }
910
911    /// Set the KERI global version
912    pub fn gvrsn(mut self, gvrsn: Versionage) -> Self {
913        self.gvrsn = Some(gvrsn);
914        self
915    }
916
917    /// Build the Smellage instance
918    pub fn build(self) -> Result<Smellage, String> {
919        let proto = self.proto.ok_or_else(|| "proto is required".to_string())?;
920        let vrsn = self.vrsn.ok_or_else(|| "vrsn is required".to_string())?;
921        let kind = self.kind.ok_or_else(|| "kind is required".to_string())?;
922        let size = self.size.ok_or_else(|| "size is required".to_string())?;
923
924        Ok(Smellage {
925            proto,
926            vrsn,
927            kind,
928            size,
929            gvrsn: self.gvrsn,
930        })
931    }
932}
933
934impl Default for SmellageBuilder {
935    fn default() -> Self {
936        Self::new()
937    }
938}
939
940/// Enum representing serialization kinds
941#[derive(Debug, PartialEq, Eq, Clone, Copy)]
942pub enum Kinds {
943    Json,
944    Mgpk,
945    Cbor,
946    Cesr,
947}
948
949impl Kinds {
950    pub fn contains(other: &str) -> bool {
951        "JSON" == other || "MGPK" == other || "CBOR" == other || "CESR" == other
952    }
953
954    pub fn from(kind: &str) -> Result<Self, KERIError> {
955        match kind {
956            "JSON" => Ok(Self::Json),
957            "MGPK" => Ok(Self::Mgpk),
958            "CBOR" => Ok(Self::Cbor),
959            "CESR" => Ok(Self::Cesr),
960            _ => Err(KERIError::VersionError(format!(
961                "Invalid serialization kind: {}",
962                kind
963            ))),
964        }
965    }
966}
967
968impl fmt::Display for Kinds {
969    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
970        match self {
971            Kinds::Json => write!(f, "JSON"),
972            Kinds::Mgpk => write!(f, "MGPK"),
973            Kinds::Cbor => write!(f, "CBOR"),
974            Kinds::Cesr => write!(f, "CESR"),
975        }
976    }
977}
978
979/// Represents supported protocol types
980#[derive(Debug, Clone, PartialEq, Eq, Hash)]
981pub struct Protocolage {
982    /// KERI protocol identifier
983    pub keri: String,
984
985    /// ACDC protocol identifier
986    pub acdc: String,
987}
988
989impl Protocolage {
990    /// Create a new Protocolage instance
991    pub fn new(keri: impl Into<String>, acdc: impl Into<String>) -> Self {
992        Self {
993            keri: keri.into(),
994            acdc: acdc.into(),
995        }
996    }
997
998    pub fn contains(other: &str) -> bool {
999        "KERI" == other || "ACDC" == other
1000    }
1001}
1002
1003impl Default for Protocolage {
1004    fn default() -> Self {
1005        Self {
1006            keri: "KERI".to_string(),
1007            acdc: "ACDC".to_string(),
1008        }
1009    }
1010}
1011
1012/// Add conversion from tuple for convenience
1013impl From<(String, String)> for Protocolage {
1014    fn from(tuple: (String, String)) -> Self {
1015        Self {
1016            keri: tuple.0,
1017            acdc: tuple.1,
1018        }
1019    }
1020}
1021
1022/// Allow conversion from &str tuple
1023impl From<(&str, &str)> for Protocolage {
1024    fn from(tuple: (&str, &str)) -> Self {
1025        Self {
1026            keri: tuple.0.to_string(),
1027            acdc: tuple.1.to_string(),
1028        }
1029    }
1030}
1031
1032#[cfg(test)]
1033mod tests {
1034    use super::*;
1035
1036    #[test]
1037    fn test_ilk_constants() {
1038        assert_eq!(Ilks::ICP, "icp");
1039        assert_eq!(Ilks::ROT, "rot");
1040        assert_eq!(Ilks::IXN, "ixn");
1041        // ... and so on
1042    }
1043
1044    #[test]
1045    fn test_all_ilks() {
1046        let all = Ilks::all();
1047        assert_eq!(all.len(), 27); // Total number of Ilks
1048        assert!(all.contains(&"icp"));
1049        assert!(all.contains(&"rot"));
1050        // ... and so on
1051    }
1052
1053    #[test]
1054    fn test_is_valid_ilk() {
1055        assert!(Ilks::is_valid("icp"));
1056        assert!(Ilks::is_valid("rot"));
1057        assert!(!Ilks::is_valid("invalid"));
1058    }
1059
1060    #[test]
1061    fn test_ilk_enum() {
1062        assert_eq!(Ilk::Icp.as_str(), "icp");
1063        assert_eq!(Ilk::Rot.as_str(), "rot");
1064        // ... and so on
1065    }
1066
1067    #[test]
1068    fn test_ilk_from_str() {
1069        assert_eq!(Ilk::from_str("icp"), Some(Ilk::Icp));
1070        assert_eq!(Ilk::from_str("rot"), Some(Ilk::Rot));
1071        assert_eq!(Ilk::from_str("invalid"), None);
1072    }
1073
1074    #[test]
1075    fn test_ilk_try_from() {
1076        let ilk: Result<Ilk, _> = "icp".try_into();
1077        assert!(ilk.is_ok());
1078        assert_eq!(ilk.unwrap(), Ilk::Icp);
1079
1080        let invalid: Result<Ilk, _> = "invalid".try_into();
1081        assert!(invalid.is_err());
1082    }
1083
1084    #[test]
1085    fn test_ilk_display() {
1086        assert_eq!(format!("{}", Ilk::Icp), "icp");
1087        assert_eq!(format!("{}", Ilk::Rot), "rot");
1088    }
1089
1090    #[test]
1091    fn test_said_constants() {
1092        assert_eq!(Saids::DOLLAR, "$id");
1093        assert_eq!(Saids::AT, "@id");
1094        assert_eq!(Saids::ID, "id");
1095        assert_eq!(Saids::I, "i");
1096        assert_eq!(Saids::D, "d");
1097    }
1098
1099    #[test]
1100    fn test_all_saids() {
1101        let all = Saids::all();
1102        assert_eq!(all.len(), 5); // Total number of SAID field labels
1103        assert!(all.contains(&"$id"));
1104        assert!(all.contains(&"@id"));
1105        assert!(all.contains(&"id"));
1106        assert!(all.contains(&"i"));
1107        assert!(all.contains(&"d"));
1108    }
1109
1110    #[test]
1111    fn test_is_valid_said() {
1112        assert!(Saids::is_valid("$id"));
1113        assert!(Saids::is_valid("@id"));
1114        assert!(Saids::is_valid("id"));
1115        assert!(Saids::is_valid("i"));
1116        assert!(Saids::is_valid("d"));
1117        assert!(!Saids::is_valid("invalid"));
1118    }
1119
1120    #[test]
1121    fn test_said_enum() {
1122        assert_eq!(Said::Dollar.as_str(), "$id");
1123        assert_eq!(Said::At.as_str(), "@id");
1124        assert_eq!(Said::Id.as_str(), "id");
1125        assert_eq!(Said::I.as_str(), "i");
1126        assert_eq!(Said::D.as_str(), "d");
1127    }
1128
1129    #[test]
1130    fn test_said_from_str() {
1131        assert_eq!(Said::from_str("$id"), Some(Said::Dollar));
1132        assert_eq!(Said::from_str("@id"), Some(Said::At));
1133        assert_eq!(Said::from_str("id"), Some(Said::Id));
1134        assert_eq!(Said::from_str("i"), Some(Said::I));
1135        assert_eq!(Said::from_str("d"), Some(Said::D));
1136        assert_eq!(Said::from_str("invalid"), None);
1137    }
1138
1139    #[test]
1140    fn test_said_try_from() {
1141        let dollar: Result<Said, _> = "$id".try_into();
1142        assert!(dollar.is_ok());
1143        assert_eq!(dollar.unwrap(), Said::Dollar);
1144
1145        let at: Result<Said, _> = "@id".try_into();
1146        assert!(at.is_ok());
1147        assert_eq!(at.unwrap(), Said::At);
1148
1149        let invalid: Result<Said, _> = "invalid".try_into();
1150        assert!(invalid.is_err());
1151    }
1152
1153    #[test]
1154    fn test_said_display() {
1155        assert_eq!(format!("{}", Said::Dollar), "$id");
1156        assert_eq!(format!("{}", Said::At), "@id");
1157        assert_eq!(format!("{}", Said::Id), "id");
1158        assert_eq!(format!("{}", Said::I), "i");
1159        assert_eq!(format!("{}", Said::D), "d");
1160    }
1161    #[test]
1162    fn test_smellage_new() {
1163        let smell = Smellage::new("KERI", Versionage { major: 1, minor: 0 }, "icp", 123);
1164        assert_eq!(smell.proto, "KERI");
1165        assert_eq!(smell.vrsn, Versionage { major: 1, minor: 0 });
1166        assert_eq!(smell.kind, "icp");
1167        assert_eq!(smell.size, 123);
1168        assert_eq!(smell.gvrsn, None);
1169    }
1170
1171    #[test]
1172    fn test_smellage_with_gvrsn() {
1173        let smell = Smellage::with_gvrsn(
1174            "KERI",
1175            Versionage { major: 1, minor: 0 },
1176            "icp",
1177            123,
1178            Versionage { major: 1, minor: 0 },
1179        );
1180        assert_eq!(smell.proto, "KERI");
1181        assert_eq!(smell.vrsn, Versionage { major: 1, minor: 0 });
1182        assert_eq!(smell.kind, "icp");
1183        assert_eq!(smell.size, 123);
1184        assert_eq!(smell.gvrsn, Some(Versionage { major: 1, minor: 0 }));
1185    }
1186
1187    #[test]
1188    fn test_smellage_builder() {
1189        let smell = SmellageBuilder::new()
1190            .proto("KERI")
1191            .vrsn(Versionage { major: 1, minor: 0 })
1192            .kind("rot")
1193            .size(256)
1194            .gvrsn(Versionage { major: 1, minor: 0 })
1195            .build()
1196            .unwrap();
1197
1198        assert_eq!(smell.proto, "KERI");
1199        assert_eq!(smell.vrsn, Versionage { major: 1, minor: 0 });
1200        assert_eq!(smell.kind, "rot");
1201        assert_eq!(smell.size, 256);
1202        assert_eq!(smell.gvrsn, Some(Versionage { major: 1, minor: 0 }));
1203    }
1204
1205    #[test]
1206    fn test_builder_error() {
1207        let result = SmellageBuilder::new()
1208            .proto("KERI")
1209            .vrsn(Versionage { major: 1, minor: 0 })
1210            .size(256)
1211            .build();
1212
1213        assert!(result.is_err());
1214        assert_eq!(result.unwrap_err(), "kind is required");
1215    }
1216
1217    #[test]
1218    fn test_protocolage_new() {
1219        let proto = Protocolage::new("KERI", "ACDC");
1220        assert_eq!(proto.keri, "KERI");
1221        assert_eq!(proto.acdc, "ACDC");
1222    }
1223
1224    #[test]
1225    fn test_protocolage_default() {
1226        let proto = Protocolage::default();
1227        assert_eq!(proto.keri, "KERI");
1228        assert_eq!(proto.acdc, "ACDC");
1229    }
1230
1231    #[test]
1232    fn test_protocolage_from_tuple() {
1233        let proto: Protocolage = ("KERI".to_string(), "ACDC".to_string()).into();
1234        assert_eq!(proto.keri, "KERI");
1235        assert_eq!(proto.acdc, "ACDC");
1236
1237        let proto: Protocolage = ("KERI", "ACDC").into();
1238        assert_eq!(proto.keri, "KERI");
1239        assert_eq!(proto.acdc, "ACDC");
1240    }
1241}