Skip to main content

libkeri/keri/core/eventing/
state.rs

1use crate::cesr::number::Number;
2use crate::cesr::tholder::{Tholder, TholderSith};
3use crate::cesr::{Versionage, VERSION};
4use crate::keri::core::serdering::SadValue;
5use crate::keri::db::basing::{KeyStateRecord, StateEERecord};
6use crate::keri::{KERIError, Kinds};
7use chrono;
8use num_bigint::BigUint;
9use std::error::Error;
10
11/// Builder for creating key state event records
12pub struct StateEventBuilder {
13    pre: String,         // Identifier prefix qb64
14    sn: u64,             // Sequence number of latest event
15    pig: String,         // SAID qb64 of prior event
16    dig: String,         // SAID qb64 of latest (current) event
17    fn_: u64,            // First seen ordinal number of latest event
18    eilk: String,        // Event type (ilk) of latest event
19    keys: Vec<String>,   // qb64 signing keys
20    eevt: StateEERecord, // Latest establishment event
21
22    stamp: Option<String>,      // ISO-8601 timestamp
23    sith: Option<TholderSith>,  // Current signing threshold
24    ndigs: Vec<String>,         // Current signing key digests qb64
25    nsith: Option<TholderSith>, // Next signing threshold
26    toad: Option<usize>,        // Witness threshold
27    wits: Vec<String>,          // Witness identifier prefixes qb64
28    cnfg: Vec<String>,          // Configuration trait strings
29    dpre: Option<String>,       // Delegator prefix if any
30    version: String,            // KERI protocol version string
31    kind: String,               // Serialization kind
32    intive: bool,               // True to use int thresholds instead of hex
33}
34
35impl StateEventBuilder {
36    /// Create a new StateEventBuilder with required fields
37    pub fn new(
38        pre: String,
39        sn: u64,
40        pig: String,
41        dig: String,
42        fn_: u64,
43        eilk: String,
44        keys: Vec<String>,
45        eevt: StateEERecord,
46    ) -> Self {
47        StateEventBuilder {
48            pre,
49            sn,
50            pig,
51            dig,
52            fn_,
53            eilk,
54            keys,
55            eevt,
56            stamp: None,
57            sith: None,
58            ndigs: Vec::new(),
59            nsith: None,
60            toad: None,
61            wits: Vec::new(),
62            cnfg: Vec::new(),
63            dpre: None,
64            version: VERSION.to_string(),
65            kind: Kinds::Json.to_string(),
66            intive: false,
67        }
68    }
69
70    /// Set the timestamp
71    pub fn with_stamp(mut self, stamp: String) -> Self {
72        self.stamp = Some(stamp);
73        self
74    }
75
76    /// Set the signing threshold
77    pub fn with_sith(mut self, sith: TholderSith) -> Self {
78        self.sith = Some(sith);
79        self
80    }
81
82    /// Set the next key digests
83    pub fn with_ndigs(mut self, ndigs: Vec<String>) -> Self {
84        self.ndigs = ndigs;
85        self
86    }
87
88    /// Set the next signing threshold
89    pub fn with_nsith(mut self, nsith: TholderSith) -> Self {
90        self.nsith = Some(nsith);
91        self
92    }
93
94    /// Set the witness threshold
95    pub fn with_toad(mut self, toad: usize) -> Self {
96        self.toad = Some(toad);
97        self
98    }
99
100    /// Set the witnesses
101    pub fn with_wits(mut self, wits: Vec<String>) -> Self {
102        self.wits = wits;
103        self
104    }
105
106    /// Set the configuration traits
107    pub fn with_cnfg(mut self, cnfg: Vec<String>) -> Self {
108        self.cnfg = cnfg;
109        self
110    }
111
112    /// Set the delegator prefix
113    pub fn with_dpre(mut self, dpre: String) -> Self {
114        self.dpre = Some(dpre);
115        self
116    }
117
118    /// Set the version
119    pub fn with_version(mut self, version: String) -> Self {
120        self.version = version;
121        self
122    }
123
124    /// Set the serialization kind
125    pub fn with_kind(mut self, kind: String) -> Self {
126        self.kind = kind;
127        self
128    }
129
130    /// Set whether to use integer thresholds
131    pub fn with_intive(mut self, intive: bool) -> Self {
132        self.intive = intive;
133        self
134    }
135
136    /// Build the KeyStateRecord
137    pub fn build(self) -> Result<KeyStateRecord, Box<dyn Error>> {
138        // Validate sequence numbers
139        let sner = Number::from_num(&BigUint::from(self.sn))?;
140        let fner = Number::from_num(&BigUint::from(self.fn_))?;
141
142        // Validate event type
143        if !matches!(self.eilk.as_str(), "icp" | "rot" | "ixn" | "dip" | "drt") {
144            return Err(Box::new(KERIError::ValueError(format!(
145                "Invalid event type et={} in key state.",
146                self.eilk
147            ))));
148        }
149
150        // Generate timestamp if not provided
151        let stamp = self.stamp.unwrap_or_else(|| {
152            chrono::Utc::now()
153                .format("%Y-%m-%dT%H:%M:%S%.6fZ")
154                .to_string()
155        });
156
157        // Calculate default sith if not provided
158        let tholder = if let Some(sith) = self.sith {
159            Tholder::new(None, None, Some(sith))?
160        } else {
161            let default_sith = format!(
162                "{:x}",
163                std::cmp::max(1, (self.keys.len() as f64 / 2.0).ceil() as usize)
164            );
165            Tholder::new(
166                None,
167                None,
168                Some(TholderSith::from_sad_value(SadValue::String(default_sith))?),
169            )?
170        };
171
172        // Validate sith
173        if let Some(num) = tholder.num() {
174            if num < 1 {
175                return Err(Box::new(KERIError::ValueError(format!(
176                    "Invalid sith = {} less than 1.",
177                    num
178                ))));
179            }
180        }
181        if tholder.size() > self.keys.len() {
182            return Err(Box::new(KERIError::ValueError(format!(
183                "Invalid sith = {:?} for keys = {:?}",
184                tholder.sith(),
185                self.keys
186            ))));
187        }
188
189        // Calculate default nsith if not provided
190        let ntholder = if let Some(nsith) = self.nsith {
191            Tholder::new(None, None, Some(nsith))?
192        } else {
193            let default_nsith = format!(
194                "{:x}",
195                std::cmp::max(0, (self.ndigs.len() as f64 / 2.0).ceil() as usize)
196            );
197            Tholder::new(
198                None,
199                None,
200                Some(TholderSith::from_sad_value(SadValue::String(
201                    default_nsith,
202                ))?),
203            )?
204        };
205
206        // Validate nsith
207        if ntholder.size() > self.ndigs.len() {
208            return Err(Box::new(KERIError::ValueError(format!(
209                "Invalid nsith = {:?} for ndigs = {:?}",
210                ntholder.sith(),
211                self.ndigs
212            ))));
213        }
214
215        // Check for witness duplicates
216        let wit_set: std::collections::HashSet<&String> = self.wits.iter().collect();
217        if wit_set.len() != self.wits.len() {
218            return Err(Box::new(KERIError::ValueError(format!(
219                "Invalid wits = {:?}, has duplicates.",
220                self.wits
221            ))));
222        }
223
224        // Calculate default toad if not provided
225        let toader = if let Some(toad) = self.toad {
226            Number::from_num(&BigUint::from(toad))?
227        } else {
228            if self.wits.is_empty() {
229                Number::from_num(&BigUint::from(0u32))?
230            } else {
231                let default_toad = std::cmp::max(1, (self.wits.len() as f64 / 2.0).ceil() as usize);
232                Number::from_num(&BigUint::from(default_toad))?
233            }
234        };
235
236        // Validate toad
237        if !self.wits.is_empty() {
238            if toader.num() < 1 || toader.num() as usize > self.wits.len() {
239                return Err(Box::new(KERIError::ValueError(format!(
240                    "Invalid toad = {} for wits = {:?}",
241                    toader.num(),
242                    self.wits
243                ))));
244            }
245        } else {
246            if toader.num() != 0 {
247                return Err(Box::new(KERIError::ValueError(format!(
248                    "Invalid toad = {} for empty wits",
249                    toader.num()
250                ))));
251            }
252        }
253
254        // Validate eevt
255        let eesner = Number::from_numh(&self.eevt.s)?;
256
257        // Validate cuts (witness removals)
258        let cuts = self.eevt.br.clone().unwrap_or_default();
259        let cut_set: std::collections::HashSet<&String> = cuts.iter().collect();
260        if cut_set.len() != cuts.len() {
261            return Err(Box::new(KERIError::ValueError(format!(
262                "Invalid cuts = {:?}, has duplicates in latest est event.",
263                cuts
264            ))));
265        }
266
267        // Validate adds (witness additions)
268        let adds = self.eevt.ba.clone().unwrap_or_default();
269        let add_set: std::collections::HashSet<&String> = adds.iter().collect();
270        if add_set.len() != adds.len() {
271            return Err(Box::new(KERIError::ValueError(format!(
272                "Invalid adds = {:?}, has duplicates in latest est event.",
273                adds
274            ))));
275        }
276
277        // Check for intersection between cuts and adds
278        let mut intersect = false;
279        for cut in &cuts {
280            if add_set.contains(&cut) {
281                intersect = true;
282                break;
283            }
284        }
285        if intersect {
286            return Err(Box::new(KERIError::ValueError(format!(
287                "Intersecting cuts = {:?} and adds = {:?} in latest est event.",
288                cuts, adds
289            ))));
290        }
291
292        // Define constant for max integer threshold
293        const MAX_INT_THOLD: usize = 2 ^ 32 - 1;
294
295        // Build the KeyStateRecord
296        let ksr = KeyStateRecord {
297            vn: Versionage::from(self.version).to_vec(),
298            i: self.pre,
299            s: sner.numh(),
300            p: self.pig,
301            d: self.dig,
302            f: fner.numh(),
303            dt: stamp,
304            et: self.eilk,
305            kt: if self.intive && tholder.num().is_some() && tholder.num().unwrap() <= MAX_INT_THOLD
306            {
307                tholder.num().unwrap().to_string()
308            } else {
309                tholder.sith().to_string()
310            },
311            k: self.keys,
312            nt: if self.intive
313                && ntholder.num().is_some()
314                && ntholder.num().unwrap() <= MAX_INT_THOLD
315            {
316                ntholder.num().unwrap().to_string()
317            } else {
318                ntholder.sith().to_string()
319            },
320            n: self.ndigs,
321            bt: if self.intive && toader.num() <= MAX_INT_THOLD as u128 {
322                toader.num().to_string()
323            } else {
324                toader.numh()
325            },
326            b: self.wits,
327            c: self.cnfg,
328            ee: self.eevt,
329            di: self.dpre.unwrap_or_default(),
330        };
331
332        Ok(ksr)
333    }
334}
335
336#[cfg(test)]
337mod tests {
338    use super::*;
339
340    #[test]
341    fn test_state_event_builder_basic() -> Result<(), Box<dyn Error>> {
342        let eevt = StateEERecord {
343            s: "0".to_string(),
344            d: "EXwm3_T3cINe-7R4FXQYcjKMr1cwrD7evf-i3k_oYrVM".to_string(),
345            br: None,
346            ba: None,
347        };
348
349        let keys = vec![
350            "DXwm3_T3cINe-7R4FXQYcjKMr1cwrD7evf-i3k_oYrVM".to_string(),
351            "EXwm3_T3cINe-7R4FXQYcjKMr1cwrD7evf-i3k_oYrVM".to_string(),
352        ];
353
354        let state = StateEventBuilder::new(
355            "EXwm3_T3cINe-7R4FXQYcjKMr1cwrD7evf-i3k_oYrVM".to_string(),
356            1,
357            "AbcdefghijklmnopqrstuvwxyzABCDEFGHIJK".to_string(),
358            "EXwm3_T3cINe-7R4FXQYcjKMr1cwrD7evf-i3k_oYrVM".to_string(),
359            0,
360            "icp".to_string(),
361            keys.clone(),
362            eevt,
363        )
364        .build()?;
365
366        assert_eq!(state.i, "EXwm3_T3cINe-7R4FXQYcjKMr1cwrD7evf-i3k_oYrVM");
367        assert_eq!(state.s, "1");
368        assert_eq!(state.et, "icp");
369        assert_eq!(state.k, keys);
370
371        Ok(())
372    }
373
374    #[test]
375    fn test_state_event_builder_with_wits() -> Result<(), Box<dyn Error>> {
376        let eevt = StateEERecord {
377            s: "0".to_string(),
378            d: "EXwm3_T3cINe-7R4FXQYcjKMr1cwrD7evf-i3k_oYrVM".to_string(),
379            br: Some(vec![
380                "BGKVzj4ve0VSd8z_AmvhLg4lqcC_9WYX90k03q-R_Ydo".to_string()
381            ]),
382            ba: Some(vec![
383                "BuyRFMideczFZoapylLIyCjSdhtqVb31wZkRKvPfNqkw".to_string()
384            ]),
385        };
386
387        let wits = vec![
388            "BGKVzj4ve0VSd8z_AmvhLg4lqcC_9WYX90k03q-R_Ydo".to_string(),
389            "BuyRFMideczFZoapylLIyCjSdhtqVb31wZkRKvPfNqkw".to_string(),
390        ];
391
392        let state = StateEventBuilder::new(
393            "EXwm3_T3cINe-7R4FXQYcjKMr1cwrD7evf-i3k_oYrVM".to_string(),
394            1,
395            "AbcdefghijklmnopqrstuvwxyzABCDEFGHIJK".to_string(),
396            "EXwm3_T3cINe-7R4FXQYcjKMr1cwrD7evf-i3k_oYrVM".to_string(),
397            0,
398            "rot".to_string(),
399            vec!["DXwm3_T3cINe-7R4FXQYcjKMr1cwrD7evf-i3k_oYrVM".to_string()],
400            eevt,
401        )
402        .with_wits(wits.clone())
403        .with_toad(2)
404        .build()?;
405
406        assert_eq!(state.et, "rot");
407        assert_eq!(state.b, wits);
408        assert_eq!(state.bt, "2");
409
410        Ok(())
411    }
412
413    #[test]
414    fn test_state_event_builder_with_delegation() -> Result<(), Box<dyn Error>> {
415        let eevt = StateEERecord {
416            s: "0".to_string(),
417            d: "EXwm3_T3cINe-7R4FXQYcjKMr1cwrD7evf-i3k_oYrVM".to_string(),
418            br: None,
419            ba: None,
420        };
421
422        let state = StateEventBuilder::new(
423            "EXwm3_T3cINe-7R4FXQYcjKMr1cwrD7evf-i3k_oYrVM".to_string(),
424            1,
425            "AbcdefghijklmnopqrstuvwxyzABCDEFGHIJK".to_string(),
426            "EXwm3_T3cINe-7R4FXQYcjKMr1cwrD7evf-i3k_oYrVM".to_string(),
427            0,
428            "dip".to_string(),
429            vec!["DXwm3_T3cINe-7R4FXQYcjKMr1cwrD7evf-i3k_oYrVM".to_string()],
430            eevt,
431        )
432        .with_dpre("EZAoTNZH3ULvaU6Z-i0d8JJR2nmwyYAfSVPzhzS6b5CM".to_string())
433        .build()?;
434
435        assert_eq!(state.et, "dip");
436        assert_eq!(state.di, "EZAoTNZH3ULvaU6Z-i0d8JJR2nmwyYAfSVPzhzS6b5CM");
437
438        Ok(())
439    }
440
441    #[test]
442    fn test_state_event_builder_with_intive() -> Result<(), Box<dyn Error>> {
443        let eevt = StateEERecord {
444            s: "0".to_string(),
445            d: "EXwm3_T3cINe-7R4FXQYcjKMr1cwrD7evf-i3k_oYrVM".to_string(),
446            br: None,
447            ba: None,
448        };
449
450        let state = StateEventBuilder::new(
451            "EXwm3_T3cINe-7R4FXQYcjKMr1cwrD7evf-i3k_oYrVM".to_string(),
452            1,
453            "AbcdefghijklmnopqrstuvwxyzABCDEFGHIJK".to_string(),
454            "EXwm3_T3cINe-7R4FXQYcjKMr1cwrD7evf-i3k_oYrVM".to_string(),
455            0,
456            "icp".to_string(),
457            vec![
458                "DXwm3_T3cINe-7R4FXQYcjKMr1cwrD7evf-i3k_oYrVM".to_string(),
459                "EXwm3_T3cINe-7R4FXQYcjKMr1cwrD7evf-i3k_oYrVM".to_string(),
460            ],
461            eevt,
462        )
463        .with_intive(true)
464        .with_sith(TholderSith::Integer(1))
465        .build()?;
466
467        assert_eq!(state.kt, "1");
468
469        Ok(())
470    }
471}