Skip to main content

libkeri/keri/core/serdering/
sad.rs

1use crate::cesr::{dig_dex, get_sizes, mtr_dex, BaseMatter};
2use crate::keri::{Ilk, Ilks, KERIError, Kinds, Said};
3use crate::Matter;
4use indexmap::IndexMap;
5use serde::ser::{SerializeMap, SerializeSeq};
6use serde::{de, ser};
7use serde::{Deserialize, Serialize};
8use serde::{Deserializer, Serializer};
9use serde_json::Number;
10use std::collections::HashMap;
11use std::fmt;
12
13#[derive(Clone)]
14pub enum SadValue {
15    Bool(bool),
16    Number(Number),
17    String(String),
18    Array(Vec<SadValue>),
19    Object(IndexMap<String, SadValue>),
20}
21
22pub type Sadder = IndexMap<String, SadValue>;
23
24impl SadValue {
25    /// Deserializes raw bytes into a data structure based on the specified kind
26    ///
27    /// # Arguments
28    ///
29    /// * `raw` - Raw bytes to deserialize
30    /// * `size` - Number of bytes to consume for deserialization (if None, uses all bytes)
31    /// * `kind` - Serialization format (JSON, MGPK, CBOR)
32    ///
33    /// # Returns
34    ///
35    /// A Result containing either the deserialized data or a KERIError
36    ///
37    /// # Notes
38    ///
39    /// JSON deserialization uses UTF-8 string conversion, while CBOR and MGPK operate directly on bytes
40    pub fn loads(raw: &[u8], size: Option<usize>, kind: Kinds) -> Result<Sadder, KERIError> {
41        // Determine how many bytes to use
42        let limit = size.unwrap_or(raw.len());
43        let data = &raw[..std::cmp::min(limit, raw.len())];
44
45        match kind {
46            Kinds::Json => {
47                // Convert bytes to UTF-8 string for JSON
48                match std::str::from_utf8(data) {
49                    Ok(text) => {
50                        let sadder = serde_json::from_str(text)
51                            .map_err(|e| KERIError::JsonError(e.to_string()))?;
52                        Ok(sadder)
53                    }
54                    Err(e) => Err(KERIError::JsonError(format!(
55                        "Invalid UTF-8 sequence: {}",
56                        e
57                    ))),
58                }
59            }
60            Kinds::Mgpk => {
61                let sadder =
62                    rmp_serde::from_slice(data).map_err(|e| KERIError::MgpkError(e.to_string()))?;
63                Ok(sadder)
64            }
65
66            Kinds::Cbor => {
67                let sadder = serde_cbor::from_slice(data)
68                    .map_err(|e| KERIError::CborError(e.to_string()))?;
69                Ok(sadder)
70            }
71            Kinds::Cesr => Err(KERIError::MgpkError(
72                "CESR deserialization not implemented".to_string(),
73            )),
74        }
75    }
76
77    ///
78    /// # Parameters:
79    /// * `sad`: Optional data to serialize. If None, uses default empty data
80    /// * `kind`: Serialization format (Json, Cbor, MsgPack)
81    /// * `proto`: Optional protocol type
82    /// * `vrsn`: Optional protocol version
83    ///
84    /// # Returns:
85    /// Serialized bytes of the data
86    ///
87    /// # Errors:
88    /// Returns a KERIError if serialization fails
89    pub fn dumps(sad: &Sadder, kind: &Kinds) -> Result<Vec<u8>, KERIError> {
90        match kind {
91            Kinds::Json => match serde_json::to_string(sad) {
92                Ok(json_str) => Ok(json_str.into_bytes()),
93                Err(e) => Err(KERIError::DeserializeError(e.to_string())),
94            },
95            Kinds::Mgpk => match rmp_serde::to_vec(sad) {
96                Ok(mgpk_bytes) => Ok(mgpk_bytes),
97                Err(e) => Err(KERIError::DeserializeError(e.to_string())),
98            },
99            Kinds::Cbor => match serde_cbor::to_vec(sad) {
100                Ok(cbor_bytes) => Ok(cbor_bytes),
101                Err(e) => Err(KERIError::DeserializeError(e.to_string())),
102            },
103            Kinds::Cesr => Err(KERIError::DeserializeError(
104                "CESR serialization not enabled".to_string(),
105            )),
106        }
107    }
108
109    // Type checking methods
110    pub fn is_array(&self) -> bool {
111        matches!(self, SadValue::Array(_))
112    }
113
114    pub fn is_object(&self) -> bool {
115        matches!(self, SadValue::Object(_))
116    }
117
118    pub fn is_string(&self) -> bool {
119        matches!(self, SadValue::String(_))
120    }
121
122    pub fn is_number(&self) -> bool {
123        matches!(self, SadValue::Number(_))
124    }
125
126    pub fn is_bool(&self) -> bool {
127        matches!(self, SadValue::Bool(_))
128    }
129
130    pub fn is_i64(&self) -> bool {
131        match self {
132            SadValue::Number(n) => n.is_i64(),
133            _ => false,
134        }
135    }
136
137    pub fn is_u64(&self) -> bool {
138        match self {
139            SadValue::Number(n) => n.is_u64(),
140            _ => false,
141        }
142    }
143
144    pub fn is_f64(&self) -> bool {
145        match self {
146            SadValue::Number(n) => n.is_f64(),
147            _ => false,
148        }
149    }
150
151    // Value extraction methods
152    pub fn as_bool(&self) -> Option<bool> {
153        match self {
154            SadValue::Bool(b) => Some(*b),
155            _ => None,
156        }
157    }
158
159    pub fn as_i64(&self) -> Option<i64> {
160        match self {
161            SadValue::Number(n) => n.as_i64(),
162            _ => None,
163        }
164    }
165
166    pub fn as_u64(&self) -> Option<u64> {
167        match self {
168            SadValue::Number(n) => n.as_u64(),
169            _ => None,
170        }
171    }
172
173    pub fn as_f64(&self) -> Option<f64> {
174        match self {
175            SadValue::Number(n) => n.as_f64(),
176            _ => None,
177        }
178    }
179
180    pub fn as_str(&self) -> Option<&str> {
181        match self {
182            SadValue::String(s) => Some(s),
183            _ => None,
184        }
185    }
186
187    pub fn as_array(&self) -> Option<&Vec<SadValue>> {
188        match self {
189            SadValue::Array(a) => Some(a),
190            _ => None,
191        }
192    }
193
194    pub fn as_object(&self) -> Option<&IndexMap<String, SadValue>> {
195        match self {
196            SadValue::Object(o) => Some(o),
197            _ => None,
198        }
199    }
200
201    // Mutable access methods
202    pub fn as_array_mut(&mut self) -> Option<&mut Vec<SadValue>> {
203        match self {
204            SadValue::Array(a) => Some(a),
205            _ => None,
206        }
207    }
208
209    pub fn as_object_mut(&mut self) -> Option<&mut IndexMap<String, SadValue>> {
210        match self {
211            SadValue::Object(o) => Some(o),
212            _ => None,
213        }
214    }
215
216    // Take ownership methods
217    pub fn take_array(self) -> Option<Vec<SadValue>> {
218        match self {
219            SadValue::Array(a) => Some(a),
220            _ => None,
221        }
222    }
223
224    pub fn take_object(self) -> Option<IndexMap<String, SadValue>> {
225        match self {
226            SadValue::Object(o) => Some(o),
227            _ => None,
228        }
229    }
230
231    pub fn take_string(self) -> Option<String> {
232        match self {
233            SadValue::String(s) => Some(s),
234            _ => None,
235        }
236    }
237
238    pub fn take_bool(self) -> Option<bool> {
239        match self {
240            SadValue::Bool(b) => Some(b),
241            _ => None,
242        }
243    }
244
245    pub fn take_number(self) -> Option<Number> {
246        match self {
247            SadValue::Number(n) => Some(n),
248            _ => None,
249        }
250    }
251
252    // Conversion methods - from primitives to SadValue
253    pub fn from_bool(b: bool) -> Self {
254        SadValue::Bool(b)
255    }
256
257    pub fn from_i64(i: i64) -> Self {
258        SadValue::Number(Number::from(i))
259    }
260
261    pub fn from_u64(u: u64) -> Self {
262        SadValue::Number(Number::from(u))
263    }
264
265    pub fn from_f64(f: f64) -> Result<Self, String> {
266        match Number::from_f64(f) {
267            Some(n) => Ok(SadValue::Number(n)),
268            None => Err("Invalid float value".to_string()),
269        }
270    }
271
272    pub fn from_string<S: Into<String>>(s: S) -> Self {
273        SadValue::String(s.into())
274    }
275
276    pub fn from_array<A: IntoIterator<Item = SadValue>>(a: A) -> Self {
277        SadValue::Array(a.into_iter().collect())
278    }
279
280    pub fn from_object<O: IntoIterator<Item = (String, SadValue)>>(o: O) -> Self {
281        SadValue::Object(o.into_iter().collect())
282    }
283
284    // Accessor methods for nested values using paths
285    pub fn pointer(&self, path: &str) -> Option<&SadValue> {
286        if path.is_empty() || path == "/" {
287            return Some(self);
288        }
289
290        if !path.starts_with('/') {
291            return None;
292        }
293
294        let mut target = self;
295        for token in path[1..].split('/') {
296            let token = token.replace("~1", "/").replace("~0", "~");
297
298            match target {
299                SadValue::Object(map) => {
300                    target = map.get(&token)?;
301                }
302                SadValue::Array(vec) => {
303                    if let Ok(index) = token.parse::<usize>() {
304                        target = vec.get(index)?;
305                    } else {
306                        return None;
307                    }
308                }
309                _ => return None,
310            }
311        }
312
313        Some(target)
314    }
315
316    pub fn pointer_mut(&mut self, path: &str) -> Option<&mut SadValue> {
317        if path.is_empty() || path == "/" {
318            return Some(self);
319        }
320
321        if !path.starts_with('/') {
322            return None;
323        }
324
325        let mut target = self;
326        let tokens: Vec<_> = path[1..].split('/').collect();
327        let (last_token, path_tokens) = tokens.split_last()?;
328        let last_token = last_token.replace("~1", "/").replace("~0", "~");
329
330        for token in path_tokens {
331            let token = token.replace("~1", "/").replace("~0", "~");
332
333            target = match target {
334                SadValue::Object(map) => map.get_mut(&token)?,
335                SadValue::Array(vec) => {
336                    if let Ok(index) = token.parse::<usize>() {
337                        vec.get_mut(index)?
338                    } else {
339                        return None;
340                    }
341                }
342                _ => return None,
343            };
344        }
345
346        match target {
347            SadValue::Object(map) => map.get_mut(&last_token),
348            SadValue::Array(vec) => {
349                if let Ok(index) = last_token.parse::<usize>() {
350                    vec.get_mut(index)
351                } else {
352                    None
353                }
354            }
355            _ => None,
356        }
357    }
358
359    // Index methods
360    pub fn get<I: Index>(&self, index: I) -> Option<&SadValue> {
361        index.index_into(self)
362    }
363
364    pub fn get_mut<I: Index>(&mut self, index: I) -> Option<&mut SadValue> {
365        index.index_into_mut(self)
366    }
367}
368
369// Implement the Index trait for accessing elements more easily
370pub trait Index {
371    fn index_into(self, target: &SadValue) -> Option<&SadValue>;
372    fn index_into_mut(self, target: &mut SadValue) -> Option<&mut SadValue>;
373}
374
375impl Index for usize {
376    fn index_into(self, target: &SadValue) -> Option<&SadValue> {
377        match target {
378            SadValue::Array(arr) => arr.get(self),
379            _ => None,
380        }
381    }
382
383    fn index_into_mut(self, target: &mut SadValue) -> Option<&mut SadValue> {
384        match target {
385            SadValue::Array(arr) => arr.get_mut(self),
386            _ => None,
387        }
388    }
389}
390
391impl Index for &str {
392    fn index_into(self, target: &SadValue) -> Option<&SadValue> {
393        match target {
394            SadValue::Object(map) => map.get(self),
395            _ => None,
396        }
397    }
398
399    fn index_into_mut(self, target: &mut SadValue) -> Option<&mut SadValue> {
400        match target {
401            SadValue::Object(map) => map.get_mut(self),
402            _ => None,
403        }
404    }
405}
406
407impl Index for String {
408    fn index_into(self, target: &SadValue) -> Option<&SadValue> {
409        self.as_str().index_into(target)
410    }
411
412    fn index_into_mut(self, target: &mut SadValue) -> Option<&mut SadValue> {
413        self.as_str().index_into_mut(target)
414    }
415}
416
417impl Index for &String {
418    fn index_into(self, target: &SadValue) -> Option<&SadValue> {
419        self.as_str().index_into(target)
420    }
421
422    fn index_into_mut(self, target: &mut SadValue) -> Option<&mut SadValue> {
423        self.as_str().index_into_mut(target)
424    }
425}
426
427// Implement equality between SadValue instances
428impl PartialEq for SadValue {
429    fn eq(&self, other: &Self) -> bool {
430        match (self, other) {
431            (SadValue::Bool(a), SadValue::Bool(b)) => a == b,
432            (SadValue::Number(a), SadValue::Number(b)) => a == b,
433            (SadValue::String(a), SadValue::String(b)) => a == b,
434            (SadValue::Array(a), SadValue::Array(b)) => a == b,
435            (SadValue::Object(a), SadValue::Object(b)) => a == b,
436            _ => false,
437        }
438    }
439}
440
441impl Eq for SadValue {}
442
443// Implement Debug trait for better logging and debugging
444impl fmt::Debug for SadValue {
445    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
446        match self {
447            SadValue::Bool(b) => write!(f, "Bool({})", b),
448            SadValue::Number(n) => write!(f, "Number({})", n),
449            SadValue::String(s) => write!(f, "String({})", s),
450            SadValue::Array(a) => f.debug_list().entries(a).finish(),
451            SadValue::Object(o) => f.debug_map().entries(o).finish(),
452        }
453    }
454}
455
456// Add Serialize implementation for SadValue
457impl Serialize for SadValue {
458    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
459    where
460        S: Serializer,
461    {
462        match self {
463            SadValue::Bool(b) => serializer.serialize_bool(*b),
464            SadValue::Number(n) => {
465                if let Some(v) = n.as_i64() {
466                    serializer.serialize_i64(v)
467                } else if let Some(v) = n.as_u64() {
468                    serializer.serialize_u64(v)
469                } else if let Some(v) = n.as_f64() {
470                    serializer.serialize_f64(v)
471                } else {
472                    // Should not happen with the Number implementation
473                    Err(ser::Error::custom("Number cannot be serialized"))
474                }
475            }
476            SadValue::String(s) => serializer.serialize_str(s),
477            SadValue::Array(a) => {
478                let mut seq = serializer.serialize_seq(Some(a.len()))?;
479                for element in a {
480                    seq.serialize_element(element)?;
481                }
482                seq.end()
483            }
484            SadValue::Object(o) => {
485                let mut map = serializer.serialize_map(Some(o.len()))?;
486                for (k, v) in o {
487                    map.serialize_entry(k, v)?;
488                }
489                map.end()
490            }
491        }
492    }
493}
494
495// Define a visitor for SadValue deserialization
496struct SadVisitor;
497
498impl<'de> de::Visitor<'de> for SadVisitor {
499    type Value = SadValue;
500
501    fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
502        formatter.write_str("a valid JSON value")
503    }
504
505    fn visit_bool<E>(self, value: bool) -> Result<Self::Value, E>
506    where
507        E: de::Error,
508    {
509        Ok(SadValue::Bool(value))
510    }
511
512    fn visit_i64<E>(self, value: i64) -> Result<Self::Value, E>
513    where
514        E: de::Error,
515    {
516        Ok(SadValue::Number(serde_json::Number::from(value)))
517    }
518
519    fn visit_u64<E>(self, value: u64) -> Result<Self::Value, E>
520    where
521        E: de::Error,
522    {
523        Ok(SadValue::Number(serde_json::Number::from(value)))
524    }
525
526    fn visit_f64<E>(self, value: f64) -> Result<Self::Value, E>
527    where
528        E: de::Error,
529    {
530        match Number::from_f64(value) {
531            Some(n) => Ok(SadValue::Number(n)),
532            None => Err(E::custom(format!("Invalid float value: {}", value))),
533        }
534    }
535
536    fn visit_str<E>(self, value: &str) -> Result<Self::Value, E>
537    where
538        E: de::Error,
539    {
540        Ok(SadValue::String(value.to_owned()))
541    }
542
543    fn visit_string<E>(self, value: String) -> Result<Self::Value, E>
544    where
545        E: de::Error,
546    {
547        Ok(SadValue::String(value))
548    }
549
550    fn visit_none<E>(self) -> Result<Self::Value, E>
551    where
552        E: de::Error,
553    {
554        // SadValue doesn't have a Null variant,
555        // so we represent null as a special Boolean value
556        // An alternative could be to return a default empty value
557        Ok(SadValue::Bool(false))
558    }
559
560    fn visit_unit<E>(self) -> Result<Self::Value, E>
561    where
562        E: de::Error,
563    {
564        // Same as visit_none for SadValue
565        Ok(SadValue::Bool(false))
566    }
567
568    fn visit_seq<A>(self, mut seq: A) -> Result<Self::Value, A::Error>
569    where
570        A: de::SeqAccess<'de>,
571    {
572        let mut values = Vec::new();
573
574        while let Some(value) = seq.next_element()? {
575            values.push(value);
576        }
577
578        Ok(SadValue::Array(values))
579    }
580
581    fn visit_map<A>(self, mut map: A) -> Result<Self::Value, A::Error>
582    where
583        A: de::MapAccess<'de>,
584    {
585        let mut obj = IndexMap::new();
586
587        while let Some((key, value)) = map.next_entry()? {
588            obj.insert(key, value);
589        }
590
591        Ok(SadValue::Object(obj))
592    }
593}
594
595// Add Deserialize implementation for SadValue
596impl<'de> Deserialize<'de> for SadValue {
597    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
598    where
599        D: Deserializer<'de>,
600    {
601        deserializer.deserialize_any(SadVisitor)
602    }
603}
604
605/// Sets the SAID fields with dummy placeholders of the appropriate length in a Sadd map
606///
607/// # Arguments
608/// * `sad` - The Sadd map to modify
609/// * `saids` - Optional map of label to digest type code overrides
610///
611/// This function sets the digestive fields with proper length placeholders
612/// based on the digest type
613pub fn set_said_placeholders(sad: &mut Sadder, saids: Option<HashMap<&str, String>>) {
614    // Define the default SAIDs mapping
615    let mut _saids: HashMap<&str, String> = HashMap::new();
616
617    // Get the ilk type
618    let ilk = if let Some(SadValue::String(t)) = sad.get("t") {
619        t.as_str()
620    } else {
621        return; // No ilk type, can't set placeholders
622    };
623
624    // Set up the defaults based on the ilk type
625    match ilk {
626        "icp" | "dip" => {
627            _saids.insert("d", mtr_dex::BLAKE3_256.to_string()); // Blake3_256
628
629            if let Some(SadValue::String(i)) = sad.get("i") {
630                if !i.is_empty() {
631                    match BaseMatter::from_qb64(i) {
632                        Ok(mtr) => {
633                            let code = String::from(mtr.code());
634                            if dig_dex::TUPLE.contains(&code.as_str()) {
635                                _saids.insert("i", code);
636                            }
637                        }
638                        Err(_) => {
639                            _saids.insert("i", mtr_dex::BLAKE3_256.to_string());
640                            // Blake3_256
641                        }
642                    }
643                } else {
644                    _saids.insert("i", mtr_dex::BLAKE3_256.to_string()); // Blake3_256
645                }
646            } else {
647                _saids.insert("i", mtr_dex::BLAKE3_256.to_string()); // Blake3_256
648            }
649        }
650        "rot" | "drt" | "vrt" | "rev" | "brv" => {
651            _saids.insert("d", mtr_dex::BLAKE3_256.to_string()); // Blake3_256
652        }
653        "ixn" => {
654            _saids.insert("d", mtr_dex::BLAKE3_256.to_string()); // Blake3_256
655        }
656        "qry" | "rpy" | "pro" | "bar" | "exn" => {
657            _saids.insert("d", mtr_dex::BLAKE3_256.to_string()); // Blake3_256
658        }
659        "vcp" => {
660            _saids.insert("d", mtr_dex::BLAKE3_256.to_string()); // Blake3_256
661            _saids.insert("i", mtr_dex::BLAKE3_256.to_string()); // Blake3_256
662        }
663        "iss" => {
664            _saids.insert("d", mtr_dex::BLAKE3_256.to_string()); // Blake3_256
665        }
666        "bis" => {
667            _saids.insert("d", mtr_dex::BLAKE3_256.to_string()); // Blake3_256
668        }
669        _ => {} // No defaults for unknown types
670    }
671
672    // Dummy character for padding
673    let dummy = "#";
674
675    // Field sizes for different digest types (fs = full size in characters)
676    let sizes = get_sizes();
677
678    // Process each SAID field
679    for (label, code) in _saids.iter() {
680        // Check for override in provided saids
681        let code = if let Some(saids_map) = &saids {
682            saids_map.get(label).unwrap_or(code)
683        } else {
684            code
685        };
686
687        // Check if this is a digestive code that needs padding
688        if let Some(size) = sizes.get(code.as_str()) {
689            if let Some(fs) = size.fs {
690                // Create a properly sized dummy string
691                let dummy_value = dummy.repeat(fs as usize);
692
693                // Set the appropriate field based on the label
694                match *label {
695                    "d" => {
696                        sad.insert("d".to_string(), SadValue::String(dummy_value));
697                    }
698                    "i" => {
699                        sad.insert("i".to_string(), SadValue::String(dummy_value));
700                    }
701                    // Add other SAID fields as needed
702                    _ => {} // Ignore unknown labels
703                }
704            }
705        }
706    }
707}
708
709/// Creates a Sadd with type-specific field defaults based on an existing Sadd
710///
711/// # Arguments
712/// * `ilk` - The event type (Ilk)
713/// * `orig` - The original Sadd object to preserve values from
714///
715/// # Returns
716/// A new Sadd instance with appropriate defaults for the given ilk,
717/// preserving any existing values from the original
718pub fn default_with_type(ilk: Ilk, orig: &Sadder) -> Sadder {
719    let mut sad = Sadder::new();
720
721    // Determine the actual ilk to use
722    let ilk_str = if let Some(SadValue::String(t)) = orig.get("t") {
723        if !t.is_empty() {
724            t.clone()
725        } else {
726            ilk.as_str().to_string()
727        }
728    } else {
729        ilk.as_str().to_string()
730    };
731
732    // Preserve version if already set
733    if let Some(SadValue::String(v)) = orig.get("v") {
734        if !v.is_empty() {
735            sad.insert("v".to_string(), SadValue::String(v.clone()));
736        } else {
737            sad.insert("v".to_string(), SadValue::String("".to_string()));
738        }
739    } else {
740        sad.insert("v".to_string(), SadValue::String("".to_string()));
741    }
742
743    // Set the type field
744    sad.insert("t".to_string(), SadValue::String(ilk_str.clone()));
745
746    // Preserve digest if already set
747    if let Some(SadValue::String(d)) = orig.get("d") {
748        if !d.is_empty() {
749            sad.insert("d".to_string(), SadValue::String(d.clone()));
750        } else {
751            sad.insert("d".to_string(), SadValue::String("".to_string()));
752        }
753    } else {
754        sad.insert("d".to_string(), SadValue::String("".to_string()));
755    }
756
757    // Helper function to get a string value or empty string default
758    let get_string_or_empty = |map: &Sadder, key: &str| -> SadValue {
759        if let Some(SadValue::String(s)) = map.get(key) {
760            SadValue::String(s.clone())
761        } else {
762            SadValue::String("".to_string())
763        }
764    };
765
766    // Helper function to get a string value with default
767    let get_string_or_default = |map: &Sadder, key: &str, default: &str| -> SadValue {
768        if let Some(SadValue::String(s)) = map.get(key) {
769            SadValue::String(s.clone())
770        } else {
771            SadValue::String(default.to_string())
772        }
773    };
774
775    // Thresholds (kt, nt, bt): a hex string, a number or, for kt and nt, a
776    // weighted list (or list of lists) of fractions, kept as given.
777    let get_string_or_number_default = |map: &Sadder, key: &str, default: &str| -> SadValue {
778        if let Some(SadValue::String(s)) = map.get(key) {
779            SadValue::String(s.clone())
780        } else if let Some(SadValue::Number(n)) = map.get(key) {
781            SadValue::Number(n.clone())
782        } else if let Some(SadValue::Array(a)) = map.get(key) {
783            SadValue::Array(a.clone())
784        } else {
785            SadValue::String(default.to_string())
786        }
787    };
788
789    // Helper function to get an array or empty array
790    let get_array_or_empty = |map: &Sadder, key: &str| -> SadValue {
791        if let Some(SadValue::Array(a)) = map.get(key) {
792            SadValue::Array(a.clone())
793        } else {
794            SadValue::Array(vec![])
795        }
796    };
797
798    // Helper function to get an empty object
799    let get_object_or_empty = |map: &Sadder, key: &str| -> SadValue {
800        if let Some(SadValue::Object(o)) = map.get(key) {
801            SadValue::Object(o.clone())
802        } else {
803            SadValue::Object(IndexMap::new())
804        }
805    };
806
807    // Apply type-specific defaults based on ilk
808    match ilk_str.as_str() {
809        "icp" => {
810            sad.insert("i".to_string(), get_string_or_empty(orig, "i"));
811            sad.insert("s".to_string(), get_string_or_default(orig, "s", "0"));
812            sad.insert(
813                "kt".to_string(),
814                get_string_or_number_default(orig, "kt", "0"),
815            );
816            sad.insert("k".to_string(), get_array_or_empty(orig, "k"));
817            sad.insert(
818                "nt".to_string(),
819                get_string_or_number_default(orig, "nt", "0"),
820            );
821            sad.insert("n".to_string(), get_array_or_empty(orig, "n"));
822            sad.insert(
823                "bt".to_string(),
824                get_string_or_number_default(orig, "bt", "0"),
825            );
826            sad.insert("b".to_string(), get_array_or_empty(orig, "b"));
827            sad.insert("c".to_string(), get_array_or_empty(orig, "c"));
828            sad.insert("a".to_string(), get_array_or_empty(orig, "a"));
829        }
830        "rot" => {
831            sad.insert("i".to_string(), get_string_or_empty(orig, "i"));
832            sad.insert("s".to_string(), get_string_or_default(orig, "s", "0"));
833            sad.insert("p".to_string(), get_string_or_empty(orig, "p"));
834            sad.insert(
835                "kt".to_string(),
836                get_string_or_number_default(orig, "kt", "0"),
837            );
838            sad.insert("k".to_string(), get_array_or_empty(orig, "k"));
839            sad.insert(
840                "nt".to_string(),
841                get_string_or_number_default(orig, "nt", "0"),
842            );
843            sad.insert("n".to_string(), get_array_or_empty(orig, "n"));
844            sad.insert(
845                "bt".to_string(),
846                get_string_or_number_default(orig, "bt", "0"),
847            );
848            sad.insert("br".to_string(), get_array_or_empty(orig, "br"));
849            sad.insert("ba".to_string(), get_array_or_empty(orig, "ba"));
850            sad.insert("a".to_string(), get_array_or_empty(orig, "a"));
851        }
852        "ixn" => {
853            sad.insert("i".to_string(), get_string_or_empty(orig, "i"));
854            sad.insert("s".to_string(), get_string_or_default(orig, "s", "0"));
855            sad.insert("p".to_string(), get_string_or_empty(orig, "p"));
856            sad.insert("a".to_string(), get_array_or_empty(orig, "a"));
857        }
858        "dip" => {
859            sad.insert("i".to_string(), get_string_or_empty(orig, "i"));
860            sad.insert("s".to_string(), get_string_or_default(orig, "s", "0"));
861            sad.insert(
862                "kt".to_string(),
863                get_string_or_number_default(orig, "kt", "0"),
864            );
865            sad.insert("k".to_string(), get_array_or_empty(orig, "k"));
866            sad.insert(
867                "nt".to_string(),
868                get_string_or_number_default(orig, "nt", "0"),
869            );
870            sad.insert("n".to_string(), get_array_or_empty(orig, "n"));
871            sad.insert(
872                "bt".to_string(),
873                get_string_or_number_default(orig, "bt", "0"),
874            );
875            sad.insert("b".to_string(), get_array_or_empty(orig, "b"));
876            sad.insert("c".to_string(), get_array_or_empty(orig, "c"));
877            sad.insert("a".to_string(), get_array_or_empty(orig, "a"));
878            sad.insert("di".to_string(), get_string_or_empty(orig, "di"));
879        }
880        "drt" => {
881            sad.insert("i".to_string(), get_string_or_empty(orig, "i"));
882            sad.insert("s".to_string(), get_string_or_default(orig, "s", "0"));
883            sad.insert("p".to_string(), get_string_or_empty(orig, "p"));
884            sad.insert(
885                "kt".to_string(),
886                get_string_or_number_default(orig, "kt", "0"),
887            );
888            sad.insert("k".to_string(), get_array_or_empty(orig, "k"));
889            sad.insert(
890                "nt".to_string(),
891                get_string_or_number_default(orig, "nt", "0"),
892            );
893            sad.insert("n".to_string(), get_array_or_empty(orig, "n"));
894            sad.insert(
895                "bt".to_string(),
896                get_string_or_number_default(orig, "bt", "0"),
897            );
898            sad.insert("br".to_string(), get_array_or_empty(orig, "br"));
899            sad.insert("ba".to_string(), get_array_or_empty(orig, "ba"));
900            sad.insert("a".to_string(), get_array_or_empty(orig, "a"));
901        }
902        "rct" => {
903            sad.insert("i".to_string(), get_string_or_empty(orig, "i"));
904            sad.insert("s".to_string(), get_string_or_default(orig, "s", "0"));
905        }
906        "qry" => {
907            sad.insert("dt".to_string(), get_string_or_empty(orig, "dt"));
908            sad.insert("r".to_string(), get_string_or_empty(orig, "r"));
909            sad.insert("rr".to_string(), get_string_or_empty(orig, "rr"));
910            sad.insert("q".to_string(), get_object_or_empty(orig, "q"));
911        }
912        "rpy" => {
913            sad.insert("dt".to_string(), get_string_or_empty(orig, "dt"));
914            sad.insert("r".to_string(), get_string_or_empty(orig, "r"));
915            sad.insert("a".to_string(), get_object_or_empty(orig, "a"));
916        }
917        "pro" => {
918            sad.insert("dt".to_string(), get_string_or_empty(orig, "dt"));
919            sad.insert("r".to_string(), get_string_or_empty(orig, "r"));
920            sad.insert("rr".to_string(), get_string_or_empty(orig, "rr"));
921            sad.insert("q".to_string(), get_object_or_empty(orig, "q"));
922        }
923        "bar" => {
924            sad.insert("dt".to_string(), get_string_or_empty(orig, "dt"));
925            sad.insert("r".to_string(), get_string_or_empty(orig, "r"));
926            sad.insert("a".to_string(), get_array_or_empty(orig, "a"));
927        }
928        "exn" => {
929            sad.insert("i".to_string(), get_string_or_empty(orig, "i"));
930            sad.insert("rp".to_string(), get_string_or_empty(orig, "rp"));
931            sad.insert("p".to_string(), get_string_or_empty(orig, "p"));
932            sad.insert("dt".to_string(), get_string_or_empty(orig, "dt"));
933            sad.insert("r".to_string(), get_string_or_empty(orig, "r"));
934            sad.insert("q".to_string(), get_object_or_empty(orig, "q"));
935            // exn `a` is a block (keripy exchange: a dict, or a SAID string);
936            // keep whatever was given.
937            sad.insert(
938                "a".to_string(),
939                match orig.get("a") {
940                    Some(v @ (SadValue::Object(_) | SadValue::Array(_) | SadValue::String(_))) => v.clone(),
941                    _ => SadValue::Object(IndexMap::new()),
942                },
943            );
944            sad.insert("e".to_string(), get_object_or_empty(orig, "e"));
945        }
946        "vcp" => {
947            sad.insert("i".to_string(), get_string_or_empty(orig, "i"));
948            sad.insert("ii".to_string(), get_string_or_empty(orig, "ii"));
949            sad.insert("s".to_string(), get_string_or_default(orig, "s", "0"));
950            sad.insert("c".to_string(), get_array_or_empty(orig, "c"));
951            sad.insert("bt".to_string(), get_string_or_default(orig, "bt", "0"));
952            sad.insert("b".to_string(), get_array_or_empty(orig, "b"));
953        }
954        "vrt" => {
955            sad.insert("i".to_string(), get_string_or_empty(orig, "i"));
956            sad.insert("p".to_string(), get_string_or_empty(orig, "p"));
957            sad.insert("s".to_string(), get_string_or_default(orig, "s", "0"));
958            sad.insert(
959                "bt".to_string(),
960                get_string_or_number_default(orig, "bt", "0"),
961            );
962            sad.insert("br".to_string(), get_array_or_empty(orig, "br"));
963            sad.insert("ba".to_string(), get_array_or_empty(orig, "ba"));
964        }
965        "iss" => {
966            sad.insert("i".to_string(), get_string_or_empty(orig, "i"));
967            sad.insert("s".to_string(), get_string_or_default(orig, "s", "0"));
968            sad.insert("ri".to_string(), get_string_or_empty(orig, "ri"));
969            sad.insert("dt".to_string(), get_string_or_empty(orig, "dt"));
970        }
971        "rev" => {
972            sad.insert("i".to_string(), get_string_or_empty(orig, "i"));
973            sad.insert("s".to_string(), get_string_or_default(orig, "s", "0"));
974            sad.insert("ri".to_string(), get_string_or_empty(orig, "ri"));
975            sad.insert("p".to_string(), get_string_or_empty(orig, "p"));
976            sad.insert("dt".to_string(), get_string_or_empty(orig, "dt"));
977        }
978        "bis" => {
979            sad.insert("i".to_string(), get_string_or_empty(orig, "i"));
980            sad.insert("ii".to_string(), get_string_or_empty(orig, "ii"));
981            sad.insert("s".to_string(), get_string_or_default(orig, "s", "0"));
982            sad.insert("r".to_string(), get_object_or_empty(orig, "rules"));
983            sad.insert("dt".to_string(), get_string_or_empty(orig, "dt"));
984        }
985        "brv" => {
986            sad.insert("i".to_string(), get_string_or_empty(orig, "i"));
987            sad.insert("s".to_string(), get_string_or_default(orig, "s", "0"));
988            sad.insert("p".to_string(), get_string_or_empty(orig, "p"));
989            sad.insert("r".to_string(), get_object_or_empty(orig, "rules"));
990            sad.insert("dt".to_string(), get_string_or_empty(orig, "dt"));
991        }
992        // Default case for unknown ilk types
993        _ => {
994            // Keep the base defaults initialized above
995        }
996    }
997
998    sad
999}
1000
1001/// Create a validation schema for the different event types
1002pub fn build_validation_schema() -> HashMap<Ilk, Vec<&'static str>> {
1003    let mut schema = HashMap::new();
1004
1005    // For each ilk, define the required fields (those that must be present)
1006    schema.insert(
1007        Ilk::Icp,
1008        vec![
1009            "v", "t", "d", "i", "s", "kt", "k", "nt", "n", "bt", "b", "c",
1010        ],
1011    );
1012    schema.insert(
1013        Ilk::Rot,
1014        vec![
1015            "v", "t", "d", "i", "s", "p", "kt", "k", "nt", "n", "bt", "br", "ba",
1016        ],
1017    );
1018    schema.insert(Ilk::Ixn, vec!["v", "t", "d", "i", "s", "p"]);
1019    schema.insert(
1020        Ilk::Dip,
1021        vec![
1022            "v", "t", "d", "i", "s", "kt", "k", "nt", "n", "bt", "b", "c", "di",
1023        ],
1024    );
1025    schema.insert(
1026        Ilk::Drt,
1027        vec![
1028            "v", "t", "d", "i", "s", "p", "kt", "k", "nt", "n", "bt", "br", "ba",
1029        ],
1030    );
1031    schema.insert(Ilk::Rct, vec!["v", "t", "d", "i", "s"]);
1032    schema.insert(Ilk::Qry, vec!["v", "t", "d", "dt", "r", "rr", "q"]);
1033    schema.insert(Ilk::Rpy, vec!["v", "t", "d", "dt", "r", "a"]);
1034    schema.insert(Ilk::Pro, vec!["v", "t", "d", "dt", "r", "rr", "q"]);
1035    schema.insert(Ilk::Bar, vec!["v", "t", "d", "dt", "r", "a"]);
1036    schema.insert(
1037        Ilk::Exn,
1038        vec!["v", "t", "d", "i", "rp", "p", "dt", "r", "q", "a", "e"],
1039    );
1040    schema.insert(
1041        Ilk::Vcp,
1042        vec!["v", "t", "d", "i", "ii", "s", "c", "bt", "b", "n"],
1043    );
1044    schema.insert(
1045        Ilk::Vrt,
1046        vec!["v", "t", "d", "i", "p", "s", "bt", "br", "ba"],
1047    );
1048    schema.insert(Ilk::Iss, vec!["v", "t", "d", "i", "s", "ri", "dt"]);
1049    schema.insert(Ilk::Rev, vec!["v", "t", "d", "i", "s", "ri", "p", "dt"]);
1050    schema.insert(Ilk::Bis, vec!["v", "t", "d", "i", "ii", "s", "ra", "dt"]);
1051    schema.insert(Ilk::Brv, vec!["v", "t", "d", "i", "s", "p", "ra", "dt"]);
1052
1053    schema
1054}
1055
1056/// Validates a Sadd map against the schema requirements
1057///
1058/// # Arguments
1059/// * `sad` - The Sadd map to validate
1060///
1061/// # Returns
1062/// * `Ok(())` if validation passes
1063/// * `Err(KERIError)` with a detailed error message if validation fails
1064pub fn validate(sad: &Sadder) -> Result<(), KERIError> {
1065    // Get the ilk value which determines the schema to use
1066    let ilk_str = match sad.get("t") {
1067        Some(SadValue::String(t)) => t.as_str(),
1068        _ => {
1069            return Err(KERIError::ValidationError(
1070                "Missing or invalid 't' field".to_string(),
1071            ))
1072        }
1073    };
1074
1075    // Try to convert string ilk to Ilk enum
1076    let ilk = match Ilk::from_str(ilk_str) {
1077        Some(ilk) => ilk,
1078        None => {
1079            return Err(KERIError::ValidationError(format!(
1080                "Invalid ilk type: {}",
1081                ilk_str
1082            )))
1083        }
1084    };
1085
1086    // Get the validation schema for this ilk
1087    let schema = build_validation_schema();
1088    let fields = match schema.get(&ilk) {
1089        Some(fields) => fields,
1090        None => {
1091            return Err(KERIError::ValidationError(format!(
1092                "No schema found for ilk: {}",
1093                ilk_str
1094            )))
1095        }
1096    };
1097
1098    // Check that all required fields are present and have appropriate values
1099    for &field in fields {
1100        match field {
1101            "v" => {
1102                // Version is required and must not be empty
1103                if !has_non_empty_string(sad, "v") {
1104                    return Err(KERIError::ValidationError(
1105                        "Missing or empty version field 'v'".to_string(),
1106                    ));
1107                }
1108            }
1109            "t" => {
1110                // Type is already validated above
1111            }
1112            "d" => {
1113                // Digest is required and must not be empty
1114                if !has_non_empty_string(sad, "d") {
1115                    return Err(KERIError::ValidationError(
1116                        "Missing or empty digest field 'd'".to_string(),
1117                    ));
1118                }
1119            }
1120            "i" => {
1121                // Identifier is required for most events
1122                if !has_non_empty_string(sad, "i") {
1123                    return Err(KERIError::ValidationError(
1124                        "Missing or empty identifier field 'i'".to_string(),
1125                    ));
1126                }
1127            }
1128            "s" => {
1129                // Sequence number is required for key events
1130                if !has_field(sad, "s") {
1131                    return Err(KERIError::ValidationError(
1132                        "Missing sequence number field 's'".to_string(),
1133                    ));
1134                }
1135
1136                // Validate as number string or parse as integer
1137                if let Some(SadValue::String(s)) = sad.get("s") {
1138                    if s.parse::<u64>().is_err() {
1139                        return Err(KERIError::ValidationError(format!(
1140                            "Invalid sequence number '{}': must be a non-negative integer",
1141                            s
1142                        )));
1143                    }
1144                } else {
1145                    return Err(KERIError::ValidationError(
1146                        "Sequence number 's' must be a string value".to_string(),
1147                    ));
1148                }
1149            }
1150            "p" => {
1151                // Prior event digest is required for rotation and interaction events
1152                if matches!(
1153                    ilk,
1154                    Ilk::Rot | Ilk::Ixn | Ilk::Drt | Ilk::Vrt | Ilk::Rev | Ilk::Brv
1155                ) && !has_non_empty_string(sad, "p")
1156                {
1157                    return Err(KERIError::ValidationError(
1158                        "Missing or empty prior digest field 'p'".to_string(),
1159                    ));
1160                }
1161            }
1162            "kt" => {
1163                // Key threshold is required for inception and rotation events
1164                if matches!(ilk, Ilk::Icp | Ilk::Rot | Ilk::Dip | Ilk::Drt) && !has_field(sad, "kt")
1165                {
1166                    return Err(KERIError::ValidationError(
1167                        "Missing key threshold field 'kt'".to_string(),
1168                    ));
1169                }
1170
1171                // Validate as threshold string or parse as integer
1172                if let Some(SadValue::String(kt)) = sad.get("kt") {
1173                    if kt.parse::<u64>().is_err() {
1174                        return Err(KERIError::ValidationError(format!(
1175                            "Invalid key threshold '{}': must be a non-negative integer",
1176                            kt
1177                        )));
1178                    }
1179                } else if has_field(sad, "kt") {
1180                    return Err(KERIError::ValidationError(
1181                        "Key threshold 'kt' must be a string value".to_string(),
1182                    ));
1183                }
1184            }
1185            "k" => {
1186                // Keys are required for inception and rotation events
1187                if matches!(ilk, Ilk::Icp | Ilk::Rot | Ilk::Dip | Ilk::Drt) {
1188                    // Must be an array of strings
1189                    if !has_string_array(sad, "k") {
1190                        return Err(KERIError::ValidationError(
1191                            "Missing or invalid keys field 'k': must be an array of strings"
1192                                .to_string(),
1193                        ));
1194                    }
1195
1196                    // Validate each key is a non-empty string
1197                    if let Some(SadValue::Array(keys)) = sad.get("k") {
1198                        for (i, key) in keys.iter().enumerate() {
1199                            if let Some(key_str) = key.as_str() {
1200                                if key_str.is_empty() {
1201                                    return Err(KERIError::ValidationError(format!(
1202                                        "Empty key at index {} in 'k'",
1203                                        i
1204                                    )));
1205                                }
1206                            } else {
1207                                return Err(KERIError::ValidationError(format!(
1208                                    "Non-string key at index {} in 'k'",
1209                                    i
1210                                )));
1211                            }
1212                        }
1213                    }
1214                }
1215            }
1216            "nt" => {
1217                // Next key threshold is required for inception and rotation events
1218                if matches!(ilk, Ilk::Icp | Ilk::Rot | Ilk::Dip | Ilk::Drt) && !has_field(sad, "nt")
1219                {
1220                    return Err(KERIError::ValidationError(
1221                        "Missing next key threshold field 'nt'".to_string(),
1222                    ));
1223                }
1224
1225                // Validate as threshold string or parse as integer
1226                if let Some(SadValue::String(nt)) = sad.get("nt") {
1227                    if nt.parse::<u64>().is_err() {
1228                        return Err(KERIError::ValidationError(format!(
1229                            "Invalid next key threshold '{}': must be a non-negative integer",
1230                            nt
1231                        )));
1232                    }
1233                } else if has_field(sad, "nt") {
1234                    return Err(KERIError::ValidationError(
1235                        "Next key threshold 'nt' must be a string value".to_string(),
1236                    ));
1237                }
1238            }
1239            "n" => {
1240                // Next keys are required for inception and rotation events
1241                if matches!(ilk, Ilk::Icp | Ilk::Rot | Ilk::Dip | Ilk::Drt) {
1242                    // Must be an array of strings
1243                    if !has_string_array(sad, "n") {
1244                        return Err(KERIError::ValidationError(
1245                            "Missing or invalid next keys field 'n': must be an array of strings"
1246                                .to_string(),
1247                        ));
1248                    }
1249
1250                    // Validate each key is a non-empty string
1251                    if let Some(SadValue::Array(keys)) = sad.get("n") {
1252                        for (i, key) in keys.iter().enumerate() {
1253                            if let Some(key_str) = key.as_str() {
1254                                if key_str.is_empty() {
1255                                    return Err(KERIError::ValidationError(format!(
1256                                        "Empty next key at index {} in 'n'",
1257                                        i
1258                                    )));
1259                                }
1260                            } else {
1261                                return Err(KERIError::ValidationError(format!(
1262                                    "Non-string next key at index {} in 'n'",
1263                                    i
1264                                )));
1265                            }
1266                        }
1267                    }
1268                }
1269            }
1270            "bt" => {
1271                // Backer threshold is required for inception and rotation events with backers
1272                if matches!(ilk, Ilk::Icp | Ilk::Rot | Ilk::Dip | Ilk::Drt)
1273                    && has_field(sad, "b")
1274                    && !has_field(sad, "bt")
1275                {
1276                    return Err(KERIError::ValidationError(
1277                        "Missing backer threshold field 'bt' when backers 'b' are present"
1278                            .to_string(),
1279                    ));
1280                }
1281
1282                // Validate as threshold string or parse as integer if present
1283                if let Some(SadValue::String(bt)) = sad.get("bt") {
1284                    if bt.parse::<u64>().is_err() {
1285                        return Err(KERIError::ValidationError(format!(
1286                            "Invalid backer threshold '{}': must be a non-negative integer",
1287                            bt
1288                        )));
1289                    }
1290                } else if has_field(sad, "bt") {
1291                    return Err(KERIError::ValidationError(
1292                        "Backer threshold 'bt' must be a string value".to_string(),
1293                    ));
1294                }
1295            }
1296            "b" => {
1297                // Backers field must be an array of strings if present
1298                if has_field(sad, "b") && !has_string_array(sad, "b") {
1299                    return Err(KERIError::ValidationError(
1300                        "Invalid backers field 'b': must be an array of strings".to_string(),
1301                    ));
1302                }
1303
1304                // Validate each backer is a non-empty string
1305                if let Some(SadValue::Array(backers)) = sad.get("b") {
1306                    for (i, backer) in backers.iter().enumerate() {
1307                        if let Some(backer_str) = backer.as_str() {
1308                            if backer_str.is_empty() {
1309                                return Err(KERIError::ValidationError(format!(
1310                                    "Empty backer at index {} in 'b'",
1311                                    i
1312                                )));
1313                            }
1314                        } else {
1315                            return Err(KERIError::ValidationError(format!(
1316                                "Non-string backer at index {} in 'b'",
1317                                i
1318                            )));
1319                        }
1320                    }
1321                }
1322            }
1323            "br" => {
1324                // Backer remove field must be an array of strings if present
1325                if has_field(sad, "br") && !has_string_array(sad, "br") {
1326                    return Err(KERIError::ValidationError(
1327                        "Invalid backer removes field 'br': must be an array of strings"
1328                            .to_string(),
1329                    ));
1330                }
1331
1332                // Validate each backer is a non-empty string
1333                if let Some(SadValue::Array(backers)) = sad.get("br") {
1334                    for (i, backer) in backers.iter().enumerate() {
1335                        if let Some(backer_str) = backer.as_str() {
1336                            if backer_str.is_empty() {
1337                                return Err(KERIError::ValidationError(format!(
1338                                    "Empty backer remove at index {} in 'br'",
1339                                    i
1340                                )));
1341                            }
1342                        } else {
1343                            return Err(KERIError::ValidationError(format!(
1344                                "Non-string backer remove at index {} in 'br'",
1345                                i
1346                            )));
1347                        }
1348                    }
1349                }
1350            }
1351            "ba" => {
1352                // Backer add field must be an array if present
1353                if has_field(sad, "ba") && !is_array(sad, "ba") {
1354                    return Err(KERIError::ValidationError(
1355                        "Invalid backer adds field 'ba': must be an array".to_string(),
1356                    ));
1357                }
1358            }
1359            "c" => {
1360                // Configuration traits must be array or object if present
1361                if has_field(sad, "c") && !is_array(sad, "c") && !is_object(sad, "c") {
1362                    return Err(KERIError::ValidationError(
1363                        "Invalid config field 'c': must be an array or object".to_string(),
1364                    ));
1365                }
1366            }
1367            "a" => {
1368                // Anchors must be array or object if present
1369                if has_field(sad, "a") && !is_array(sad, "a") && !is_object(sad, "a") {
1370                    return Err(KERIError::ValidationError(
1371                        "Invalid anchors field 'a': must be an array or object".to_string(),
1372                    ));
1373                }
1374            }
1375            "di" => {
1376                // Delegator identifier is required for delegated events
1377                if matches!(ilk, Ilk::Dip | Ilk::Drt) && !has_non_empty_string(sad, "di") {
1378                    return Err(KERIError::ValidationError(
1379                        "Missing or empty delegator field 'di'".to_string(),
1380                    ));
1381                }
1382            }
1383            "dt" => {
1384                // Date-time is required for certain events
1385                if matches!(ilk, Ilk::Rpy | Ilk::Qry | Ilk::Exn) && !has_non_empty_string(sad, "dt")
1386                {
1387                    return Err(KERIError::ValidationError(
1388                        "Missing or empty date-time field 'dt'".to_string(),
1389                    ));
1390                }
1391            }
1392            "r" => {
1393                // Route is required for query and reply events
1394                if matches!(ilk, Ilk::Qry | Ilk::Rpy) && !has_non_empty_string(sad, "r") {
1395                    return Err(KERIError::ValidationError(
1396                        "Missing or empty route field 'r'".to_string(),
1397                    ));
1398                }
1399            }
1400            "q" => {
1401                // Query or payload must be object if present
1402                if has_field(sad, "q") && !is_object(sad, "q") {
1403                    return Err(KERIError::ValidationError(
1404                        "Invalid query field 'q': must be an object".to_string(),
1405                    ));
1406                }
1407            }
1408            "ri" => {
1409                // Registry identifier required for issuance and revocation events
1410                if matches!(ilk, Ilk::Iss | Ilk::Rev) && !has_non_empty_string(sad, "ri") {
1411                    return Err(KERIError::ValidationError(
1412                        "Missing or empty registry identifier 'ri'".to_string(),
1413                    ));
1414                }
1415            }
1416            "ii" => {
1417                // Issuer identifier required for certain events
1418                if matches!(ilk, Ilk::Bis | Ilk::Vcp) && !has_non_empty_string(sad, "ii") {
1419                    return Err(KERIError::ValidationError(
1420                        "Missing or empty issuer identifier field 'ii'".to_string(),
1421                    ));
1422                }
1423            }
1424            "rules" => {
1425                // Rules must be object if present
1426                if has_field(sad, "rules") && !is_object(sad, "rules") {
1427                    return Err(KERIError::ValidationError(
1428                        "Invalid rules field 'rules': must be an object".to_string(),
1429                    ));
1430                }
1431            }
1432            "e" => {
1433                // Exchange info must be object if present
1434                if has_field(sad, "e") && !is_object(sad, "e") {
1435                    return Err(KERIError::ValidationError(
1436                        "Invalid exchange field 'e': must be an object".to_string(),
1437                    ));
1438                }
1439            }
1440            // Add more fields here as needed
1441            _ => {
1442                // Other fields are not validated
1443            }
1444        }
1445    }
1446
1447    // Add any cross-field validation rules here
1448    if let Some(SadValue::Array(keys)) = sad.get("k") {
1449        // If kt is present, ensure the threshold is not greater than the number of keys
1450        if let Some(SadValue::String(kt)) = sad.get("kt") {
1451            if let Ok(kt_val) = kt.parse::<usize>() {
1452                if kt_val > keys.len() && kt_val != 0 {
1453                    return Err(KERIError::ValidationError(format!(
1454                        "Invalid key threshold '{}': greater than number of keys {}",
1455                        kt,
1456                        keys.len()
1457                    )));
1458                }
1459            }
1460        }
1461    }
1462
1463    if let Some(SadValue::Array(nkeys)) = sad.get("n") {
1464        // If nt is present, ensure the threshold is not greater than the number of next keys
1465        if let Some(SadValue::String(nt)) = sad.get("nt") {
1466            if let Ok(nt_val) = nt.parse::<usize>() {
1467                if nt_val > nkeys.len() && nt_val != 0 {
1468                    return Err(KERIError::ValidationError(format!(
1469                        "Invalid next key threshold '{}': greater than number of next keys {}",
1470                        nt,
1471                        nkeys.len()
1472                    )));
1473                }
1474            }
1475        }
1476    }
1477
1478    // All validations passed
1479    Ok(())
1480}
1481
1482/// Checks if a field exists in the Sadd map
1483fn has_field(sad: &Sadder, field: &str) -> bool {
1484    sad.contains_key(field)
1485}
1486
1487/// Checks if a field exists and is a non-empty string
1488fn has_non_empty_string(sad: &Sadder, field: &str) -> bool {
1489    if let Some(SadValue::String(s)) = sad.get(field) {
1490        !s.is_empty()
1491    } else {
1492        false
1493    }
1494}
1495
1496/// Checks if a field exists and is an array of strings
1497fn has_string_array(sad: &Sadder, field: &str) -> bool {
1498    if let Some(SadValue::Array(arr)) = sad.get(field) {
1499        arr.iter().all(|v| v.as_str().is_some())
1500    } else {
1501        false
1502    }
1503}
1504
1505/// Checks if a field exists and is an array
1506fn is_array(sad: &Sadder, field: &str) -> bool {
1507    if let Some(value) = sad.get(field) {
1508        value.is_array()
1509    } else {
1510        false
1511    }
1512}
1513
1514/// Checks if a field exists and is an object
1515fn is_object(sad: &Sadder, field: &str) -> bool {
1516    if let Some(value) = sad.get(field) {
1517        value.is_object()
1518    } else {
1519        false
1520    }
1521}
1522
1523/// Creates a simpler version of the validate method that returns a string error
1524/// instead of a KERIError
1525pub fn is_valid(sad: &Sadder) -> Result<(), String> {
1526    match validate(sad) {
1527        Ok(()) => Ok(()),
1528        Err(e) => Err(e.to_string()),
1529    }
1530}
1531
1532/// Creates a specific event type from this general structure
1533pub fn ilk(sad: &Sadder) -> Result<Ilk, KERIError> {
1534    let t = match sad.get("t") {
1535        Some(SadValue::String(t)) => t,
1536        _ => {
1537            return Err(KERIError::ValidationError(
1538                "Missing or invalid 't' field".to_string(),
1539            ))
1540        }
1541    };
1542    match t.as_str() {
1543        Ilks::ICP => Ok(Ilk::Icp),
1544        Ilks::ROT => Ok(Ilk::Rot),
1545        Ilks::IXN => Ok(Ilk::Ixn),
1546        Ilks::DIP => Ok(Ilk::Dip),
1547        Ilks::DRT => Ok(Ilk::Drt),
1548        Ilks::RCT => Ok(Ilk::Rct),
1549        Ilks::QRY => Ok(Ilk::Qry),
1550        Ilks::RPY => Ok(Ilk::Rpy),
1551        Ilks::VCP => Ok(Ilk::Vcp),
1552        Ilks::VRT => Ok(Ilk::Vrt),
1553        Ilks::ISS => Ok(Ilk::Iss),
1554        Ilks::REV => Ok(Ilk::Rev),
1555        _ => Err(KERIError::FieldError(String::from("Unknown event type"))),
1556    }
1557}
1558
1559pub fn get_primary_said_label(sad: &Sadder) -> Option<Said> {
1560    match ilk(sad) {
1561        Ok(ilk) => match ilk {
1562            Ilk::Icp => Some(Said::D),
1563            Ilk::Rot => Some(Said::D),
1564            Ilk::Ixn => Some(Said::D),
1565            Ilk::Dip => Some(Said::D),
1566            Ilk::Drt => Some(Said::D),
1567            Ilk::Qry => Some(Said::D),
1568            Ilk::Rpy => Some(Said::D),
1569            Ilk::Pro => Some(Said::D),
1570            Ilk::Bar => Some(Said::D),
1571            Ilk::Exn => Some(Said::D),
1572            Ilk::Vcp => Some(Said::D),
1573            Ilk::Vrt => Some(Said::D),
1574            Ilk::Iss => Some(Said::D),
1575            Ilk::Rev => Some(Said::D),
1576            Ilk::Bis => Some(Said::D),
1577            Ilk::Brv => Some(Said::D),
1578            _ => None,
1579        },
1580        _ => None,
1581    }
1582}