Skip to main content

libkeri/keri/db/basing/
mod.rs

1mod habitat_record;
2mod key_state_record;
3
4use crate::cesr::counting::{ctr_dex_1_0, BaseCounter, Counter};
5use crate::cesr::dater::Dater;
6use crate::cesr::diger::Diger;
7use crate::cesr::indexing::siger::Siger;
8use crate::cesr::num_dex;
9use crate::cesr::number::Number;
10use crate::cesr::prefixer::Prefixer;
11use crate::cesr::saider::Saider;
12use crate::cesr::seqner::Seqner;
13use crate::cesr::verfer::Verfer;
14use crate::keri::core::eventing::{Kever, SealEvent};
15use crate::keri::core::filing::{BaseFiler, Filer, FilerDefaults};
16use crate::keri::core::serdering::{Rawifiable, Serder, SerderKERI};
17use crate::keri::db::dbing::keys::{dg_key, sn_key};
18use crate::keri::db::dbing::LMDBer;
19use crate::keri::db::errors::DBError;
20use crate::keri::db::koming::{Komer, SerialKind};
21use crate::keri::db::subing::catcesr::CatCesrSuber;
22use crate::keri::db::subing::catcesrioset::CatCesrIoSetSuber;
23use crate::keri::db::subing::cesr::CesrSuber;
24use crate::keri::db::subing::cesrioset::CesrIoSetSuber;
25use crate::keri::db::subing::dup::DupSuber;
26use crate::keri::db::subing::iodup::IoDupSuber;
27use crate::keri::db::subing::on::OnSuber;
28use crate::keri::db::subing::oniodup::OnIoDupSuber;
29use crate::keri::db::subing::serder::SerderSuber;
30use crate::keri::db::subing::{Suber, Utf8Codec};
31use crate::keri::KERIError;
32use crate::Matter;
33use chrono::DateTime;
34pub use habitat_record::HabitatRecord;
35use indexmap::IndexSet;
36pub use key_state_record::KeyStateRecord;
37pub use key_state_record::StateEERecord;
38use num_bigint::BigUint;
39use serde::{Deserialize, Serialize};
40use std::collections::HashMap;
41use std::path::PathBuf;
42use std::sync::Arc;
43
44/// EventSourceRecord tracks the source of an event (local or remote)
45/// Keyed by dig (said) of serder of event
46#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
47pub struct EventSourceRecord {
48    /// True if local (protected), False if remote (unprotected)
49    pub local: bool,
50}
51
52impl EventSourceRecord {
53    /// Create a new EventSourceRecord with default local=true
54    pub fn new() -> Self {
55        EventSourceRecord { local: true }
56    }
57
58    /// Create a new EventSourceRecord with specified local value
59    pub fn with_local(local: bool) -> Self {
60        EventSourceRecord { local }
61    }
62
63    /// Convert the record to a hashmap for serialization
64    pub fn to_map(&self) -> HashMap<String, bool> {
65        let mut map = HashMap::new();
66        map.insert("local".to_string(), self.local);
67        map
68    }
69
70    /// Create from a hashmap after deserialization
71    pub fn from_map(map: &HashMap<String, bool>) -> Option<Self> {
72        map.get("local").map(|&local| EventSourceRecord { local })
73    }
74}
75
76impl Default for EventSourceRecord {
77    fn default() -> Self {
78        Self::new()
79    }
80}
81
82impl IntoIterator for EventSourceRecord {
83    type Item = (String, bool);
84    type IntoIter = std::vec::IntoIter<Self::Item>;
85
86    fn into_iter(self) -> Self::IntoIter {
87        vec![("local".to_string(), self.local)].into_iter()
88    }
89}
90
91/// Service Endpoint Record with url for endpoint of a given scheme
92///
93/// The eid is usually a nontransferable identifier when its used for roles
94/// witness or watcher but may be transferable for other roles such as controller,
95/// judge, juror, public watcher, or registrar.
96///
97/// Database Keys are (eid, scheme) where eid is service endpoint identifier
98/// (qb64 prefix) and scheme is the url protocol scheme (tcp, https).
99///
100/// A loc reply message is required from which the values of this
101/// database record are extracted. route is /loc/scheme Uses enact-anul model
102/// To nullify endpoint set url field to empty.
103///
104/// An end authorization reply message is also required to authorize the eid as
105/// endpoint provider for cid at role. See EndpointRecord
106#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
107pub struct LocationRecord {
108    /// Full url including host:port/path?query scheme is optional
109    pub url: String,
110}
111
112impl LocationRecord {
113    /// Create a new LocationRecord
114    pub fn new(url: String) -> Self {
115        Self { url }
116    }
117
118    /// Check if the endpoint is nullified (empty url)
119    pub fn is_nullified(&self) -> bool {
120        self.url.is_empty()
121    }
122
123    /// Convert to HashMap for iteration/serialization compatibility
124    pub fn to_map(&self) -> HashMap<String, String> {
125        let mut map = HashMap::new();
126        map.insert("url".to_string(), self.url.clone());
127        map
128    }
129}
130
131impl IntoIterator for LocationRecord {
132    type Item = (String, String);
133    type IntoIter = std::collections::hash_map::IntoIter<String, String>;
134
135    fn into_iter(self) -> Self::IntoIter {
136        self.to_map().into_iter()
137    }
138}
139
140/// Service Endpoint ID (SEID) Record with fields and keys to manage endpoints by
141/// cid, role, and eid. Serves as aggregation mechanism for authorization and other
142/// functions such as UX naming with regards the endpoint.
143///
144/// The namespace is a tree of branches with each leaf at a
145/// specific (cid, role, eid). Retrieval by branch returns groups of leaves as
146/// appropriate for a cid branch or cid.role branch.
147/// Database Keys are (cid, role, eid) where cid is attributable controller identifier
148/// (qb64 prefix) that has role(s) such as watcher, witness etc and eid is the
149/// identifier of the controller acting in a role i.e. watcher identifier.
150#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
151pub struct EndpointRecord {
152    /// AuthZ via reply message
153    /// - `Some(true)` means eid is allowed as controller of endpoint in role
154    /// - `Some(false)` means eid is disallowed as controller of endpoint in role  
155    /// - `None` means eid is neither allowed or disallowed (no reply msg)
156    pub allowed: Option<bool>,
157
158    /// AuthZ via expose message
159    /// - `Some(true)` means eid is enabled as controller of endpoint in role
160    /// - `Some(false)` means eid is disabled as controller of endpoint in role
161    /// - `None` means eid is neither enabled or disabled (no expose msg)
162    pub enabled: Option<bool>,
163
164    /// Optional user friendly name for eid in role
165    pub name: String,
166}
167
168impl EndpointRecord {
169    /// Create a new EndpointRecord with default values
170    pub fn new() -> Self {
171        Self {
172            allowed: None,
173            enabled: None,
174            name: String::new(),
175        }
176    }
177
178    /// Create a new EndpointRecord with specified values
179    pub fn with_values(allowed: Option<bool>, enabled: Option<bool>, name: String) -> Self {
180        Self {
181            allowed,
182            enabled,
183            name,
184        }
185    }
186
187    /// Check if endpoint is allowed (authorized via reply message)
188    pub fn is_allowed(&self) -> Option<bool> {
189        self.allowed
190    }
191
192    /// Check if endpoint is enabled (authorized via expose message)
193    pub fn is_enabled(&self) -> Option<bool> {
194        self.enabled
195    }
196
197    /// Set allowed status (add/cut model)
198    pub fn set_allowed(&mut self, allowed: bool) {
199        self.allowed = Some(allowed);
200    }
201
202    /// Set enabled status  
203    pub fn set_enabled(&mut self, enabled: bool) {
204        self.enabled = Some(enabled);
205    }
206
207    /// Set user friendly name
208    pub fn set_name(&mut self, name: String) {
209        self.name = name;
210    }
211
212    /// Convert to HashMap for iteration/serialization compatibility
213    pub fn to_map(&self) -> HashMap<String, serde_json::Value> {
214        let mut map = HashMap::new();
215        map.insert("allowed".to_string(), serde_json::Value::from(self.allowed));
216        map.insert("enabled".to_string(), serde_json::Value::from(self.enabled));
217        map.insert(
218            "name".to_string(),
219            serde_json::Value::String(self.name.clone()),
220        );
221        map
222    }
223}
224
225impl Default for EndpointRecord {
226    fn default() -> Self {
227        Self::new()
228    }
229}
230
231impl IntoIterator for EndpointRecord {
232    type Item = (String, serde_json::Value);
233    type IntoIter = std::collections::hash_map::IntoIter<String, serde_json::Value>;
234
235    fn into_iter(self) -> Self::IntoIter {
236        self.to_map().into_iter()
237    }
238}
239
240// Database key types for organizing records
241#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
242pub struct LocationKey {
243    pub eid: String,    // service endpoint identifier (qb64 prefix)
244    pub scheme: String, // url protocol scheme (tcp, https)
245}
246
247#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
248pub struct EndpointKey {
249    pub cid: String,  // attributable controller identifier (qb64 prefix)
250    pub role: String, // role such as watcher, witness
251    pub eid: String,  // identifier of the controller acting in role
252}
253
254impl LocationKey {
255    pub fn new(eid: String, scheme: String) -> Self {
256        Self { eid, scheme }
257    }
258}
259
260impl EndpointKey {
261    pub fn new(cid: String, role: String, eid: String) -> Self {
262        Self { cid, role, eid }
263    }
264}
265
266/// Baser struct for key event log and escrow storage (DB)
267/// Sets up named sub databases for key event logs and escrow storage.
268pub struct Baser {
269    /// Base database
270    lmdber: Arc<LMDBer>, // The base LMDB database
271
272    // Local prefixes and key-state caches live in Kevery (one copy per owner),
273    // not here: Baser is a stateless handle over LMDB and safe to share.
274
275    /// habitat application state keyed by habitat name, includes prefix
276    pub habs: Komer<HabitatRecord>,
277
278    /// habitat name database mapping (domain,name) as key to Prefixer
279    pub names: Suber,
280
281    /// .evts is named sub DB whose values are serialized key events
282    ///     dgKey
283    ///     DB is keyed by identifier prefix plus digest of serialized event
284    ///     Only one value per DB key is allowed
285    pub evts: Suber,
286
287    /// .fels is named sub DB of first seen event logs (FEL) as indices that map
288    ///    first seen ordinal number to digests.
289    ///    Actual serialized key events are stored in .evts by SAID digest
290    ///    This indexes events in first 'seen' accepted order for replay and
291    ///    cloning of event log.
292    ///    Uses first seen order number or fn.
293    ///    fnKey
294    ///    DB is keyed by identifier prefix plus monotonically increasing first
295    ///    seen order number fn.
296    ///    Value is digest of serialized event used to lookup event in .evts sub DB
297    ///    Only one value per DB key is allowed.
298    ///    Provides append only ordering of accepted first seen events.
299    pub fels: OnSuber,
300
301    /// .kels is named sub DB of key event logs as indices that map sequence numbers
302    ///     to serialized key event digests.
303    ///     Actual serialized key events are stored in .evts by SAID digest
304    ///     Uses sequence number or sn.
305    ///     snKey
306    ///     Values are digests used to lookup event in .evts sub DB
307    ///     DB is keyed by identifier prefix plus sequence number of key event
308    ///     More than one value per DB key is allowed
309    pub kels: OnIoDupSuber<Utf8Codec>,
310
311    /// .fons is named subDB CesrSuber
312    ///     Uses digest
313    ///     dgKey
314    ///     Maps prefix and digest to fn value (first seen ordinal number) of
315    ///     the associated event. So one used pre and event digest, get its fn here
316    ///     and then use fn to fetch event from .evnts by fn from .fels.
317    ///     This ensures that any event looked up this way was first seen at
318    ///     some point in time even if later superseded by a recovery rotation.
319    ///     Whereas direct lookup in .evts could be escrowed events that may
320    ///     never have been accepted as first seen.
321    ///     CesrSuber(db=self, subkey='fons.', klas=core.Number)
322    pub fons: CesrSuber<Number>,
323
324    /// .esrs is named sub DB instance of Komer of EventSourceRecord
325    ///      dgKey
326    ///      DB is keyed by identifier prefix plus digest (said) of serialized event
327    ///      Value is serialized instance of EventSourceRecord dataclass.
328    ///      Only one value per DB key is allowed.
329    ///      Keeps track of the source of the event. When .local is Truthy the
330    ///      event was sourced in a protected way such as being generated
331    ///      locally or via a protected path. When .local is Falsey the event was
332    ///      NOT sourced in a protected way. The value of .local determines what
333    ///      validation logic to run on the event. This database is used to track
334    ///      the source when processing escrows that would otherwise be decoupled
335    ///      from the original source of the event.
336    pub esrs: Komer<EventSourceRecord>,
337
338    /// .dtss is named sub DB of datetime stamp strings in ISO 8601 format of
339    ///      the datetime when the event was first escrosed and then later first
340    ///      seen by log. Used for escrows timeouts and extended validation.
341    ///      dgKey
342    ///      DB is keyed by identifier prefix plus digest of serialized event
343    ///      Value is ISO 8601 datetime stamp bytes
344    pub dtss: DupSuber,
345
346    /// .sdts (sad date-time-stamp) named subDB instance of CesrSuber that
347    ///     maps SAD SAID to Dater instance's CESR serialization of
348    ///     ISO-8601 datetime
349    ///     key = said (bytes) of sad, val = dater.qb64b
350    pub sdts: CesrSuber<Dater>,
351
352    /// .rpys (replys) named subDB instance of SerderSuber that maps said of
353    ///     reply message (versioned SAD) to serialization of that reply message.
354    ///     key is said bytes, val is Serder.raw bytes of reply 'rpy' message
355    pub rpys: SerderSuber<SerderKERI>,
356
357    /// .ssgs (sad trans indexed sigs) named subDB instance of CesrIoSetSuber
358    ///     that maps keys quadruple (saider.qb64, prefixer.qb64, seqner.q64,
359    ///     diger.qb64) to val Siger of trans id signature. Where: saider is
360    ///     said of SAD and prefixer, seqner, and diger indicate the key state
361    ///     est event for signer or reply SAD. Each key may
362    ///     have a set of vals in insertion order one for each signer of the sad.
363    ///     key = join (saider.qb64b, prefixer.qb64b, seqner.qb64b, diger.qb64b)
364    ///     (bytes)  val = siger.qb64b
365    pub ssgs: CatCesrIoSetSuber<Siger>,
366
367    /// .scgs (sad nontrans cigs) named subDB instance of CatCesrIoSetSuber
368    ///     that maps said of SAD to couple (Verfer, Cigar) for nontrans signer.
369    ///     For nontrans qb64 of Verfer is same as Prefixer.
370    ///     Each key may have a set of vals in insertion order one for each
371    ///     nontrans signer of the sad.
372    ///     key = said (bytes) of SAD, val = cat of (verfer.qb64, cigar.qb64b)
373    pub scgs: CatCesrIoSetSuber<Verfer>,
374
375    /// .rpes (reply escrows) named subDB instance of CesrIoSetSuber that
376    ///     maps routes of reply (versioned SAD) to single Saider of that
377    ///     reply msg.
378    ///     Routes such as '/end/role/' and '/loc/scheme'
379    ///     key is route bytes, vals = saider.qb64b of reply 'rpy' msg
380    pub rpes: CesrIoSetSuber<Saider>,
381
382    /// .aess is named sub DB of authorizing event source seal couples
383    ///      that map digest to seal source couple of authorizer's
384    ///      (delegator or issuer) event. Each couple is a concatenation of full
385    ///      qualified items, snu+dig of the authorizing (delegating or issuing)
386    ///      source event.
387    ///      dgKey
388    ///      Values are couples used to lookup authorizer's source event in
389    ///      .kels sub DB
390    ///      DB is keyed by identifier prefix plus digest of key event
391    ///      Only one value per DB key is allowed
392    pub aess: Suber,
393
394    /// .sigs is named sub DB of fully qualified indexed event signatures
395    ///      dgKey
396    ///      DB is keyed by identifier prefix plus digest of serialized event
397    ///      More than one value per DB key is allowed
398    pub sigs: DupSuber,
399
400    ///  .wigs is named sub DB of indexed witness signatures of event that may
401    ///      come directly or derived from a witness receipt message.
402    ///      Witnesses always have nontransferable identifier prefixes.
403    ///      The index is the offset of the witness into the witness list
404    ///      of the most recent establishment event wrt the receipted event.
405    ///      dgKey
406    ///      DB is keyed by identifier prefix plus digest of serialized event
407    ///      More than one value per DB key is allowed
408    pub wigs: DupSuber,
409
410    /// Insertion order set of witnesses qb64 prefix
411    pub wits: IoDupSuber,
412
413    /// .rcts is named sub DB of event receipt couplets from nontransferable
414    ///     signers.
415    ///     These are endorsements from nontrasferable signers who are not witnesses
416    ///     May be watchers or other
417    ///     Each couple is concatenation of fully qualified items.
418    ///     These are: non-transferale prefix plus non-indexed event signature
419    ///     by that prefix.
420    ///     dgKey
421    ///     DB is keyed by identifier prefix plus digest of serialized event
422    ///     More than one value per DB key is allowed
423    pub rcts: DupSuber,
424
425    /// .vrcs is named sub DB of event validator receipt quadruples from transferable
426    ///     signers. Each quadruple is concatenation of  four fully qualified items
427    ///     of validator. These are: transferable prefix, plus latest establishment
428    ///     event sequence number plus latest establishment event digest,
429    ///     plus indexed event signature.
430    ///     These are endorsements by transferable AIDs that are not the controller
431    ///     may be watchers or others.
432    ///     When latest establishment event is multisig then there will
433    ///     be multiple quadruples one per signing key, each a dup at same db key.
434    ///     dgKey
435    ///     DB is keyed by identifier prefix plus digest of serialized event
436    ///     More than one value per DB key is allowed
437    pub vrcs: DupSuber,
438
439    /// Prefix situation database
440    /// Key is identifier prefix (fully qualified qb64)
441    /// Value is serialized parameter dict of public key situation
442    pub states: Komer<KeyStateRecord>,
443
444    pub locs: Komer<LocationRecord>,
445
446    pub ends: Komer<EndpointRecord>,
447
448    pub eans: CesrSuber<Saider>,
449
450    pub lans: CesrSuber<Saider>,
451
452    pub pses: IoDupSuber,
453
454    /// Partially witnessed escrow: snKey(pre, sn) -> said of the escrowed event
455    /// (keripy `.pwes`).
456    pub pwes: IoDupSuber,
457
458    /// Out-of-order escrow: snKey(pre, sn) -> said of an event whose prior
459    /// event isn't accepted yet (keripy `.ooes`).
460    pub ooes: IoDupSuber,
461
462    /// Likely duplicitous escrow: snKey(pre, sn) -> said of an event that
463    /// conflicts with one already accepted at that sn (keripy `.ldes`).
464    pub ldes: IoDupSuber,
465
466    /// .misfits: events from a remote source for an identifier that is
467    ///     locally owned, witnessed or delegated (keripy `misfits`, "mfes.").
468    ///     snKey -> event SAID. They wait for the local owner to decide; nothing
469    ///     processes them automatically (as in keripy).
470    pub misfits: IoDupSuber,
471
472    /// .delegables: delegated events, for a locally owned delegator, that have
473    ///     no approval yet (keripy `delegables`, "dees."). snKey -> event SAID.
474    ///     The delegator approves them with `Habery::approve_delegation`.
475    pub delegables: IoDupSuber,
476
477    /// Unverified receipt escrow: snKey(pre, sn) -> said + receiptor prefix +
478    /// cigar of a non-transferable receipt whose event is not yet in the KEL
479    /// (keripy `.ures`).
480    pub ures: IoDupSuber,
481
482    /// Unverified witness receipt escrow: snKey(pre, sn) -> said + wig of an
483    /// indexed witness receipt whose event is not yet in the KEL (keripy `.uwes`).
484    pub uwes: IoDupSuber,
485}
486
487impl Filer for Baser {
488    fn defaults() -> FilerDefaults {
489        BaseFiler::defaults()
490    }
491
492    #[cfg(target_os = "windows")]
493    const TAIL_DIR_PATH: &'static str = "keri\\db";
494    #[cfg(not(target_os = "windows"))]
495    const TAIL_DIR_PATH: &'static str = "keri/db";
496
497    #[cfg(target_os = "windows")]
498    const ALT_TAIL_DIR_PATH: &'static str = ".keri\\db";
499    #[cfg(not(target_os = "windows"))]
500    const ALT_TAIL_DIR_PATH: &'static str = ".keri/db";
501
502    const TEMP_PREFIX: &'static str = "keri_db_";
503}
504
505impl Baser {
506    /// Maximum number of named databases
507    pub const MAX_NAMED_DBS: u32 = 10;
508
509    /// Create a new Keeper instance
510    pub fn new(lmdber: Arc<LMDBer>) -> Result<Self, DBError> {
511        // Create the keeper instance
512        let baser = Baser {
513            lmdber: lmdber.clone(),
514
515            // Initialize the evts sub database
516            evts: Suber::new(lmdber.clone(), "evts.", None, false)
517                .map_err(|e| DBError::DatabaseError(format!("SuberError: {}", e)))?,
518
519            // Initialize the fels sub database
520            fels: OnSuber::new(lmdber.clone(), "fels.", None, false)
521                .map_err(|e| DBError::DatabaseError(format!("SuberError: {}", e)))?,
522
523            // Initialize the kels sub database
524            kels: OnIoDupSuber::new(lmdber.clone(), "kels.", None, false)
525                .map_err(|e| DBError::DatabaseError(format!("SuberError: {}", e)))?,
526
527            // Initialize the fons sub database
528            fons: CesrSuber::<Number>::new(lmdber.clone(), "fons.", None, false)
529                .map_err(|e| DBError::DatabaseError(format!("SuberError: {}", e)))?,
530
531            // Initialize the esrs sub database
532            esrs: Komer::new(lmdber.clone(), "esrs.", SerialKind::Json)
533                .map_err(|e| DBError::DatabaseError(format!("SuberError: {}", e)))?,
534
535            // Initialize the dtss sub database
536            dtss: DupSuber::new(lmdber.clone(), "dtss.", None, false)
537                .map_err(|e| DBError::DatabaseError(format!("SuberError: {}", e)))?,
538
539            rpys: SerderSuber::new(lmdber.clone(), "rpys", None, false)
540                .map_err(|e| DBError::DatabaseError(format!("SuberError: {}", e)))?,
541
542            sdts: CesrSuber::new(lmdber.clone(), "sdts", None, false)
543                .map_err(|e| DBError::DatabaseError(format!("SuberError: {}", e)))?,
544
545            ssgs: CatCesrIoSetSuber::new(
546                lmdber.clone(),
547                "ssgs.",
548                vec!["siger".to_string()],
549                None,
550                false,
551            )
552            .map_err(|e| DBError::DatabaseError(format!("SuberError: {}", e)))?,
553
554            scgs: CatCesrIoSetSuber::new(
555                lmdber.clone(),
556                "scgs.",
557                vec!["verfer".to_string(), "cigar".to_string()],
558                None,
559                false,
560            )
561            .map_err(|e| DBError::DatabaseError(format!("SuberError: {}", e)))?,
562
563            rpes: CesrIoSetSuber::new(lmdber.clone(), "rpes.", None, false)
564                .map_err(|e| DBError::DatabaseError(format!("SuberError: {}", e)))?,
565
566            // Initialize the aess sub database
567            aess: Suber::new(lmdber.clone(), "aess.", None, false)
568                .map_err(|e| DBError::DatabaseError(format!("SuberError: {}", e)))?,
569
570            // Initialize the sigs sub database
571            sigs: DupSuber::new(lmdber.clone(), "sigs.", None, false)
572                .map_err(|e| DBError::DatabaseError(format!("SuberError: {}", e)))?,
573
574            // Initialize the wigs sub database
575            wigs: DupSuber::new(lmdber.clone(), "wigs.", None, false)
576                .map_err(|e| DBError::DatabaseError(format!("SuberError: {}", e)))?,
577
578            // Initialize the wits sub database
579            wits: IoDupSuber::new(lmdber.clone(), "wits.", None, false)
580                .map_err(|e| DBError::DatabaseError(format!("SuberError: {}", e)))?,
581
582            // Initialize the wits sub database
583            rcts: DupSuber::new(lmdber.clone(), "rcts.", None, false)
584                .map_err(|e| DBError::DatabaseError(format!("SuberError: {}", e)))?,
585
586            // Initialize the wits sub database
587            vrcs: DupSuber::new(lmdber.clone(), "vrcs.", None, false)
588                .map_err(|e| DBError::DatabaseError(format!("SuberError: {}", e)))?,
589
590            // Initialize the states sub database
591            states: Komer::new(lmdber.clone(), "stts.", SerialKind::Json)
592                .map_err(|e| DBError::DatabaseError(format!("SuberError: {}", e)))?,
593
594            ends: Komer::new(lmdber.clone(), "ends.", SerialKind::Json)
595                .map_err(|e| DBError::DatabaseError(format!("SuberError: {}", e)))?,
596
597            locs: Komer::new(lmdber.clone(), "locs.", SerialKind::Json)
598                .map_err(|e| DBError::DatabaseError(format!("SuberError: {}", e)))?,
599
600            habs: Komer::new(lmdber.clone(), "habs.", SerialKind::Json)
601                .map_err(|e| DBError::DatabaseError(format!("SuberError: {}", e)))?,
602
603            names: Suber::new(lmdber.clone(), "names.", None, false)
604                .map_err(|e| DBError::DatabaseError(format!("SuberError: {}", e)))?,
605
606            eans: CesrSuber::new(lmdber.clone(), "eans.", None, false)
607                .map_err(|e| DBError::DatabaseError(format!("SuberError: {}", e)))?,
608
609            lans: CesrSuber::new(lmdber.clone(), "lans.", None, false)
610                .map_err(|e| DBError::DatabaseError(format!("SuberError: {}", e)))?,
611
612            pses: IoDupSuber::new(lmdber.clone(), "pses.", None, false)
613                .map_err(|e| DBError::DatabaseError(format!("SuberError: {}", e)))?,
614
615            pwes: IoDupSuber::new(lmdber.clone(), "pwes.", None, false)
616                .map_err(|e| DBError::DatabaseError(format!("SuberError: {}", e)))?,
617
618            ooes: IoDupSuber::new(lmdber.clone(), "ooes.", None, false)
619                .map_err(|e| DBError::DatabaseError(format!("SuberError: {}", e)))?,
620
621            ldes: IoDupSuber::new(lmdber.clone(), "ldes.", None, false)
622                .map_err(|e| DBError::DatabaseError(format!("SuberError: {}", e)))?,
623
624            misfits: IoDupSuber::new(lmdber.clone(), "mfes.", None, false)
625                .map_err(|e| DBError::DatabaseError(format!("SuberError: {}", e)))?,
626
627            delegables: IoDupSuber::new(lmdber.clone(), "dees.", None, false)
628                .map_err(|e| DBError::DatabaseError(format!("SuberError: {}", e)))?,
629
630            ures: IoDupSuber::new(lmdber.clone(), "ures.", None, false)
631                .map_err(|e| DBError::DatabaseError(format!("SuberError: {}", e)))?,
632
633            uwes: IoDupSuber::new(lmdber.clone(), "uwes.", None, false)
634                .map_err(|e| DBError::DatabaseError(format!("SuberError: {}", e)))?,
635        };
636
637        Ok(baser)
638    }
639    pub fn get_ke_last<K>(&self, key: K) -> Result<Option<String>, KERIError>
640    where
641        K: AsRef<[u8]>,
642    {
643        // Use the kels OnIoDupSuber to get the last inserted duplicate value
644        match self.kels.get_io_dup_val_last::<K, Vec<u8>>(&[key]) {
645            Ok(Some(val_bytes)) => {
646                // Convert bytes to String (assuming UTF-8 encoded digest)
647                match String::from_utf8(val_bytes) {
648                    Ok(digest) => Ok(Some(digest)),
649                    Err(e) => Err(KERIError::DeserializationError(format!(
650                        "Failed to decode digest as UTF-8: {}",
651                        e
652                    ))),
653                }
654            }
655            Ok(None) => Ok(None),
656            Err(e) => {
657                // Convert SuberError to DBError - adjust this based on your DBError enum
658                Err(KERIError::DatabaseError(format!("SuberError: {}", e)))
659            }
660        }
661    }
662
663    pub fn get_evt<K>(&self, key: K) -> Result<Option<Vec<u8>>, KERIError>
664    where
665        K: AsRef<[u8]>,
666    {
667        // Convert the key to the format expected by the evts database
668        let db_key = self.evts.to_key(&[key], false);
669
670        // Call the LMDBer's get_val method directly
671        self.lmdber
672            .get_val(&self.evts.base.sdb, &db_key)
673            .map_err(|e| KERIError::DatabaseError(format!("LMDBer error: {}", e)))
674    }
675
676    /// Check if database is opened
677    pub fn opened(&self) -> bool {
678        self.lmdber.opened()
679    }
680
681    /// Get name of database
682    pub fn name(&self) -> String {
683        self.lmdber.name()
684    }
685
686    /// Get database path
687    pub fn path(&self) -> Option<PathBuf> {
688        self.lmdber.path()
689    }
690
691    /// Close the database
692    /// Check if database is temporary
693    pub fn temp(&self) -> bool {
694        self.lmdber.temp()
695    }
696
697    /// Create a key to access the pubs database with prefix and rotation index
698    pub fn ri_key(pre: &str, ri: u64) -> String {
699        format!("{}.{:032x}", pre, ri)
700    }
701
702    pub fn fetch_all_sealing_event_by_event_seal(
703        &self,
704        _pre: &str,
705        _anchor: &str,
706    ) -> Result<bool, DBError> {
707        Ok(false)
708    }
709
710    /// The last (not superseded) event in `pre`'s KEL at or after `sn` that
711    /// anchors `seal` and is fully witnessed, i.e. has at least `toad` witness
712    /// signatures (keripy: db/basing.py Baser.fetchLastSealingEventByEventSeal).
713    ///
714    /// keripy reads `toad` from the KEL's current key state
715    /// (`Baser.fullyWitnessed`); the caller passes it because the Baser does
716    /// not hold the Kevers here. Only an exact `{i, s, d}` event seal matches.
717    pub fn fetch_last_sealing_event_by_event_seal(
718        &self,
719        pre: &str,
720        seal: &SealEvent,
721        sn: u64,
722        toad: usize,
723    ) -> Result<Option<SerderKERI>, KERIError> {
724        let mut sn = sn;
725        while let Some(said) = self.get_ke_last(sn_key(pre, sn))? {
726            if let Some(raw) = self.get_evt(dg_key(pre, &said))? {
727                let serder = SerderKERI::from_raw(&raw, None)
728                    .map_err(|e| KERIError::ValueError(format!("stored event {}: {}", said, e)))?;
729                let anchors = serder.seals().unwrap_or_default().iter().any(|eseal| {
730                    eseal.len() == 3
731                        && eseal.keys().map(String::as_str).eq(["i", "s", "d"])
732                        && eseal.get("i").and_then(|v| v.as_str()) == Some(seal.i.as_str())
733                        && eseal.get("s").and_then(|v| v.as_str()) == Some(seal.s.as_str())
734                        && eseal.get("d").and_then(|v| v.as_str()) == Some(seal.d.as_str())
735                });
736                if anchors && self.wig_count(pre, &said)? >= toad {
737                    return Ok(Some(serder));
738                }
739            }
740            sn += 1;
741        }
742        Ok(None)
743    }
744
745    /// Number of witness signatures stored for event `said` of `pre`.
746    pub fn wig_count(&self, pre: &str, said: &str) -> Result<usize, KERIError> {
747        Ok(self
748            .wigs
749            .get::<_, Vec<u8>>(&[&dg_key(pre, said)])
750            .map_err(|e| KERIError::DatabaseError(format!("wigs: {}", e)))?
751            .len())
752    }
753
754    /// The accepted event of `pre` at `sn` as a message with all its
755    /// attachments (signatures, witness signatures, source seal couple, first
756    /// seen couple), as keripy `cloneEvtMsg` writes it.
757    pub fn clone_evt_msg_at(&self, pre: &str, sn: u64) -> Result<Vec<u8>, KERIError> {
758        let said = self
759            .get_ke_last(sn_key(pre, sn))?
760            .ok_or_else(|| KERIError::MissingEntryError(format!("no event for {} at sn {}", pre, sn)))?;
761        let fner = self
762            .fons
763            .get(&[&dg_key(pre, &said)])
764            .map_err(|e| KERIError::DatabaseError(format!("fons: {}", e)))?
765            .ok_or_else(|| KERIError::MissingEntryError(format!("no first seen number for {}", said)))?;
766        self.clone_evt_msg(pre, fner.num() as u64, &said)
767            .map_err(|e| KERIError::DatabaseError(format!("clone {}: {}", said, e)))
768    }
769
770    /// Returns an iterator of first seen event messages with attachments for the
771    /// identifier prefix `pre` starting at first seen order number, `fn_num`.
772    /// Essentially a replay in first seen order with attachments.
773    ///
774    /// # Parameters
775    /// * `pre` - Identifier prefix as string
776    /// * `fn_num` - Optional first seen number to resume replay. Default is 0
777    ///
778    /// # Returns
779    /// * `Result<Vec<Vec<u8>>, DBError>` - Collection of messages with prefix `pre` starting at `fn_num`
780    pub fn clone_pre_iter(&self, pre: &str, fn_num: Option<u64>) -> Result<Vec<Vec<u8>>, DBError> {
781        let start_fn = fn_num.unwrap_or(0);
782        let mut msgs = Vec::new();
783
784        // We need to get items from the fels database for the given prefix
785        // starting at the specified first seen ordinal number
786        let key_prefix = pre.as_bytes(); // Prefix for key search
787
788        // Get all items with this prefix
789        let mut items = Vec::new();
790
791        // Use the low-level interface to get items from the fels database
792        let on_items: Vec<(Vec<Vec<u8>>, u64, Vec<u8>)> = self
793            .fels
794            .get_on_item_iter(&[&key_prefix], start_fn as u32)
795            .map_err(|e| DBError::DatabaseError(format!("Error getting items: {}", e)))?;
796
797        for (ckey, cn, cval) in on_items {
798            // Check if the key starts with our prefix
799            if ckey.starts_with(&[pre.as_bytes().to_vec()]) && cn >= start_fn {
800                // Convert the digest value to a string
801                let dig = String::from_utf8_lossy(&cval).to_string();
802                items.push((ckey.to_vec(), cn, dig));
803            }
804        }
805
806        // Now process each item to get the serialized message
807        for (_, fn_num, dig) in items {
808            match self.clone_evt_msg(pre, fn_num, &dig) {
809                Ok(msg) => msgs.push(msg),
810                Err(_) => continue, // Skip this event if there's an error, as in Python implementation
811            }
812        }
813
814        Ok(msgs)
815    }
816    /// Recursively clone delegation chain from AID of Kever if one exists.
817    ///
818    /// This method yields messages in the correct order: first the delegator's
819    /// delegation chain (if any), then all events from the delegator's key event log.
820    ///
821    /// # Parameters
822    /// * `kever` - Kever from which to clone the delegator's AID
823    ///
824    /// # Returns
825    /// * `Result<Vec<Vec<u8>>, DBError>` - Collection of messages representing the delegation chain
826    pub fn clone_delegation(
827        &self,
828        kever: &Kever,
829        kevers: &HashMap<String, Kever>,
830    ) -> Result<Vec<Vec<u8>>, DBError> {
831        let mut msgs = Vec::new();
832
833        // Check if this kever is delegated and has a delegator in our kevers
834        if kever.delegated {
835            if let Some(ref delpre) = kever.delpre {
836                if let Some(dkever) = kevers.get(delpre) {
837                    // Recursively clone the delegator's delegation chain first
838                    let delegator_msgs = self.clone_delegation(dkever, kevers)?;
839                    msgs.extend(delegator_msgs);
840
841                    // Then clone all events from the delegator's prefix starting from fn=0
842                    let delegator_events = self.clone_pre_iter(delpre, Some(0))?;
843                    msgs.extend(delegator_events);
844                }
845            }
846        }
847
848        Ok(msgs)
849    }
850
851    /// Clones Event as Serialized CESR Message with Body and attached Foot
852    ///
853    /// # Parameters
854    /// * `pre` - Identifier prefix of event
855    /// * `fn_num` - First seen number (ordinal) of event
856    /// * `dig` - Digest of event
857    ///
858    /// # Returns
859    /// * `Result<Vec<u8>, DBError>` - Message body with attachments
860    pub fn clone_evt_msg(&self, pre: &str, fn_num: u64, dig: &str) -> Result<Vec<u8>, DBError> {
861        // Initialize message and attachments
862        let mut msg = Vec::<u8>::new(); // message
863        let mut atc = Vec::<u8>::new(); // attachments
864
865        // Get the event message
866        let dg_key = dg_key(pre, dig);
867        let raw = self
868            .evts
869            .get::<_, Vec<u8>>(&[&dg_key])
870            .map_err(|_| DBError::MissingEntryError(format!("Missing event for dig={}.", dig)))?;
871
872        // Extend message with raw event data
873        msg.extend_from_slice(&raw.unwrap_or_default());
874
875        // Add indexed signatures to attachments
876        let sigs = self
877            .sigs
878            .get::<_, Vec<u8>>(&[&dg_key])
879            .map_err(|_| DBError::MissingEntryError(format!("Missing sigs for dig={}.", dig)))?;
880
881        // Add counter for controller indexed signatures
882        let counter = BaseCounter::from_code_and_count(
883            Some(ctr_dex_1_0::CONTROLLER_IDX_SIGS),
884            Some(sigs.len() as u64),
885            Some("1.0"),
886        )
887        .unwrap()
888        .qb64b();
889        atc.extend_from_slice(&counter);
890
891        // Add each signature to attachments
892        for sig in sigs {
893            atc.extend_from_slice(&sig);
894        }
895
896        // Add indexed witness signatures to attachments if they exist
897        if let Ok(wigs) = self.wigs.get::<_, Vec<u8>>(&[&dg_key]) {
898            if !wigs.is_empty() {
899                // Add counter for witness indexed signatures
900                let counter = BaseCounter::from_code_and_count(
901                    Some(ctr_dex_1_0::WITNESS_IDX_SIGS),
902                    Some(wigs.len() as u64),
903                    Some("1.0"),
904                )
905                .unwrap()
906                .qb64b();
907                atc.extend_from_slice(&counter);
908
909                // Add each witness signature to attachments
910                for wig in wigs {
911                    atc.extend_from_slice(&wig);
912                }
913            }
914        }
915
916        // Add authorizer (delegator/issuer) source seal event couple to attachments
917        if let Ok(Some(couple)) = self.aess.get::<_, Option<Vec<u8>>>(&[&dg_key]) {
918            // Add counter for seal source couples
919            let counter = BaseCounter::from_code_and_count(
920                Some(ctr_dex_1_0::SEAL_SOURCE_COUPLES),
921                Some(1),
922                Some("1.0"),
923            )
924            .unwrap()
925            .qb64b();
926            atc.extend_from_slice(&counter);
927            atc.extend_from_slice(&couple.unwrap());
928        }
929
930        // Add trans endorsement quadruples to attachments (not controller)
931        if let Ok(quads) = self.vrcs.get::<_, Vec<u8>>(&[&dg_key]) {
932            if !quads.is_empty() {
933                // Add counter for trans receipt quadruples
934                let counter = BaseCounter::from_code_and_count(
935                    Some(ctr_dex_1_0::TRANS_RECEIPT_QUADRUPLES),
936                    Some(quads.len() as u64),
937                    Some("1.0"),
938                )
939                .unwrap()
940                .qb64b();
941                atc.extend_from_slice(&counter);
942
943                // Add each quadruple to attachments
944                for quad in quads {
945                    atc.extend_from_slice(&quad);
946                }
947            }
948        }
949
950        // Add nontrans endorsement couples to attachments (not witnesses)
951        if let Ok(coups) = self.rcts.get::<_, Vec<u8>>(&[&dg_key]) {
952            if !coups.is_empty() {
953                // Add counter for non-trans receipt couples
954                let counter = BaseCounter::from_code_and_count(
955                    Some(ctr_dex_1_0::NON_TRANS_RECEIPT_COUPLES),
956                    Some(coups.len() as u64),
957                    Some("1.0"),
958                )
959                .unwrap()
960                .qb64b();
961                atc.extend_from_slice(&counter);
962
963                // Add each couple to attachments
964                for coup in coups {
965                    atc.extend_from_slice(&coup);
966                }
967            }
968        }
969
970        // Add first seen replay couple to attachments
971        let dts = self.dtss.get::<_, Vec<u8>>(&[&dg_key]).map_err(|_| {
972            DBError::MissingEntryError(format!("Missing datetime for dig={}.", dig))
973        })?;
974
975        // Add counter for first seen replay couples
976        let counter = BaseCounter::from_code_and_count(
977            Some(ctr_dex_1_0::FIRST_SEEN_REPLAY_COUPLES),
978            Some(1),
979            Some("1.0"),
980        )
981        .unwrap()
982        .qb64b();
983        atc.extend_from_slice(&counter);
984
985        // Add first seen number
986        let fn_bytes = Number::from_num_and_code(&BigUint::from(fn_num), num_dex::HUGE)
987            .unwrap()
988            .qb64b();
989        atc.extend_from_slice(&fn_bytes);
990
991        // Add datetime
992        let dt = DateTime::parse_from_rfc3339(&String::from_utf8_lossy(&dts[0]))
993            .map_err(|e| DBError::ValueError(format!("{}", e)))?;
994        let dater = Dater::from_dt(DateTime::from(dt)).qb64b();
995        atc.extend_from_slice(&dater);
996
997        // Check if attachments size is valid (multiple of 4)
998        if atc.len() % 4 != 0 {
999            return Err(DBError::ValueError(format!(
1000                "Invalid attachments size={}, nonintegral quadlets.",
1001                atc.len()
1002            )));
1003        }
1004
1005        // Prepend pipelining counter to attachments
1006        let pcnt = BaseCounter::from_code_and_count(
1007            Some(ctr_dex_1_0::ATTACHMENT_GROUP),
1008            Some((atc.len() / 4) as u64),
1009            Some("1.0"),
1010        )
1011        .unwrap()
1012        .qb64b();
1013        msg.extend_from_slice(&pcnt);
1014
1015        // Add attachments to message
1016        msg.extend_from_slice(&atc);
1017
1018        Ok(msg)
1019    }
1020
1021    /// Returns iterator of all (pre, fn, dig) triples in first seen order for
1022    /// all events for all prefixes in database. Items are sorted by
1023    /// fnKey(pre, fn) where fn is first seen order number int.
1024    /// Returns all First Seen Event Logs FELs.
1025    ///
1026    /// Returned items are triples of (pre, fn, dig): Where pre is identifier prefix,
1027    /// fn is first seen order number int and dig is event digest for lookup
1028    /// in .evts sub db.
1029    ///
1030    /// # Returns
1031    /// * `Result<Vec<(String, u64, String)>, DBError>` - Collection of (prefix, fn, digest) triples
1032    pub fn get_fel_item_all_pre_iter(&self) -> Result<Vec<(String, u64, String)>, DBError> {
1033        let mut items = Vec::new();
1034        // Get all items from the fels database starting from the beginning (empty key)
1035        let on_items: Vec<(Vec<Vec<u8>>, u64, Vec<u8>)> = self
1036            .fels
1037            .get_on_item_iter(&[b""], 0)
1038            .map_err(|e| DBError::DatabaseError(format!("Error getting all FEL items: {}", e)))?;
1039
1040        for (ckey, cn, cval) in on_items {
1041            // Extract the prefix from the composite key
1042            // The key format is typically [prefix_bytes, fn_bytes]
1043            // We need to extract just the prefix part
1044            if let Some(prefix_bytes) = ckey.first() {
1045                let pre = String::from_utf8_lossy(prefix_bytes).to_string();
1046                let fn_num = cn;
1047                let dig = String::from_utf8_lossy(&cval).to_string();
1048
1049                items.push((pre, fn_num, dig));
1050            }
1051        }
1052
1053        // Sort by first seen order number to ensure proper ordering
1054        items.sort_by(|a, b| a.1.cmp(&b.1));
1055
1056        Ok(items)
1057    }
1058
1059    /// Returns iterator of first seen event messages with attachments for all
1060    /// identifier prefixes starting at the beginning of the database.
1061    /// Essentially a replay in first seen order with attachments of entire
1062    /// set of FELs (First Seen Event Logs).
1063    ///
1064    /// # Returns
1065    /// * `Result<Vec<Vec<u8>>, DBError>` - Collection of all event messages with attachments
1066    pub fn clone_all_pre_iter(&self) -> Result<Vec<Vec<u8>>, DBError> {
1067        let mut msgs = Vec::new();
1068
1069        // Get all (pre, fn, dig) triples from the FEL database
1070        let fel_items = self.get_fel_item_all_pre_iter()?;
1071
1072        // For each item, try to clone the event message
1073        for (pre, fn_num, dig) in fel_items {
1074            match self.clone_evt_msg(&pre, fn_num, &dig) {
1075                Ok(msg) => msgs.push(msg),
1076                Err(_) => continue, // Skip this event if there's an error, as in Python implementation
1077            }
1078        }
1079
1080        Ok(msgs)
1081    }
1082    /// Return count of signatures at key.
1083    /// Uses dgKey format for the key.
1084    /// Returns zero if no entry at key.
1085    ///
1086    /// # Parameters
1087    /// * `key` - The key to count signatures for (should be in dgKey format)
1088    ///
1089    /// # Returns
1090    /// * `Result<usize, DBError>` - Count of signatures, zero if no entry
1091    pub fn cnt_sigs(&self, key: &[u8]) -> Result<usize, DBError> {
1092        self.sigs
1093            .cnt(&[key])
1094            .map_err(|e| DBError::DatabaseError(format!("Error counting signatures: {}", e)))
1095    }
1096    pub fn get_sigs_iter(
1097        &self,
1098        key: &[u8],
1099    ) -> Result<impl Iterator<Item = Result<Vec<u8>, DBError>>, DBError> {
1100        let iter = self.sigs.get_iter::<_, Vec<u8>>(&[key]).map_err(|e| {
1101            DBError::DatabaseError(format!("Error getting signatures iterator: {}", e))
1102        })?;
1103
1104        // Collect into a Vec to avoid lifetime issues with the mapped iterator
1105        let results: Vec<Result<Vec<u8>, DBError>> = iter
1106            .map(|result| {
1107                result.map_err(|e| {
1108                    DBError::DatabaseError(format!("Error deserializing signature: {}", e))
1109                })
1110            })
1111            .collect();
1112
1113        Ok(results.into_iter())
1114    }
1115
1116    /// Fetch transferable signature groups from the ssgs database
1117    ///
1118    /// # Parameters
1119    /// * `saider` - SAID for the reply to which signatures are attached
1120    /// * `snh` - Optional sequence number hex string for filtering
1121    ///
1122    /// # Returns
1123    /// * `Ok(Vec<(Prefixer, Seqner, Diger, Vec<Siger>)>)` - List of signature groups
1124    /// * `Err(KERIError)` - On database error or parsing failure
1125    pub fn fetch_tsgs(
1126        &self,
1127        saider: Saider,
1128        snh: Option<&str>,
1129    ) -> Result<Vec<(Prefixer, Seqner, Diger, Vec<Siger>)>, KERIError> {
1130        let mut tsgs = Vec::new();
1131        let mut sigers = Vec::new();
1132        let mut old: Option<Vec<Vec<u8>>> = None;
1133
1134        // Get items from ssgs database
1135        let items = self
1136            .ssgs
1137            .get_item_iter(&[saider.qb64().as_bytes(), b""], false)
1138            .map_err(|e| {
1139                KERIError::DatabaseError(format!("Failed to get signature items: {}", e))
1140            })?;
1141
1142        for (keys, siger_matters) in items {
1143            if keys.len() < 2 {
1144                continue;
1145            }
1146
1147            let triple = keys[1..].to_vec(); // Skip the saider key, take the triple
1148
1149            if Some(&triple) != old.as_ref() {
1150                // New signature group
1151                if let Some(snh) = snh {
1152                    if triple.len() >= 2 {
1153                        let seq_str = String::from_utf8_lossy(&triple[1]);
1154                        if seq_str.as_ref() > snh {
1155                            // Use .as_ref() to convert Cow to &str
1156                            break; // Only process lower sequence numbers
1157                        }
1158                    }
1159                }
1160
1161                if !sigers.is_empty() && old.is_some() {
1162                    // Append the previous signature group
1163                    if let Some(old_triple) = &old {
1164                        let (prefixer, seqner, diger) = self.klasify_triple(old_triple)?;
1165                        tsgs.push((prefixer, seqner, diger, sigers.clone()));
1166                        sigers.clear();
1167                    }
1168                }
1169                old = Some(triple);
1170            }
1171
1172            // Convert Matter instances to Siger
1173            for siger_matter in siger_matters {
1174                if let Some(siger) = siger_matter.as_any().downcast_ref::<Siger>() {
1175                    sigers.push(siger.clone());
1176                }
1177            }
1178        }
1179
1180        // Handle the last group
1181        if !sigers.is_empty() && old.is_some() {
1182            if let Some(old_triple) = &old {
1183                let (prefixer, seqner, diger) = self.klasify_triple(old_triple)?;
1184                tsgs.push((prefixer, seqner, diger, sigers));
1185            }
1186        }
1187
1188        Ok(tsgs)
1189    }
1190
1191    /// Convert a triple of serialized values to Prefixer, Seqner, Diger instances
1192    /// Rust implementation of the klasify function for the specific case of (Prefixer, Seqner, Diger)
1193    ///
1194    /// # Parameters
1195    /// * `triple` - Vector of byte vectors representing [prefixer, seqner, diger]
1196    ///
1197    /// # Returns
1198    /// * `Ok((Prefixer, Seqner, Diger))` - Converted instances
1199    /// * `Err(KERIError)` - On conversion failure
1200    fn klasify_triple(&self, triple: &[Vec<u8>]) -> Result<(Prefixer, Seqner, Diger), KERIError> {
1201        if triple.len() != 3 {
1202            return Err(KERIError::ValidationError(
1203                "Expected triple of values".to_string(),
1204            ));
1205        }
1206
1207        let prefixer = Prefixer::from_qb64(&String::from_utf8_lossy(&triple[0]))
1208            .map_err(|e| KERIError::ValidationError(format!("Failed to create Prefixer: {}", e)))?;
1209
1210        let seqner = Seqner::from_snh(&String::from_utf8_lossy(&triple[1]))
1211            .map_err(|e| KERIError::ValidationError(format!("Failed to create Seqner: {}", e)))?;
1212
1213        let diger = Diger::from_qb64(&String::from_utf8_lossy(&triple[2]))
1214            .map_err(|e| KERIError::ValidationError(format!("Failed to create Diger: {}", e)))?;
1215
1216        Ok((prefixer, seqner, diger))
1217    }
1218}