Skip to main content

libkeri/keri/core/serdering/
mod.rs

1pub mod sad;
2
3pub use sad::SadValue;
4pub use sad::Sadder;
5
6use crate::cesr::counting::gen_dex;
7use crate::cesr::diger::Diger;
8use crate::cesr::number::Number;
9use crate::cesr::tholder::{Tholder, TholderSith};
10use crate::cesr::verfer::Verfer;
11use crate::cesr::{dig_dex, mtr_dex, BaseMatter, Versionage, VRSN_1_0};
12use crate::keri::core::serdering::sad::{
13    default_with_type, get_primary_said_label, set_said_placeholders,
14};
15use crate::keri::{deversify, smell, versify, Ilk, KERIError, Kinds, Protocolage, Said, Smellage};
16use crate::Matter;
17use base64::prelude::BASE64_STANDARD;
18use base64::Engine;
19use indexmap::IndexMap;
20use serde_json::{self};
21use std::any::Any;
22use std::collections::HashMap;
23use tracing::error;
24
25/// Get the span length for a given version and serialization format
26fn get_version_span(vrsn: &Versionage, kind: &Kinds) -> Result<usize, KERIError> {
27    // Define version spans based on serialization kind
28    match (vrsn, kind) {
29        // KERI protocol version spans
30        (Versionage { major: 1, minor: 0 }, Kinds::Json) => Ok(17),
31        (Versionage { major: 1, minor: 0 }, Kinds::Cbor) => Ok(17),
32        (Versionage { major: 1, minor: 0 }, Kinds::Mgpk) => Ok(17),
33        (Versionage { major: 2, minor: 0 }, Kinds::Json) => Ok(16),
34        (Versionage { major: 2, minor: 0 }, Kinds::Cbor) => Ok(16),
35        (Versionage { major: 2, minor: 0 }, Kinds::Mgpk) => Ok(16),
36
37        // ACDC protocol version spans
38        // (Versionage { major: 1, minor: 0 }, _) if vrsn.kind == "ACDC" => Ok(17),
39        // Add other version spans as needed
40
41        // Unknown version/kind combination
42        _ => Err(KERIError::VersionError(
43            "Unsupported version and kind combination".to_string(),
44        )),
45    }
46}
47
48/// Base implementation of the Serder trait for serializable/deserializable entities
49#[derive(Debug, Clone)]
50pub struct BaseSerder {
51    /// Serialized message as bytes
52    raw: Vec<u8>,
53    /// Serializable attribute dictionary (key event dict)
54    pub sad: Sadder,
55    /// Protocol identifier type (e.g., 'KERI' or 'ACDC')
56    proto: String,
57    /// Event version information
58    vrsn: Versionage,
59    /// Serialization kind (json, cbor, msgpack, binary)
60    kind: Kinds,
61    /// Number of bytes in serialized event
62    size: usize,
63    /// qb64 self-addressing identifier given by appropriate saidive field
64    said: Option<String>,
65    /// CESR genus code for this Serder
66    genus: String,
67    /// CESR genus code table version for this Serder
68    gvrsn: Versionage,
69}
70
71impl Default for BaseSerder {
72    fn default() -> Self {
73        BaseSerder {
74            raw: Vec::new(),
75            sad: Sadder::default(),
76            proto: String::new(),
77            vrsn: Versionage { major: 1, minor: 0 },
78            kind: Kinds::Json,
79            size: 0,
80            said: None,
81            genus: String::new(),
82            gvrsn: Versionage { major: 1, minor: 0 },
83        }
84    }
85}
86
87impl BaseSerder {
88    pub fn from_init(
89        raw: Option<&[u8]>,
90        sad: Option<&Sadder>,
91        makify: Option<bool>,
92        smellage: Option<Smellage>,
93        proto: Option<String>,
94        vrsn: Option<Versionage>,
95        kind: Option<Kinds>,
96        ilk: Option<Ilk>,
97        saids: Option<HashMap<&str, String>>,
98    ) -> Result<Self, KERIError> {
99        let mfy = makify.unwrap_or(true);
100
101        match raw {
102            Some(raw) => Self::from_raw(raw, smellage),
103            None => {
104                if mfy {
105                    let mut serder = Self::default();
106                    serder.makify(
107                        sad.unwrap_or(&Sadder::default()),
108                        proto,
109                        vrsn,
110                        kind,
111                        ilk,
112                        saids,
113                    )?;
114                    Ok(serder)
115                } else {
116                    match sad {
117                        Some(sad) => Self::from_sad(sad),
118                        None => Err(KERIError::MissingRequiredField(
119                            "raw".to_string(),
120                            "Raw or Sad required".to_string(),
121                        ))?,
122                    }
123                }
124            }
125        }
126    }
127
128    pub fn from_sad(sad: &Sadder) -> Result<Self, KERIError> {
129        let genus = String::from(gen_dex::KERI);
130        let ver = sad.get("v").unwrap().as_str().unwrap();
131
132        let smell = deversify(ver.as_bytes())?;
133        let (proto, vrsn, kind, size, gvrsn) =
134            (smell.proto, smell.vrsn, smell.kind, smell.size, smell.gvrsn);
135        // Verify version field exists
136
137        let raw = BaseSerder::dumps(sad, &Kinds::from(kind.as_str())?)?;
138
139        let mut serder = BaseSerder {
140            raw: raw[..size].to_vec(),
141            sad: sad.clone(),
142            proto,
143            vrsn,
144            kind: Kinds::from(&kind)?,
145            size,
146            said: None,
147            genus,
148            gvrsn: gvrsn
149                .ok_or_else(|| KERIError::FieldError("Missing required gvrsn value".to_string()))?,
150        };
151
152        // Get the primary said field label
153        let label = match get_primary_said_label(sad) {
154            Some(label) => label,
155            None => {
156                // Set said to None (null in Python)
157                serder.said = None;
158                return Ok(serder);
159            }
160        };
161
162        // Check if the primary said field exists in the sad
163        // Check if the primary said field exists in the sad
164        let sad = &serder.sad;
165        match label {
166            Said::D => {
167                serder.said = Some(sad["d"].as_str().unwrap().to_string());
168            }
169            _ => {
170                return Err(KERIError::FieldError(format!(
171                    "Missing primary said field in {:?}.",
172                    sad
173                )));
174            }
175        }
176
177        // Note: In Rust, we don't modify the passed-in raw buffer directly
178        // The strip functionality would be implemented elsewhere if needed
179
180        // Verify fields including the saids provided in raw
181        match serder.verify() {
182            Ok(_) => Ok(serder),
183            Err(err) => {
184                // Log the error
185                error!("Invalid raw for Serder {}\n{}", serder.pretty(None), err);
186
187                Err(KERIError::ValidationError(format!(
188                    "Invalid raw for Serder = {:?}. {}",
189                    serder.sad, err
190                )))
191            }
192        }
193    }
194
195    /// Prepares a Sadder by padding the version field and then calculating the correct version string
196    /// This mirrors the Python makify method's versification logic
197    ///
198    /// # Arguments
199    /// * `sad` - The Sadder to prepare
200    /// * `kind` - The serialization format kind
201    /// * `proto` - The protocol string
202    /// * `vrsn` - The version information
203    ///
204    /// # Returns
205    /// The updated Sadder with proper version string
206    pub fn prepare_version(
207        &self,
208        sad: &mut Sadder,
209        kind: Kinds,
210        proto: String,
211        vrsn: Versionage,
212    ) -> Result<(), KERIError> {
213        // Only process for these serialization formats
214        if matches!(kind, Kinds::Json | Kinds::Cbor | Kinds::Mgpk) {
215            // Dummy character for padding
216            let dummy = "#";
217
218            // Get the span length for this version
219            let span = get_version_span(&vrsn, &kind)?;
220
221            // Pad the version field with dummy characters to ensure proper span
222            sad.insert("v".to_string(), SadValue::String(dummy.repeat(span)));
223
224            // Serialize to calculate the size
225            let raw = Self::dumps(&sad, &kind)?;
226            let size = raw.len();
227
228            // Generate the correct version string with the calculated size
229            let vs = versify(
230                proto.as_str(),
231                &vrsn,
232                kind.to_string().as_str(),
233                size as u64,
234            )?;
235
236            // Update the version string in the Sadder
237            sad.insert("v".to_string(), SadValue::String(vs));
238        }
239
240        Ok(())
241    }
242
243    /// Computes the self-addressing identifier (SAID) for the given raw data and genus.
244    ///
245    /// # Arguments
246    ///
247    /// * `raw` - Byte slice of the serialized message.
248    /// * `genus` - The CESR genus code associated with the event.
249    ///
250    /// # Returns
251    ///
252    /// * `Result<String, KERIError>` - The computed SAID as a base64-encoded string on success,
253    ///                                   or a KERIError on failure.
254    fn compute_said(raw: &[u8], genus: &str) -> Result<String, KERIError> {
255        // Use the appropriate hashing algorithm based on the genus code.
256        let hash = match genus {
257            "BLAKE3" => blake3::hash(raw).to_hex().to_string(),
258            "SHA256" => {
259                use sha2::{Digest, Sha256};
260                let mut hasher = Sha256::new();
261                hasher.update(raw);
262                BASE64_STANDARD.encode(hasher.finalize())
263            }
264            "SHA3_256" => {
265                use sha3::{Digest, Sha3_256};
266                let mut hasher = Sha3_256::new();
267                hasher.update(raw);
268                BASE64_STANDARD.encode(hasher.finalize())
269            }
270            _ => {
271                return Err(KERIError::FieldError(format!(
272                    "Unsupported genus code for SAID computation: {}",
273                    genus
274                )));
275            }
276        };
277
278        Ok(hash)
279    }
280
281    pub fn compare_said(&self, said: &str) -> bool {
282        match &self.said {
283            Some(ss) => ss == said,
284            None => false,
285        }
286    }
287
288    // Helper method to get the primary said field label
289    fn get_primary_said_label(&self) -> Option<Said> {
290        get_primary_said_label(&self.sad)
291    }
292
293    /// Deserializes raw bytes into a data structure based on the specified kind
294    ///
295    /// # Arguments
296    ///
297    /// * `raw` - Raw bytes to deserialize
298    /// * `size` - Number of bytes to consume for deserialization (if None, uses all bytes)
299    /// * `kind` - Serialization format (JSON, MGPK, CBOR)
300    ///
301    /// # Returns
302    ///
303    /// A Result containing either the deserialized data or a KERIError
304    ///
305    /// # Notes
306    ///
307    /// JSON deserialization uses UTF-8 string conversion, while CBOR and MGPK operate directly on bytes
308    pub fn loads(raw: &[u8], size: Option<usize>, kind: Kinds) -> Result<Sadder, KERIError> {
309        // Determine how many bytes to use
310        let limit = size.unwrap_or(raw.len());
311        let data = &raw[..std::cmp::min(limit, raw.len())];
312
313        match kind {
314            Kinds::Json => {
315                // Convert bytes to UTF-8 string for JSON
316                match std::str::from_utf8(data) {
317                    Ok(text) => {
318                        let sadder = serde_json::from_str(text)
319                            .map_err(|e| KERIError::JsonError(e.to_string()))?;
320                        Ok(sadder)
321                    }
322                    Err(e) => Err(KERIError::JsonError(format!(
323                        "Invalid UTF-8 sequence: {}",
324                        e
325                    ))),
326                }
327            }
328            Kinds::Mgpk => {
329                let sadder =
330                    rmp_serde::from_slice(data).map_err(|e| KERIError::MgpkError(e.to_string()))?;
331                Ok(sadder)
332            }
333
334            Kinds::Cbor => {
335                let sadder = serde_cbor::from_slice(data)
336                    .map_err(|e| KERIError::CborError(e.to_string()))?;
337                Ok(sadder)
338            }
339            Kinds::Cesr => Err(KERIError::MgpkError(
340                "CESR deserialization not implemented".to_string(),
341            )),
342        }
343    }
344
345    ///
346    /// # Parameters:
347    /// * `sad`: Optional data to serialize. If None, uses default empty data
348    /// * `kind`: Serialization format (Json, Cbor, MsgPack)
349    /// * `proto`: Optional protocol type
350    /// * `vrsn`: Optional protocol version
351    ///
352    /// # Returns:
353    /// Serialized bytes of the data
354    ///
355    /// # Errors:
356    /// Returns a KERIError if serialization fails
357    pub fn dumps(sad: &Sadder, kind: &Kinds) -> Result<Vec<u8>, KERIError> {
358        match kind {
359            Kinds::Json => match serde_json::to_string(sad) {
360                Ok(json_str) => Ok(json_str.into_bytes()),
361                Err(e) => Err(KERIError::DeserializeError(e.to_string())),
362            },
363            Kinds::Mgpk => match rmp_serde::to_vec(sad) {
364                Ok(mgpk_bytes) => Ok(mgpk_bytes),
365                Err(e) => Err(KERIError::DeserializeError(e.to_string())),
366            },
367            Kinds::Cbor => match serde_cbor::to_vec(sad) {
368                Ok(cbor_bytes) => Ok(cbor_bytes),
369                Err(e) => Err(KERIError::DeserializeError(e.to_string())),
370            },
371            Kinds::Cesr => Err(KERIError::DeserializeError(
372                "CESR serialization not enabled".to_string(),
373            )),
374        }
375    }
376
377    pub fn verify(&self) -> Result<(), KERIError> {
378        // Call the potentially overridden _verify method
379        self._verify()
380    }
381
382    /// Makify given sad dict makes the versions string and computes the said
383    /// field values and sets associated properties:
384    /// raw, sad, proto, version, kind, size
385    ///
386    /// Override for protocol and ilk specific saidification behavior. Especially
387    /// for inceptive ilks that have more than one said field like a said derived
388    /// identifier prefix.
389    ///
390    /// Default prioritization:
391    ///    Use method parameter if not None
392    ///    Else use provided version string if valid
393    ///    Otherwise use class attribute
394    ///
395    /// # Parameters
396    /// * `sad` - Serializable saidified field map of message
397    /// * `proto` - Optional desired protocol type str value of Protocols.
398    ///             If None then its extracted from sad or uses default .Proto
399    /// * `vrsn` - Optional instance desired protocol version.
400    ///            If None then its extracted from sad or uses default .Vrsn
401    /// * `kind` - Optional serialization kind string value of Serials.
402    ///            supported kinds are 'json', 'cbor', 'msgpack', 'binary'.
403    ///            If None then its extracted from sad or uses default .Kind
404    /// * `ilk` - Optional desired ilk packet type str value of Ilks.
405    ///           If None then its extracted from sad or uses default .Ilk
406    /// * `saids` - Optional dict keyed by label of codes for saidive fields to
407    ///             override defaults given in .Fields for a given ilk.
408    ///             If None then use defaults
409    pub fn makify(
410        &mut self,
411        sad: &Sadder,
412        proto: Option<String>,
413        vrsn: Option<Versionage>,
414        kind: Option<Kinds>,
415        ilk: Option<Ilk>,
416        saids: Option<HashMap<&str, String>>,
417    ) -> Result<(), KERIError> {
418        // Determine protocol to use
419        let mut sproto = None;
420        let mut svrsn = None;
421        let mut skind = None;
422        match sad.get("v") {
423            Some(SadValue::String(v)) if !v.is_empty() => {
424                let smellage = deversify(v.as_str())?;
425                sproto = Some(smellage.proto);
426                svrsn = Some(smellage.vrsn);
427                skind = Some(Kinds::from(&smellage.kind)?);
428            }
429            _ => {}
430        }
431        let proto = proto
432            .or_else(|| {
433                sproto.or_else(|| Some("KERI".to_string())) // Extract from sad (this would need implementation details)
434            })
435            .unwrap_or_else(|| self.proto.clone());
436
437        // Determine version to use
438        let vrsn = vrsn
439            .or_else(|| {
440                svrsn.or_else(|| {
441                    // Extract from sad (this would need implementation details)
442                    Some(VRSN_1_0)
443                })
444            })
445            .unwrap_or_else(|| self.vrsn.clone());
446
447        // Determine kind to use
448        let kind = kind
449            .or_else(|| {
450                skind.or_else(|| {
451                    // Extract from sad (this would need implementation details)
452                    Some(Kinds::Json)
453                })
454            })
455            .unwrap_or_else(|| self.kind.clone());
456
457        let ilk = ilk.unwrap_or_else(|| Ilk::Icp);
458
459        // Update sad with the determined values
460        let mut sad = default_with_type(ilk, sad);
461
462        // Create a map of SAID fields that need to be computed
463        let mut said_fields: HashMap<&str, String> = HashMap::new();
464        match sad["t"].as_str().unwrap() {
465            "icp" | "dip" => {
466                said_fields.insert("d", mtr_dex::BLAKE3_256.to_string()); // Blake3_256
467                match sad.get("i") {
468                    Some(SadValue::String(i)) if !i.is_empty() => {
469                        match BaseMatter::from_qb64(&i.clone()) {
470                            Ok(mtr) => {
471                                let code = String::from(mtr.code().clone());
472                                if dig_dex::TUPLE.contains(&code.as_str()) {
473                                    said_fields.insert("i", code);
474                                }
475                            }
476                            Err(_) => {
477                                said_fields.insert("i", mtr_dex::BLAKE3_256.to_string());
478                                // Blake3_256
479                            }
480                        }
481                    }
482                    _ => {
483                        said_fields.insert("i", mtr_dex::BLAKE3_256.to_string());
484                        // Blake3_256
485                    }
486                }
487            }
488            "rot" | "drt" | "vrt" | "rev" | "brv" => {
489                said_fields.insert("d", mtr_dex::BLAKE3_256.to_string()); // Blake3_256
490            }
491            "ixn" => {
492                said_fields.insert("d", mtr_dex::BLAKE3_256.to_string()); // Blake3_256
493            }
494            "qry" | "rpy" | "pro" | "bar" | "exn" => {
495                said_fields.insert("d", mtr_dex::BLAKE3_256.to_string()); // Blake3_256
496            }
497            "vcp" => {
498                said_fields.insert("d", mtr_dex::BLAKE3_256.to_string()); // Blake3_256
499                said_fields.insert("i", mtr_dex::BLAKE3_256.to_string()); // Blake3_256
500            }
501            "iss" => {
502                said_fields.insert("d", mtr_dex::BLAKE3_256.to_string()); // Blake3_256
503            }
504            "bis" => {
505                said_fields.insert("d", mtr_dex::BLAKE3_256.to_string()); // Blake3_256
506            }
507            _ => {} // No digestive fields for other types
508        }
509
510        // Override with provided SAIDs if any
511        if let Some(saids) = saids.clone() {
512            for (label, code) in saids {
513                said_fields.insert(label, code.to_string());
514            }
515        }
516
517        // Handle saidive fields
518        set_said_placeholders(&mut sad, saids);
519        self.prepare_version(&mut sad, kind.clone(), proto.clone(), vrsn.clone())?;
520        // Serialize sad to raw based on kind
521        let raw = Self::dumps(&sad, &kind)?;
522
523        // Compute the digest for each SAID field
524        for (label, code) in said_fields {
525            // Check if the code is digestive (in DigDex)
526            if dig_dex::TUPLE.contains(&code.as_str()) {
527                let diger = Diger::from_ser_and_code(&raw, code.as_str())
528                    .map_err(|e| KERIError::from(e))?;
529                let qb64 = diger.qb64();
530
531                // Update the field based on the label
532                sad.insert(label.to_string(), SadValue::String(qb64));
533            }
534        }
535
536        // Serialize the final data with updated SAIDs
537        let raw = Self::dumps(&sad, &kind)?;
538
539        // Compute SAID (Self-Addressing IDentifier) for the sad
540        let said = match sad.get("d") {
541            Some(SadValue::String(d)) if !d.is_empty() => Some(d.to_string()),
542            _ => match sad.get("i") {
543                Some(SadValue::String(i)) if !i.is_empty() => Some(i.to_string()),
544                _ => None,
545            },
546        };
547
548        // Update object properties
549        self.raw = raw;
550        self.sad = sad.clone();
551        self.proto = proto;
552        self.vrsn = vrsn;
553        self.kind = kind;
554        self.said = said;
555        // For CESR kind, just compute the size of the whole message, not sure why this matters?
556        let size = if kind == Kinds::Cesr {
557            self.raw.len()
558        } else {
559            self.raw.len()
560        };
561
562        self.size = size;
563
564        Ok(())
565    }
566}
567
568/// Trait representing a serializable/deserializable entity with SAID (Self-Addressing IDentifier)
569pub trait Serder: Any + Send + Sync {
570    /// Returns a pretty-printed JSON representation of the serialized data
571    ///
572    /// # Parameters
573    /// * `size` - Optional size limit for the output. None means no limit.
574    ///   This protects against syslog errors when exceeding UDP MTU.
575    ///   IPv4 MTU is 576, IPv6 MTU is 1280, and most broadband routers have 1454 MTU.
576    fn pretty(&self, size: Option<usize>) -> String;
577
578    /// Returns the raw bytes representation
579    fn raw(&self) -> &[u8];
580
581    /// Returns a copy of the serializable attribute dictionary (saidified data)
582    fn sad(&self) -> Sadder;
583
584    /// Returns the CESR genus code for this Serder
585    fn genus(&self) -> &str;
586
587    /// Returns the CESR genus code table version for this Serder
588    fn gvrsn(&self) -> &Versionage;
589
590    /// Returns the serialization kind (value of Serials/Serialage)
591    fn kind(&self) -> &Kinds;
592
593    /// Returns the protocol identifier type (e.g., 'KERI' or 'ACDC')
594    fn proto(&self) -> &str;
595
596    /// Alias for proto() - returns the protocol identifier type
597    fn protocol(&self) -> &str {
598        self.proto()
599    }
600
601    /// Returns the protocol version for this Serder
602    fn vrsn(&self) -> &Versionage;
603
604    /// Alias for vrsn() - returns the protocol version
605    fn version(&self) -> &Versionage {
606        self.vrsn()
607    }
608
609    /// Returns the number of bytes in the raw representation
610    fn size(&self) -> usize;
611
612    /// Returns the qb64 SAID (Self-Addressing IDentifier)
613    fn said(&self) -> Option<&str>;
614
615    /// Returns the qb64b (bytes) representation of the SAID
616    fn saidb(&self) -> Option<Vec<u8>> {
617        self.said().map(|s| s.as_bytes().to_vec())
618    }
619
620    /// Returns the packet type given by sad['t'] if any
621    fn ilk(&self) -> Option<&str>;
622
623    fn as_any(&self) -> &dyn Any;
624
625    fn clone_box(&self) -> Box<dyn Serder>;
626}
627
628/// Trait that must be implemented by types that can be parsed
629pub trait Rawifiable: Sized {
630    fn from_raw(raw: &[u8], smell: Option<Smellage>) -> Result<Self, KERIError>;
631}
632
633impl Serder for BaseSerder {
634    fn pretty(&self, size: Option<usize>) -> String {
635        let json_str = serde_json::to_string_pretty(&self.sad)
636            .unwrap_or_else(|_| "Error serializing to JSON".to_string());
637
638        if let Some(limit) = size {
639            if json_str.len() > limit {
640                return json_str[..limit].to_string();
641            }
642        }
643
644        json_str
645    }
646
647    fn raw(&self) -> &[u8] {
648        &self.raw
649    }
650
651    fn sad(&self) -> Sadder {
652        self.sad.clone() // Return a copy
653    }
654
655    fn genus(&self) -> &str {
656        &self.genus
657    }
658
659    fn gvrsn(&self) -> &Versionage {
660        &self.gvrsn
661    }
662
663    fn kind(&self) -> &Kinds {
664        &self.kind
665    }
666
667    fn proto(&self) -> &str {
668        &self.proto
669    }
670
671    fn vrsn(&self) -> &Versionage {
672        &self.vrsn
673    }
674
675    fn size(&self) -> usize {
676        self.size
677    }
678
679    fn said(&self) -> Option<&str> {
680        self.said.as_deref()
681    }
682
683    fn ilk(&self) -> Option<&str> {
684        Some(self.sad.get("t").unwrap().as_str().unwrap())
685    }
686
687    fn as_any(&self) -> &dyn Any {
688        self
689    }
690
691    fn clone_box(&self) -> Box<dyn Serder> {
692        Box::new(self.clone())
693    }
694}
695
696impl Rawifiable for BaseSerder {
697    /// Returns an error if verification fails or if required fields are missing
698    fn from_raw(raw: &[u8], smellage: Option<Smellage>) -> Result<Self, KERIError> {
699        // Create a new BaseSerder instance
700        // Inhale the raw data (equivalent to _inhale in Python)
701        // Parse smellage or smell the raw data
702        let genus = gen_dex::KERI.to_string();
703        let (proto, vrsn, kind, size, gvrsn) = match smellage {
704            Some(smell) => {
705                // Use provided smellage
706                (smell.proto, smell.vrsn, smell.kind, smell.size, smell.gvrsn)
707            }
708            None => {
709                // Smell the raw data
710                let smell = smell(raw)?;
711                (smell.proto, smell.vrsn, smell.kind, smell.size, smell.gvrsn)
712            }
713        };
714
715        // Deserialize data based on kind
716        let sad = BaseSerder::loads(raw, Some(size), Kinds::from(&kind)?)?;
717        let said_label = get_primary_said_label(&sad);
718
719        // Verify version field exists
720        let mut serder = BaseSerder {
721            raw: raw[..size].to_vec(),
722            sad,
723            proto,
724            vrsn,
725            kind: Kinds::from(&kind)?,
726            size,
727            said: None,
728            genus,
729            gvrsn: gvrsn.unwrap(),
730        };
731
732        // Get the primary said field label
733
734        let label = match said_label {
735            Some(label) => label,
736            None => {
737                // Set said to None (null in Python)
738                serder.said = None;
739                return Ok(serder);
740            }
741        };
742
743        // Check if the primary said field exists in the sad
744        let sad = &serder.sad;
745        match label {
746            Said::D => {
747                serder.said = Some(sad.get("d").unwrap().as_str().unwrap().to_string());
748            }
749            _ => {
750                return Err(KERIError::FieldError(format!(
751                    "Missing primary said field in {:?}.",
752                    sad
753                )));
754            }
755        }
756
757        // Note: In Rust, we don't modify the passed-in raw buffer directly
758        // The strip functionality would be implemented elsewhere if needed
759
760        // Verify fields including the saids provided in raw
761        match serder.verify() {
762            Ok(_) => Ok(serder),
763            Err(err) => {
764                // Log the error
765                error!("Invalid raw for Serder {}\n{}", serder.pretty(None), err);
766
767                Err(KERIError::ValidationError(format!(
768                    "Invalid raw for Serder = {:?}. {}",
769                    serder.sad, err
770                )))
771            }
772        }
773    }
774}
775
776// Define a trait for verification behavior
777pub trait Verifiable {
778    // Default implementation that can be overridden
779    fn _verify(&self) -> Result<(), KERIError> {
780        // Default behavior
781        Ok(())
782    }
783}
784
785// Implement the trait for BaseSerder
786impl Verifiable for BaseSerder {
787    // You can override the default implementation if needed
788    fn _verify(&self) -> Result<(), KERIError> {
789        // Verify that the required SAID field is present. This is a critical field for integrity checks.
790        if let Some(said) = &self.said {
791            // Compute the expected SAID based on the self-addressing hash of the serialized message.
792            // Create a map of SAID fields that need to be computed
793            let mut sad = self.sad.clone();
794            set_said_placeholders(&mut sad, None);
795            let raw = Self::dumps(&sad, &self.kind)?;
796
797            let dcoder = Diger::from_qb64(said);
798            let diger = Diger::from_ser_and_code(&raw, dcoder.unwrap().code())
799                .map_err(|e| KERIError::from(e))?;
800            let qb64 = diger.qb64();
801            if said != &qb64 {
802                return Err(KERIError::ValidationError(format!(
803                    "SAID mismatch: expected {}, found {}",
804                    qb64, said
805                )));
806            }
807        } else {
808            // If the SAID is None, verification fails since it's a required field.
809            return Err(KERIError::FieldError("Missing SAID field.".to_string()));
810        }
811
812        // Additional checks can be added here for other required fields or properties.
813
814        Ok(())
815    }
816}
817
818/// KERI-specific implementation of the Serder
819#[derive(Debug, Clone)]
820pub struct SerderKERI {
821    pub base: BaseSerder,
822}
823
824/// Implement the Serder trait for SerderKERI
825impl Serder for SerderKERI {
826    fn pretty(&self, size: Option<usize>) -> String {
827        self.base.pretty(size)
828    }
829    fn raw(&self) -> &[u8] {
830        self.base.raw()
831    }
832    fn sad(&self) -> Sadder {
833        self.base.sad()
834    }
835    fn genus(&self) -> &str {
836        self.base.genus()
837    }
838    fn gvrsn(&self) -> &Versionage {
839        self.base.gvrsn()
840    }
841    fn kind(&self) -> &Kinds {
842        self.base.kind()
843    }
844    fn proto(&self) -> &str {
845        self.base.proto()
846    }
847    fn vrsn(&self) -> &Versionage {
848        self.base.vrsn()
849    }
850    fn size(&self) -> usize {
851        self.base.size()
852    }
853    fn said(&self) -> Option<&str> {
854        self.base.said()
855    }
856    fn ilk(&self) -> Option<&str> {
857        self.base.ilk()
858    }
859    fn as_any(&self) -> &dyn Any {
860        self
861    }
862    fn clone_box(&self) -> Box<dyn Serder> {
863        Box::new(self.clone())
864    }
865}
866
867impl Rawifiable for SerderKERI {
868    /// Creates a new `SerderKERI` by constructing its `BaseSerder` from raw bytes.
869    fn from_raw(raw: &[u8], smell: Option<Smellage>) -> Result<Self, KERIError> {
870        let base = BaseSerder::from_raw(raw, smell)?;
871        Ok(Self { base })
872    }
873}
874
875impl SerderKERI {
876    pub fn new(
877        raw: Option<&[u8]>,
878        sad: Option<&Sadder>,
879        makify: Option<bool>,
880        smellage: Option<Smellage>,
881        proto: Option<String>,
882        vrsn: Option<Versionage>,
883        kind: Option<Kinds>,
884        ilk: Option<Ilk>,
885        saids: Option<HashMap<&str, String>>,
886    ) -> Result<Self, KERIError> {
887        let base =
888            BaseSerder::from_init(raw, sad, makify, smellage, proto, vrsn, kind, ilk, saids)?;
889        Ok(Self { base })
890    }
891    /// Creates a new `SerderKERI` by constructing its `BaseSerder` from a sad.
892    pub fn from_sad(sad: &Sadder) -> Result<Self, KERIError> {
893        let base = BaseSerder::from_sad(sad)?;
894        Ok(Self { base })
895    }
896
897    pub fn from_sad_and_saids(
898        sad: &Sadder,
899        saids: Option<HashMap<&str, String>>,
900    ) -> Result<Self, KERIError> {
901        let base = BaseSerder::from_init(
902            None,
903            Some(sad),
904            Some(true),
905            None,
906            None,
907            None,
908            None,
909            None,
910            saids,
911        )?;
912        Ok(Self { base })
913    }
914
915    /// Returns true if Serder represents an establishment event
916    pub fn estive(&self) -> bool {
917        let t = self.base.sad.get("t").unwrap().as_str().unwrap();
918        matches!(t, "icp" | "rot" | "dip" | "drt")
919    }
920
921    /// Returns key event dict property getter. Alias for .sad
922    pub fn ked(&self) -> Sadder {
923        self.base.sad.clone()
924    }
925
926    /// Returns qb64 of .sad["i"] identifier prefix
927    pub fn pre(&self) -> Option<String> {
928        Some(
929            self.base
930                .sad
931                .get("i")
932                .unwrap()
933                .as_str()
934                .unwrap()
935                .to_string()
936                .clone(),
937        )
938    }
939
940    /// Returns qb64b of .pre identifier prefix as bytes
941    pub fn preb(&self) -> Option<Vec<u8>> {
942        self.pre().map(|pre| pre.into_bytes())
943    }
944
945    /// Number instance of sequence number
946    pub fn sner(&self) -> Option<Number> {
947        let num = Number::from_numh(
948            self.base
949                .sad
950                .get("s")
951                .unwrap_or(&SadValue::String("0".to_string()))
952                .as_str()
953                .unwrap(),
954        );
955        match num {
956            Ok(num) => Some(num),
957            Err(e) => {
958                error!("Error parsing sequence number: {}", e);
959                None
960            }
961        }
962    }
963
964    /// Sequence number as integer
965    pub fn sn(&self) -> Option<u64> {
966        match self.sner() {
967            Some(num) => Some(num.num() as u64),
968            None => None,
969        }
970    }
971
972    /// Sequence number as hex string
973    pub fn snh(&self) -> Option<String> {
974        self.sner().map(|sner| sner.numh())
975    }
976
977    /// Seals from .sad["a"]
978    pub fn seals(&self) -> Option<Vec<IndexMap<String, SadValue>>> {
979        match &self.base.sad.get("a") {
980            Some(SadValue::Array(list)) => {
981                let mut seals = Vec::new();
982                for seal in list.iter() {
983                    match seal {
984                        SadValue::Object(seal) => seals.push(seal.clone()),
985                        _ => return None,
986                    }
987                }
988                Some(seals)
989            }
990            Some(SadValue::Object(map)) => {
991                let mut seals = Vec::new();
992                seals.push(map.clone());
993                Some(seals)
994            }
995            _ => None,
996        }
997    }
998
999    /// Traits list (config traits) from .sad["c"]
1000    pub fn traits(&self) -> Option<SadValue> {
1001        self.base.sad.get("c").cloned()
1002    }
1003
1004    /// Tholder instance as converted from .sad['kt']
1005    pub fn tholder(&self) -> Option<Tholder> {
1006        match self.base.sad.get("kt") {
1007            Some(kt) => {
1008                let sith = TholderSith::from_sad_value(kt.clone());
1009                match sith {
1010                    Ok(sith) => {
1011                        let thold = Tholder::new(None, None, Some(sith));
1012                        match thold {
1013                            Ok(thold) => Some(thold),
1014                            Err(e) => {
1015                                error!("Error parsing threshold: {}", e);
1016                                None
1017                            }
1018                        }
1019                    }
1020                    Err(_) => None,
1021                }
1022            }
1023            None => None,
1024        }
1025    }
1026
1027    /// List of qb64 keys from .sad['k']
1028    pub fn keys(&self) -> Option<Vec<String>> {
1029        match &self.base.sad.get("k") {
1030            Some(SadValue::Array(list)) => {
1031                let mut keys = Vec::new();
1032                for key in list.iter() {
1033                    match key {
1034                        SadValue::String(key) => keys.push(key.clone()),
1035                        _ => return None,
1036                    }
1037                }
1038                Some(keys)
1039            }
1040            _ => None,
1041        }
1042    }
1043
1044    /// List of Verfer instances as converted from .sad['k']
1045    pub fn verfers(&self) -> Option<Vec<Verfer>> {
1046        self.keys().and_then(|keys| {
1047            let mut verfers = Vec::new();
1048            for key in keys.iter() {
1049                match Verfer::from_qb64(key) {
1050                    Ok(verfer) => verfers.push(verfer),
1051                    Err(_) => return None,
1052                }
1053            }
1054            Some(verfers)
1055        })
1056    }
1057
1058    /// Tholder instance as converted from .sad['nt']
1059    pub fn ntholder(&self) -> Option<Tholder> {
1060        // Same as tholder(): `nt` is a threshold value (hex string or weights),
1061        // not a CESR-encoded limen.
1062        let nt = self.base.sad.get("nt")?;
1063        let sith = TholderSith::from_sad_value(nt.clone()).ok()?;
1064        match Tholder::new(None, None, Some(sith)) {
1065            Ok(thold) => Some(thold),
1066            Err(e) => {
1067                error!("Error parsing next threshold: {}", e);
1068                None
1069            }
1070        }
1071    }
1072
1073    /// Next key digests from .sad['n']
1074    pub fn ndigs(&self) -> Option<Vec<String>> {
1075        match &self.base.sad.get("n") {
1076            Some(SadValue::Array(list)) => {
1077                let mut keys = Vec::new();
1078                for key in list.iter() {
1079                    match key {
1080                        SadValue::String(key) => keys.push(key.clone()),
1081                        _ => return None,
1082                    }
1083                }
1084                Some(keys)
1085            }
1086            _ => None,
1087        }
1088    }
1089
1090    /// List of Diger instances as converted from .sad['n']
1091    pub fn ndigers(&self) -> Option<Vec<Diger>> {
1092        self.ndigs().and_then(|digs| {
1093            let mut digers = Vec::new();
1094            for dig in digs.iter() {
1095                match Diger::from_qb64(dig) {
1096                    Ok(diger) => digers.push(diger),
1097                    Err(_) => return None,
1098                }
1099            }
1100            Some(digers)
1101        })
1102    }
1103
1104    /// Number of backer TOAD threshold
1105    pub fn bner(&self) -> Option<Number> {
1106        let num = Number::from_numh(
1107            self.base
1108                .sad
1109                .get("bt")
1110                .unwrap_or(&SadValue::String("0".to_string()))
1111                .as_str()
1112                .unwrap(),
1113        );
1114        match num {
1115            Ok(num) => Some(num),
1116            Err(e) => {
1117                error!("Error parsing sequence number: {}", e);
1118                None
1119            }
1120        }
1121    }
1122
1123    /// Backer TOAD number as integer
1124    pub fn bn(&self) -> Option<u64> {
1125        match self.sner() {
1126            Some(num) => Some(num.num() as u64),
1127            None => None,
1128        }
1129    }
1130
1131    /// Backers list from .sad['b']
1132    pub fn backs(&self) -> Option<Vec<String>> {
1133        match &self.base.sad.get("b") {
1134            Some(SadValue::Array(list)) => {
1135                let mut keys = Vec::new();
1136                for key in list.iter() {
1137                    match key {
1138                        SadValue::String(key) => keys.push(key.clone()),
1139                        _ => return None,
1140                    }
1141                }
1142                Some(keys)
1143            }
1144            _ => None,
1145        }
1146    }
1147
1148    /// List of Verfer instances as converted from .sad['b']
1149    pub fn berfers(&self) -> Option<Vec<Verfer>> {
1150        self.backs().and_then(|keys| {
1151            let mut verfers = Vec::new();
1152            for key in keys.iter() {
1153                match Verfer::from_qb64(key) {
1154                    Ok(verfer) => verfers.push(verfer),
1155                    Err(_) => return None,
1156                }
1157            }
1158            Some(verfers)
1159        })
1160    }
1161
1162    /// Prior event SAID from .sad['p']
1163    pub fn prior(&self) -> Option<String> {
1164        match self.base.sad.get("p") {
1165            Some(sv) => match sv {
1166                SadValue::String(val) => Some(val.clone()),
1167                _ => None,
1168            },
1169            None => None,
1170        }
1171    }
1172
1173    /// Prior event SAID as bytes
1174    pub fn priorb(&self) -> Option<Vec<u8>> {
1175        self.prior().map(|prior| prior.into_bytes())
1176    }
1177
1178    /// List of backers to be cut (removed) from .sad['br']
1179    pub fn cuts(&self) -> Option<Vec<String>> {
1180        match &self.base.sad.get("br") {
1181            Some(SadValue::Array(list)) => {
1182                let mut keys = Vec::new();
1183                for key in list.iter() {
1184                    match key {
1185                        SadValue::String(key) => keys.push(key.clone()),
1186                        _ => return None,
1187                    }
1188                }
1189                Some(keys)
1190            }
1191            _ => None,
1192        }
1193    }
1194
1195    /// List of backers to be added from .sad['ba']
1196    pub fn adds(&self) -> Option<Vec<String>> {
1197        match &self.base.sad.get("ba") {
1198            Some(SadValue::Array(list)) => {
1199                let mut keys = Vec::new();
1200                for key in list.iter() {
1201                    match key {
1202                        SadValue::String(key) => keys.push(key.clone()),
1203                        _ => return None,
1204                    }
1205                }
1206                Some(keys)
1207            }
1208            _ => None,
1209        }
1210    }
1211
1212    /// Delegator ID prefix from .sad["di"]
1213    pub fn delpre(&self) -> Option<String> {
1214        match self.base.sad.get("di") {
1215            Some(sv) => match sv {
1216                SadValue::String(val) => Some(val.clone()),
1217                _ => None,
1218            },
1219            None => None,
1220        }
1221    }
1222
1223    /// Delegator ID prefix as bytes
1224    pub fn delpreb(&self) -> Option<Vec<u8>> {
1225        self.delpre().map(|delpre| delpre.into_bytes())
1226    }
1227
1228    /// Date-time-stamp from .sad["dt"]
1229    pub fn stamp(&self) -> Option<String> {
1230        match self.base.sad.get("dt") {
1231            Some(sv) => match sv {
1232                SadValue::String(val) => Some(val.clone()),
1233                _ => None,
1234            },
1235            None => None,
1236        }
1237    }
1238
1239    /// UUID (salty nonce) from .sad["u"]
1240    pub fn uuid(&self) -> Option<String> {
1241        match self.base.sad.get("u") {
1242            Some(sv) => match sv {
1243                SadValue::String(val) => Some(val.clone()),
1244                _ => None,
1245            },
1246            None => None,
1247        }
1248    }
1249
1250    /// Alias for .uuid property with version check
1251    pub fn nonce(&self) -> Option<String> {
1252        match self.base.sad.get("n") {
1253            Some(sv) => match sv {
1254                SadValue::String(val) => Some(val.clone()),
1255                _ => None,
1256            },
1257            None => None,
1258        }
1259    }
1260
1261    /// Get the ilk of the event
1262    pub fn ilk(&self) -> Option<Ilk> {
1263        match self.base.sad.get("t") {
1264            Some(sv) => match sv {
1265                SadValue::String(val) => Ilk::from_str(val),
1266                _ => None,
1267            },
1268            None => None,
1269        }
1270    }
1271
1272    pub fn compare_said(&self, said: &str) -> bool {
1273        self.base.compare_said(said)
1274    }
1275}
1276
1277// Override the verification for the derived struct
1278impl Verifiable for SerderKERI {
1279    fn _verify(&self) -> Result<(), KERIError> {
1280        // First call the base implementation
1281        self.base._verify()?;
1282
1283        // Then add SerderKERI-specific verification
1284        // Additional verification logic here
1285
1286        Ok(())
1287    }
1288}
1289
1290/// Helper function to parse version string into Versionage
1291fn parse_version(version_str: &str) -> Result<Versionage, String> {
1292    let parts: Vec<&str> = version_str.split('.').collect();
1293
1294    if parts.len() != 2 {
1295        return Err(format!("Invalid version format: {}", version_str));
1296    }
1297
1298    let major = match parts[0].parse::<u32>() {
1299        Ok(num) => num,
1300        Err(_) => return Err(format!("Invalid major version: {}", parts[0])),
1301    };
1302
1303    let minor = match parts[1].parse::<u32>() {
1304        Ok(num) => num,
1305        Err(_) => return Err(format!("Invalid minor version: {}", parts[1])),
1306    };
1307
1308    Ok(Versionage { major, minor })
1309}
1310
1311/// SerderACDC struct that extends BaseSerder
1312#[derive(Debug, Clone)]
1313pub struct SerderACDC {
1314    /// Base Serder fields and behavior
1315    pub base: BaseSerder,
1316}
1317
1318/// Implement the Serder trait for SerderKERI
1319impl Serder for SerderACDC {
1320    fn pretty(&self, size: Option<usize>) -> String {
1321        self.base.pretty(size)
1322    }
1323    fn raw(&self) -> &[u8] {
1324        self.base.raw()
1325    }
1326    fn sad(&self) -> Sadder {
1327        self.base.sad()
1328    }
1329    fn genus(&self) -> &str {
1330        self.base.genus()
1331    }
1332    fn gvrsn(&self) -> &Versionage {
1333        self.base.gvrsn()
1334    }
1335    fn kind(&self) -> &Kinds {
1336        self.base.kind()
1337    }
1338    fn proto(&self) -> &str {
1339        self.base.proto()
1340    }
1341    fn vrsn(&self) -> &Versionage {
1342        self.base.vrsn()
1343    }
1344    fn size(&self) -> usize {
1345        self.base.size()
1346    }
1347    fn said(&self) -> Option<&str> {
1348        self.base.said()
1349    }
1350    fn ilk(&self) -> Option<&str> {
1351        self.base.ilk()
1352    }
1353    fn as_any(&self) -> &dyn Any {
1354        self
1355    }
1356    fn clone_box(&self) -> Box<dyn Serder> {
1357        Box::new(self.clone())
1358    }
1359}
1360
1361impl SerderACDC {
1362    /// Creates a new `SerderACDC` by constructing its `BaseSerder` from a sad.
1363    pub fn from_sad(sad: &Sadder) -> Result<Self, KERIError> {
1364        let base = BaseSerder::from_sad(sad)?;
1365        Ok(Self { base })
1366    }
1367
1368    /// uuid property getter
1369    /// Optional fields return None when not present
1370    ///
1371    /// Returns:
1372    ///    Option<String>: qb64 of .sad["u"] salty nonce
1373    /// UUID (salty nonce) from .sad["u"]
1374    pub fn uuid(&self) -> Option<String> {
1375        match self.base.sad.get("u") {
1376            Some(sv) => match sv {
1377                SadValue::String(val) => Some(val.clone()),
1378                _ => None,
1379            },
1380            None => None,
1381        }
1382    }
1383
1384    /// uuidb property getter (uuid bytes)
1385    /// Optional fields return None when not present
1386    ///
1387    /// Returns:
1388    ///    Option<Vec<u8>>: qb64b of .sad["u"] salty nonce as bytes
1389    pub fn uuidb(&self) -> Option<Vec<u8>> {
1390        self.uuid().map(|s| s.as_bytes().to_vec())
1391    }
1392
1393    /// issuer property getter (issuer AID)
1394    /// Optional fields return None when not present
1395    ///
1396    /// Returns:
1397    ///    Option<String>: qb64 of .sad["i"] issuer AID
1398    pub fn issuer(&self) -> Option<String> {
1399        match self.base.sad.get("i") {
1400            Some(sv) => match sv {
1401                SadValue::String(val) => Some(val.clone()),
1402                _ => None,
1403            },
1404            None => None,
1405        }
1406    }
1407
1408    /// issuerb property getter (issuer AID bytes)
1409    /// Optional fields return None when not present
1410    ///
1411    /// Returns:
1412    ///    Option<Vec<u8>>: qb64b of .issuer AID as bytes
1413    pub fn issuerb(&self) -> Option<Vec<u8>> {
1414        self.issuer().map(|s| s.as_bytes().to_vec())
1415    }
1416
1417    /// regi property getter (registry identifier SAID)
1418    /// Optional fields return None when not present
1419    ///
1420    /// Returns:
1421    ///    Option<String>: qb64 of .sad["ri"] registry SAID
1422    pub fn regi(&self) -> Option<String> {
1423        match self.base.sad.get("ri") {
1424            Some(sv) => match sv {
1425                SadValue::String(val) => Some(val.clone()),
1426                _ => None,
1427            },
1428            None => None,
1429        }
1430    }
1431
1432    /// regib property getter (registry identifier SAID bytes)
1433    /// Optional fields return None when not present
1434    ///
1435    /// Returns:
1436    ///    Option<Vec<u8>>: qb64b of .issuer AID as bytes
1437    pub fn regib(&self) -> Option<Vec<u8>> {
1438        // Note: There's a bug in the Python implementation that uses self.issuer here
1439        // Fixing it to use self.regi instead
1440        self.regi().map(|s| s.as_bytes().to_vec())
1441    }
1442
1443    /// schema block or SAID property getter
1444    /// Optional fields return None when not present
1445    ///
1446    /// Returns:
1447    ///    Option<&Value>: from ._sad["s"]
1448    pub fn schema(&self) -> Option<String> {
1449        match self.base.sad.get("s") {
1450            Some(sv) => match sv {
1451                SadValue::String(val) => Some(val.clone()),
1452                _ => None,
1453            },
1454            None => None,
1455        }
1456    }
1457
1458    /// attrib block or SAID property getter (attribute)
1459    /// Optional fields return None when not present
1460    ///
1461    /// Returns:
1462    ///    Option<&String>: from ._sad["a"]
1463    pub fn attrib(&self) -> Option<IndexMap<String, SadValue>> {
1464        match &self.base.sad.get("a") {
1465            Some(SadValue::Array(_)) => None,
1466            Some(SadValue::Object(map)) => Some(map.clone()),
1467            _ => None,
1468        }
1469    }
1470
1471    /// issuee property getter (issuee AID)
1472    /// Optional fields return None when not present
1473    ///
1474    /// Returns:
1475    ///    Option<String>: qb64 of .sad["a"]["i"] issuee AID
1476    pub fn issuee(&self) -> Option<String> {
1477        match &self.attrib() {
1478            Some(map) => match map.get("i") {
1479                Some(sv) => match sv {
1480                    SadValue::String(val) => Some(val.clone()),
1481                    _ => None,
1482                },
1483                None => None,
1484            },
1485            _ => None,
1486        }
1487    }
1488
1489    /// issueeb property getter (issuee AID bytes)
1490    /// Optional fields return None when not present
1491    ///
1492    /// Returns:
1493    ///    Option<Vec<u8>>: qb64b of .issuee AID as bytes
1494    pub fn issueeb(&self) -> Option<Vec<u8>> {
1495        self.issuee().map(|s| s.as_bytes().to_vec())
1496    }
1497
1498    /// attagg block property getter (attribute aggregate)
1499    /// Optional fields return None when not present
1500    ///
1501    /// Returns:
1502    ///    Option<&Value>: from ._sad["A"]
1503    pub fn attagg(&self) -> Option<&SadValue> {
1504        match &self.base.sad.get("A") {
1505            Some(sv) => Some(sv.clone()),
1506            _ => None,
1507        }
1508    }
1509
1510    /// edge block property getter
1511    /// Optional fields return None when not present
1512    ///
1513    /// Returns:
1514    ///    Option<&Value>: from ._sad["e"]
1515    pub fn edge(&self) -> Option<IndexMap<String, SadValue>> {
1516        match &self.base.sad.get("e") {
1517            Some(SadValue::Array(_)) => None,
1518            Some(SadValue::Object(map)) => Some(map.clone()),
1519            _ => None,
1520        }
1521    }
1522
1523    /// rule block property getter
1524    /// Optional fields return None when not present
1525    ///
1526    /// Returns:
1527    ///    Option<&Value>: from ._sad["r"]
1528    pub fn rule(&self) -> Option<IndexMap<String, SadValue>> {
1529        match &self.base.sad.get("r") {
1530            Some(SadValue::Array(_)) => None,
1531            Some(SadValue::Object(map)) => Some(map.clone()),
1532            _ => None,
1533        }
1534    }
1535}
1536
1537impl Rawifiable for SerderACDC {
1538    /// Creates a new `SerderACDC` by constructing its `BaseSerder` from raw bytes.
1539    fn from_raw(raw: &[u8], smell: Option<Smellage>) -> Result<Self, KERIError> {
1540        let base = BaseSerder::from_raw(raw, smell)?;
1541        Ok(Self { base })
1542    }
1543}
1544
1545// Implement the Serder trait for SerderACDC (assuming we have a trait as discussed)
1546impl Verifiable for SerderACDC {
1547    fn _verify(&self) -> Result<(), KERIError> {
1548        // First verify base fields
1549        self.base._verify()?;
1550
1551        // Add ACDC-specific verification
1552        // This could include validating the schema, issuer, etc.
1553
1554        Ok(())
1555    }
1556}
1557
1558impl SerderACDC {
1559    /// Public verification method that delegates to the trait method
1560    pub fn verify(&self) -> Result<(), KERIError> {
1561        self._verify()
1562    }
1563}
1564
1565/// Serder factory for generating serder instances by protocol type
1566pub struct Serdery;
1567
1568impl Serdery {
1569    /// Create a new Serdery instance
1570    pub fn new() -> Self {
1571        Serdery
1572    }
1573
1574    /// Extract and return Serder implementation based on protocol type detected in message
1575    ///
1576    /// # Arguments
1577    /// * `ims` - Serialized incoming message stream. Assumes start of stream is raw Serder.
1578    /// * `genus` - CESR genus code from stream parser.
1579    /// * `gvrsn` - Instance CESR genus code table version (Major, Minor)
1580    /// * `native` - True means may be CESR native message so snuff instead of smell.
1581    ///             False means not CESR native i.e JSON, CBOR, MGPK field map, so use smell.
1582    /// * `skip` - Bytes to skip at front of ims. Useful for CESR native serialization.
1583    ///
1584    /// # Returns
1585    /// Box<dyn Serder> - Instance of appropriate Serder implementation
1586    pub fn reap(
1587        &self,
1588        ims: &[u8],
1589        _genus: &str,
1590        _gvrsn: &Versionage,
1591        native: Option<bool>,
1592        skip: Option<usize>,
1593    ) -> Result<Box<dyn Serder>, KERIError> {
1594        let native = native.unwrap_or(false);
1595        let skip = skip.unwrap_or(0);
1596
1597        let smellage = if native {
1598            // Handle CESR native case, skipping bytes if necessary
1599            if skip > 0 && skip < ims.len() {
1600                smell(&ims[skip..])
1601            } else {
1602                smell(ims)
1603            }
1604        } else {
1605            smell(ims)
1606        }?;
1607
1608        let protos = Protocolage::default();
1609        if smellage.proto == protos.keri {
1610            // Create SerderKERI instance
1611            let serder = SerderKERI::from_raw(ims, Some(smellage))?;
1612            Ok(Box::new(serder))
1613        } else if smellage.proto == protos.acdc {
1614            // Create SerderACDC instance
1615            let serder = SerderACDC::from_raw(ims, Some(smellage))?;
1616            Ok(Box::new(serder))
1617        } else {
1618            Err(KERIError::ProtocolError(format!(
1619                "Unsupported protocol type = {}",
1620                smellage.proto
1621            )))
1622        }
1623    }
1624}
1625
1626// Helper function to check if a value is iterable
1627fn is_iterable(value: &SadValue) -> bool {
1628    matches!(value, SadValue::Array(_) | SadValue::Object(_))
1629}
1630
1631#[cfg(test)]
1632mod tests {
1633    use super::*;
1634    use crate::keri::core::serdering::sad::validate;
1635    use crate::keri::core::serdering::{SadValue, Sadder};
1636    use indexmap::{indexmap, IndexMap};
1637
1638    #[test]
1639    fn test_valid_icp_event() {
1640        let mut icp_event = IndexMap::new();
1641
1642        // Add version information
1643        icp_event.insert("v".to_string(), SadValue::from_string("KERI10JSON00011c_"));
1644
1645        // Add event type
1646        icp_event.insert("t".to_string(), SadValue::from_string("icp"));
1647
1648        // Add SAID digest
1649        icp_event.insert(
1650            "d".to_string(),
1651            SadValue::from_string("EL1L56LyoKrIofnn0q7_eKmLBELDT-8rS-7wjTuELmzQ"),
1652        );
1653
1654        // Add identifier
1655        icp_event.insert(
1656            "i".to_string(),
1657            SadValue::from_string("EL1L56LyoKrIofnn0q7_eKmLBELDT-8rS-7wjTuELmzQ"),
1658        );
1659
1660        // Add sequence number
1661        icp_event.insert("s".to_string(), SadValue::from_string("0"));
1662
1663        // Add key threshold
1664        icp_event.insert("kt".to_string(), SadValue::from_string("1"));
1665
1666        // Add keys as array
1667        let keys = vec![SadValue::from_string(
1668            "DQbYDpQRN5cmkQ94mR69N_c98C0-SIVYEj2LM2VAGUhZ",
1669        )];
1670        icp_event.insert("k".to_string(), SadValue::from_array(keys));
1671
1672        // Add next key threshold
1673        icp_event.insert("nt".to_string(), SadValue::from_string("1"));
1674
1675        // Add next keys as array
1676        let next_keys = vec![SadValue::from_string(
1677            "EsgNZjFXMI8szR6N5eG8OsHqXxyKWrYCkP9mGkYAjS3Y",
1678        )];
1679        icp_event.insert("n".to_string(), SadValue::from_array(next_keys));
1680
1681        // Add backer threshold
1682        icp_event.insert("bt".to_string(), SadValue::from_string("0"));
1683
1684        // Add backers as empty array
1685        icp_event.insert("b".to_string(), SadValue::from_array(Vec::new()));
1686
1687        // Add configuration traits as empty array
1688        icp_event.insert("c".to_string(), SadValue::from_array(Vec::new()));
1689
1690        // The final result is a Sadder (IndexMap<String, SadValue>)
1691        let icp_event: Sadder = icp_event;
1692
1693        assert!(validate(&icp_event).is_ok());
1694    }
1695
1696    #[test]
1697    fn test_invalid_icp_event() {
1698        // Missing k field which is required for icp events
1699        let invalid_icp = indexmap! {
1700            "v".to_string() => SadValue::from_string("KERI10JSON00011c_"),
1701            "t".to_string() => SadValue::from_string("icp"),
1702            "d".to_string() => SadValue::from_string("EL1L56LyoKrIofnn0q7_eKmLBELDT-8rS-7wjTuELmzQ"),
1703            "i".to_string() => SadValue::from_string("EL1L56LyoKrIofnn0q7_eKmLBELDT-8rS-7wjTuELmzQ"),
1704            "s".to_string() => SadValue::from_string("0".to_string()),
1705            "k".to_string() => SadValue::from_string("1".to_string()),
1706            // k field is missin
1707            "n".to_string() => SadValue::from_string("1".to_string()),
1708            "n".to_string() => SadValue::from_array(vec![SadValue::from_string("EsgNZjFXMI8szR6N5eG8OsHqXxyKWrYCkP9mGkYAjS3Y")]),
1709            "b".to_string() => SadValue::from_string("0".to_string()),
1710            "b".to_string() => SadValue::from_array(vec![]),
1711            "c".to_string() => SadValue::from_array(vec![]),
1712        };
1713
1714        assert!(validate(&invalid_icp).is_err());
1715    }
1716
1717    #[test]
1718    fn test_serder_initialization_and_verification() {
1719        // Test creating a Serder with makify=true and icp ilk
1720        let serder =
1721            BaseSerder::from_init(None, None, Some(true), None, None, None, None, None, None)
1722                .unwrap();
1723
1724        // Check the generated SAD structure
1725        let sad = serder.sad();
1726        assert_eq!(sad["t"].as_str().unwrap(), "icp");
1727        assert_eq!(sad["s"].as_str().unwrap(), "0");
1728        assert_eq!(sad["kt"].as_str().unwrap(), "0");
1729        assert_eq!(sad["nt"].as_str().unwrap(), "0");
1730        assert_eq!(sad["bt"].as_str().unwrap(), "0");
1731        assert!(sad["k"].as_str().is_none());
1732        assert!(sad["n"].as_str().is_none());
1733        assert!(sad["b"].as_str().is_none());
1734        assert!(sad["c"].as_str().is_none());
1735
1736        // In Python there's an assert for 'a' field, assuming it exists in Rust as well
1737        match &sad["a"] {
1738            SadValue::Array(list) => assert!(list.is_empty()),
1739            SadValue::Object(map) => assert!(map.is_empty()),
1740            _ => panic!("Expected 'a' field to exist but be empty"),
1741        }
1742
1743        // Verify the SAID is consistent
1744        assert_eq!(sad["d"], sad["i"].clone());
1745
1746        // Get raw bytes and verify they match the expected pattern
1747        let raw = serder.raw();
1748        assert!(raw.starts_with(b"{\"v\":\"KERI10JSON"));
1749        // assert!(raw.contains(b"\"t\":\"icp\""));
1750
1751        // Verify other properties
1752        // assert!(serder.verify().is_ok());
1753        assert_eq!(serder.ilk().unwrap(), "icp");
1754
1755        // Store values for reconstruction tests
1756        let sad_clone = serder.sad().clone();
1757        let raw_clone = serder.raw();
1758        let said = serder.said().clone();
1759        let size = serder.size();
1760
1761        // Test reconstruction from SAD
1762        let serder_from_sad = SerderKERI::from_sad(&sad_clone).unwrap();
1763        assert_eq!(serder_from_sad.raw(), raw_clone);
1764        assert_eq!(serder_from_sad.sad()["d"], sad["d"]);
1765        assert_eq!(serder_from_sad.proto(), "KERI");
1766        assert_eq!(serder_from_sad.vrsn(), &VRSN_1_0);
1767        assert_eq!(serder_from_sad.size(), size);
1768        assert_eq!(serder_from_sad.kind(), &Kinds::Json);
1769        assert_eq!(serder_from_sad.said(), said);
1770        assert_eq!(serder_from_sad.ilk().unwrap(), Ilk::Icp);
1771
1772        // Test reconstruction from raw bytes
1773        let serder_from_raw = SerderKERI::from_raw(&raw_clone, None).unwrap();
1774        assert_eq!(serder_from_raw.raw(), raw_clone);
1775
1776        // Check that SAD matches between original and reconstructed from raw
1777        let regenerated_sad = serder_from_raw.sad();
1778        assert_eq!(regenerated_sad["v"], sad["v"]);
1779        assert_eq!(regenerated_sad["t"], sad["t"]);
1780        assert_eq!(regenerated_sad["d"], sad["d"]);
1781        assert_eq!(regenerated_sad["i"], sad["i"]);
1782
1783        // Additional verification
1784        assert_eq!(serder_from_raw.proto(), "KERI");
1785        assert_eq!(serder_from_raw.vrsn(), &VRSN_1_0);
1786        assert_eq!(serder_from_raw.size(), size);
1787        assert_eq!(serder_from_raw.kind(), &Kinds::Json);
1788        assert_eq!(serder_from_raw.said(), said);
1789        assert_eq!(serder_from_raw.ilk().unwrap(), Ilk::Icp);
1790
1791        // Test creating a Serder with makify=true and icp ilk
1792        let mut sad = Sadder::default();
1793        sad.insert(
1794            "i".to_string(),
1795            SadValue::String("DKxy2sgzfplyr-tgwIxS19f2OchFHtLwPWD3v4oYimBx".to_string()),
1796        );
1797        let serder = BaseSerder::from_init(
1798            None,
1799            Some(&sad),
1800            Some(true),
1801            None,
1802            None,
1803            None,
1804            None,
1805            None,
1806            None,
1807        )
1808        .unwrap();
1809        assert_eq!(serder.sad()["i"], sad["i"]);
1810        assert_eq!(
1811            serder.sad()["d"].as_str().unwrap(),
1812            "EIXK39EgyxshefoCdSpKCkG5FR9s405YI4FAHDvAqO_R"
1813        );
1814    }
1815}