libkeri 0.1.0

A Rust library for KERI (Key Event Receipt Infrastructure)
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
use crate::Matter;
use std::collections::HashSet;
use std::error::Error;

use crate::cesr::cigar::Cigar;
use crate::cesr::non_trans_dex;
use crate::cesr::seqner::Seqner;
use crate::keri::core::serdering::{Serder, SerderKERI};

pub mod incept;
pub mod interact;
pub mod kever;
pub mod kevery;
pub mod query;
pub mod receipt;
pub mod reply;
pub mod rotate;
pub mod state;

use crate::cesr::counting::{ctr_dex_1_0, BaseCounter, Counter};
use crate::cesr::indexing::siger::Siger;
use crate::cesr::indexing::Indexer;
use crate::cesr::tholder::Tholder;
use crate::cesr::verfer::Verfer;
use crate::keri::KERIError;
pub use incept::*;
pub use interact::*;
pub use kever::*;
pub use kevery::*;
pub use query::*;
pub use receipt::*;
pub use reply::*;
pub use rotate::*;
pub use state::*;

// Determine threshold representations based on intive flag
const MAX_INT_THOLD: usize = 12; // Define this constant based on your system

fn ample(n: usize) -> usize {
    // Implementation for ample - computes witness threshold
    std::cmp::max(1, (n as f64 / 2.0).ceil() as usize)
}

fn is_digest_code(code: &str) -> bool {
    // Check if code is in DigDex
    ["E", "S", "X"].contains(&code)
}

fn is_prefix_code(code: &str) -> bool {
    // Check if code is in PreDex
    ["A", "B", "C", "D"].contains(&code)
}

/// SealEvent represents a triple (i, s, d) of identifier, sequence number, and digest
#[derive(Debug, Clone)]
pub struct SealEvent {
    pub i: String, // identifier prefix (pre)
    pub s: String, // sequence number as hex string
    pub d: String, // digest (said)
}

impl SealEvent {
    pub fn new(i: String, s: String, d: String) -> Self {
        Self { i, s, d }
    }
}

/// SealLast represents a single value (i) of identifier
#[derive(Debug, Clone)]
pub struct SealLast {
    pub i: String, // identifier prefix (pre)
}

impl SealLast {
    pub fn new(i: String) -> Self {
        Self { i }
    }
}

pub enum Seal {
    SealLast(SealLast),
    SealEvent(SealEvent),
}

/// Attaches indexed signatures from sigers and/or cigars and/or wigers to KERI message data from serder
///
/// # Arguments
///
/// * `serder` - SerderKERI instance containing the event
/// * `sigers` - Optional list of Siger instances to create indexed signatures
/// * `seal` - Optional seal:
///     - If SealEvent: Use attachment group code TransIdxSigGroups plus attach
///       triple pre+snu+dig made from (i,s,d) of seal plus ControllerIdxSigs
///       plus attached indexed sigs in sigers
///     - If SealLast: Use attachment group code TransLastIdxSigGroups plus
///       attach triple pre made from (i) of seal plus ControllerIdxSigs
///       plus attached indexed sigs in sigers
///     - Else: Use ControllerIdxSigs plus attached indexed sigs in sigers
/// * `wigers` - Optional list of Siger instances of witness index signatures
/// * `cigars` - Optional list of Cigars instances of non-transferable non indexed
///   signatures from which to form receipt couples.
///   Each cigar.verfer.qb64 is pre of receiptor and cigar.qb64 is signature
/// * `pipelined` - If true, prepend pipelining count code to attachemnts
///   If false, do not prepend pipelining count code
///
/// # Returns
///
/// Bytearray containing the KERI event message
///
/// # Errors
///
/// Returns an error if there are no signatures attached or if there are invalid attachment sizes
pub fn validate_sigs(
    serder: &SerderKERI,
    sigers: Vec<Siger>,
    verfers: &[Verfer],
    tholder: &Tholder,
) -> Result<(Vec<Siger>, bool), KERIError> {
    // Check if we have enough verfers for the threshold
    if verfers.len() < tholder.size() {
        let verfer_qb64s: Vec<String> = verfers.iter().map(|v| v.qb64()).collect();
        return Err(KERIError::ValidationError(format!(
            "Invalid sith = {} for keys = {:?}",
            tholder.sith(),
            verfer_qb64s
        )));
    }

    // Get unique verified sigers and indices lists from sigers list
    let (verified_sigers, indices) = verify_sigs(serder.raw(), sigers, verfers)?;
    // verified_sigers now have .verfer assigned

    // Check if we have at least one verified signature
    if indices.is_empty() {
        return Err(KERIError::ValidationError(format!(
            "No verified signatures for message={:?}",
            serder.ked()
        )));
    }

    // Check if satisfies threshold for fully signed
    let valid = tholder.satisfy(&indices);

    Ok((verified_sigers, valid))
}

pub fn messagize(
    serder: &SerderKERI,
    sigers: Option<&[Siger]>,
    seal: Option<Seal>,
    wigers: Option<&[Siger]>,
    cigars: Option<&[Cigar]>,
    pipelined: bool,
) -> Result<Vec<u8>, Box<dyn Error>> {
    let mut msg = serder.raw().to_vec(); // make copy of raw bytes
    let mut atc = Vec::new(); // attachment bytearray

    if sigers.is_none() && cigars.is_none() && wigers.is_none() {
        return Err("Missing attached signatures on message".into());
    }

    if let Some(sigers_slice) = sigers {
        if !sigers_slice.is_empty() {
            // Check if we have a seal
            if let Some(seal_any) = seal {
                // Try to downcast to SealEvent
                match seal_any {
                    Seal::SealLast(seal_last) => {
                        let counter = BaseCounter::from_code_and_count(
                            Some(ctr_dex_1_0::TRANS_LAST_IDX_SIG_GROUPS),
                            Some(1),
                            None,
                        )?;
                        atc.extend(counter.qb64b());

                        // Append seal data
                        atc.extend(seal_last.i.as_bytes());
                    }
                    Seal::SealEvent(seal_event) => {
                        let counter = BaseCounter::from_code_and_count(
                            Some(ctr_dex_1_0::TRANS_IDX_SIG_GROUPS),
                            Some(1),
                            None,
                        )?;
                        atc.extend(counter.qb64b());

                        // Append seal data
                        atc.extend(seal_event.i.as_bytes());
                        let seqner = Seqner::from_snh(&seal_event.s)?;
                        atc.extend(seqner.qb64b());
                        atc.extend(seal_event.d.as_bytes());
                    }
                }
            }

            // Add controller indexed signatures
            let counter = BaseCounter::from_code_and_count(
                Some(ctr_dex_1_0::CONTROLLER_IDX_SIGS),
                Some(sigers_slice.len() as u64),
                None,
            )?;
            atc.extend(counter.qb64b());

            for siger in sigers_slice {
                atc.extend(siger.qb64b());
            }
        }
    }

    if let Some(wigers_slice) = wigers {
        if !wigers_slice.is_empty() {
            // Add witness indexed signatures
            let counter = BaseCounter::from_code_and_count(
                Some(ctr_dex_1_0::WITNESS_IDX_SIGS),
                Some(wigers_slice.len() as u64),
                None,
            )?;
            atc.extend(counter.qb64b());

            for wiger in wigers_slice {
                // Check if non-transferable
                if let Some(verfer) = &wiger.verfer() {
                    if !non_trans_dex::TUPLE.contains(&verfer.code()) {
                        return Err(format!(
                            "Attempt to use tranferable prefix={} for receipt.",
                            verfer.qb64()
                        )
                        .into());
                    }
                }
                atc.extend(wiger.qb64b());
            }
        }
    }

    if let Some(cigars_slice) = cigars {
        if !cigars_slice.is_empty() {
            // Add non-transferable receipt couples
            let counter = BaseCounter::from_code_and_count(
                Some(ctr_dex_1_0::NON_TRANS_RECEIPT_COUPLES),
                Some(cigars_slice.len() as u64),
                None,
            )?;
            atc.extend(counter.qb64b());

            for cigar in cigars_slice {
                // Check if non-transferable
                if !non_trans_dex::TUPLE.contains(&cigar.verfer().unwrap().code()) {
                    return Err(format!(
                        "Attempt to use tranferable prefix={} for receipt.",
                        cigar.verfer().unwrap().qb64()
                    )
                    .into());
                }

                // Append verfer and signature
                atc.extend(cigar.verfer().unwrap().qb64b());
                atc.extend(cigar.qb64b());
            }
        }
    }

    if pipelined {
        // Check that attachments size is a multiple of 4 (integral quadlets)
        if atc.len() % 4 != 0 {
            return Err(format!(
                "Invalid attachments size={}, nonintegral quadlets.",
                atc.len()
            )
            .into());
        }

        // Add attachment group counter
        let counter = BaseCounter::from_code_and_count(
            Some(ctr_dex_1_0::ATTACHMENT_GROUP),
            Some((atc.len() / 4) as u64),
            None,
        )?;
        msg.extend(counter.qb64b());
    }

    // Add attachments to message
    msg.extend(atc);

    Ok(msg)
}

/// Verifies signatures against verifiers and returns verified signatures and their indices
///
/// Returns tuple of (vsigers, vindices) where:
/// - vsigers is a list of unique verified sigers with assigned verfer
/// - vindices is a list of indices from those verified sigers
///
/// The returned vsigers and vindices may be used for threshold validation
///
/// Assigns appropriate verfer from verfers to each siger based on siger index
/// If no signatures verify then sigers and indices are empty
///
/// # Arguments
///
/// * `raw` - The signed data as bytes
/// * `sigers` - A list of indexed Siger instances (signatures)
/// * `verfers` - A list of Verfer instances (public keys)
///
/// # Returns
///
/// * `Result<(Vec<Siger>, Vec<usize>), KERIError>` - Tuple of verified sigers and their indices
fn verify_sigs(
    raw: &[u8],
    sigers: Vec<Siger>,
    verfers: &[Verfer],
) -> Result<(Vec<Siger>, Vec<usize>), KERIError> {
    if sigers.is_empty() {
        return Ok((Vec::new(), Vec::new()));
    }

    // Create a set of unique signatures to avoid duplicates
    // In Rust, we'll use a HashSet to collect unique sigers based on their qb64
    let mut unique_signatures = HashSet::new();
    let mut unique_sigers = Vec::new();

    for siger in sigers {
        let qb64 = siger.qb64();
        if unique_signatures.insert(qb64) {
            unique_sigers.push(siger);
        }
    }

    // Create a vector to hold sigers with assigned verfers
    let mut usigers_with_verfers = Vec::new();

    // Assign verfers to each unique siger based on index
    for mut siger in unique_sigers {
        let index = siger.index() as usize;
        if index >= verfers.len() {
            // Log if index is out of bounds
            continue;
        }

        // Clone the verfer and assign it to the siger
        let verfer = verfers[index].clone();
        siger.set_verfer(verfer);
        usigers_with_verfers.push(siger);
    }

    // Create lists of verified sigers and their indices
    let mut vindices = Vec::new();
    let mut vsigers = Vec::new();

    // Verify each siger and collect valid ones
    for siger in usigers_with_verfers {
        // Get verfer from siger - it should be present now
        if let Some(verfer) = siger.verfer() {
            // Verify the signature
            match verfer.verify(siger.raw(), raw) {
                Ok(true) => {
                    // Signature verified successfully
                    vindices.push(siger.index() as usize);
                    vsigers.push(siger);
                }
                Ok(false) => {
                    // Signature failed verification
                    print!("Signature failed verification for index {}", siger.index());
                }
                Err(err) => {
                    // Error during verification
                    print!(
                        "Error verifying signature at index {}: {:?}",
                        siger.index(),
                        err
                    );
                }
            }
        } else {
            // This shouldn't happen if we properly assigned verfers above
            print!("Siger missing verfer at index {}", siger.index());
        }
    }

    Ok((vsigers, vindices))
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::cesr::signing::{Salter, Sigmat};
    use crate::cesr::{mtr_dex, Matter};
    use crate::keri::app::keeping::{Keeper, Manager};
    use crate::keri::core::eventing::interact::InteractEventBuilder;
    use crate::keri::core::eventing::rotate::RotateEventBuilder;
    use crate::keri::core::serdering::SadValue;
    use crate::keri::db::dbing::LMDBer;
    use indexmap::IndexMap;
    use std::error::Error;
    use std::sync::Arc;

    #[test]
    fn test_messagize() -> Result<(), Box<dyn Error>> {
        // Create deterministic salter for testing
        let raw = b"0123456789abcdef";
        let salter = Salter::new(Some(raw), None, None)?;
        assert_eq!(salter.qb64b(), b"0AAwMTIzNDU2Nzg5YWJjZGVm");

        let lmdber = LMDBer::builder()
            .name("manager_ks")
            .reopen(true)
            .build()
            .expect("Failed to open manager database: {}");
        let keeper = Keeper::new(Arc::new(&lmdber)).expect("Failed to create manager database");
        let mut manager = Manager::new(keeper, None, None, None, None, Some(salter.qb64b()), None)?;
        // Test salty algorithm incept
        let (verfers, digers) = manager.incept(
            None,
            Some(1),
            None,
            None,
            Some(0),
            None,
            None,
            None,
            None,
            Some("C"),
            None,
            None,
            Some(true),
            None,
        )?;
        assert_eq!(verfers.len(), 1);
        assert_eq!(digers.len(), 0);
        assert_eq!(
            verfers[0].qb64b(),
            b"DOif48whAmpb_4kyksMcz57snMRIuX0bqN1FDe09AlRj"
        );

        // Create inception event
        let serder = InceptionEventBuilder::new(vec![verfers[0].qb64()])
            .with_code(mtr_dex::BLAKE3_256.to_string())
            .build()?;

        // Sign the serialized event
        let sigers: Vec<Siger> = manager
            .sign(
                serder.raw(),
                None,
                Some(verfers),
                None,
                None,
                None,
                None,
                None,
            )?
            .iter()
            .map(|sigmat| match sigmat {
                Sigmat::Indexed(siger) => siger.clone(),
                Sigmat::NonIndexed(_) => {
                    panic!("Unexpected non-indexed signature");
                }
            })
            .collect();

        // Test basic messagize with sigers
        let msg = messagize(&serder, Some(&sigers), None, None, None, false)?;

        // Expected output for basic case
        assert_eq!(
            String::from_utf8(msg.clone())?,
            concat!(
                r#"{"v":"KERI10JSON0000fd_","t":"icp","d":"EFyzzg2Mp5A3ecChc6AhSLTQ"#,
                r#"ssBZAmNvPnGxjJyHxl4F","i":"EFyzzg2Mp5A3ecChc6AhSLTQssBZAmNvPnGxj"#,
                r#"JyHxl4F","s":"0","kt":"1","k":["DOif48whAmpb_4kyksMcz57snMRIuX0b"#,
                r#"qN1FDe09AlRj"],"nt":"0","n":[],"bt":"0","b":[],"c":[],"a":[]}-AA"#,
                r#"BAAB1DuEfnZZ6juMZDYiodcWiIqdjuEE-QzdORp-DbxdDN_GG84x_NA1rSc5lPfP"#,
                r#"QQkQkxI862_XjyZLHyClVTLoD"#
            )
        );

        // Test with pipelined
        let msg = messagize(&serder, Some(&sigers), None, None, None, true)?;

        // Expected output for pipelined case
        assert_eq!(
            String::from_utf8(msg.clone())?,
            concat!(
                r#"{"v":"KERI10JSON0000fd_","t":"icp","d":"EFyzzg2Mp5A3ecChc6AhSLTQ"#,
                r#"ssBZAmNvPnGxjJyHxl4F","i":"EFyzzg2Mp5A3ecChc6AhSLTQssBZAmNvPnGxj"#,
                r#"JyHxl4F","s":"0","kt":"1","k":["DOif48whAmpb_4kyksMcz57snMRIuX0b"#,
                r#"qN1FDe09AlRj"],"nt":"0","n":[],"bt":"0","b":[],"c":[],"a":[]}-VA"#,
                r#"X-AABAAB1DuEfnZZ6juMZDYiodcWiIqdjuEE-QzdORp-DbxdDN_GG84x_NA1rSc5"#,
                r#"lPfPQQkQkxI862_XjyZLHyClVTLoD"#
            )
        );

        // Test with SealEvent
        let seal = Seal::SealEvent(SealEvent::new(
            "DAvCLRr5luWmp7keDvDuLP0kIqcyBYq79b3Dho1QvrjI".to_string(),
            "0".to_string(),
            "EMuNWHss_H_kH4cG7Li1jn2DXfrEaqN7zhqTEhkeDZ2z".to_string(),
        ));

        let msg = messagize(&serder, Some(&sigers), Some(seal), None, None, false)?;

        // Expected output with SealEvent
        assert_eq!(
            String::from_utf8(msg.clone())?,
            concat!(
                r#"{"v":"KERI10JSON0000fd_","t":"icp","d":"EFyzzg2Mp5A3ecChc6AhSLTQ"#,
                r#"ssBZAmNvPnGxjJyHxl4F","i":"EFyzzg2Mp5A3ecChc6AhSLTQssBZAmNvPnGxj"#,
                r#"JyHxl4F","s":"0","kt":"1","k":["DOif48whAmpb_4kyksMcz57snMRIuX0b"#,
                r#"qN1FDe09AlRj"],"nt":"0","n":[],"bt":"0","b":[],"c":[],"a":[]}-FA"#,
                r#"BDAvCLRr5luWmp7keDvDuLP0kIqcyBYq79b3Dho1QvrjI0AAAAAAAAAAAAAAAAAA"#,
                r#"AAAAAEMuNWHss_H_kH4cG7Li1jn2DXfrEaqN7zhqTEhkeDZ2z-AABAAB1DuEfnZZ"#,
                r#"6juMZDYiodcWiIqdjuEE-QzdORp-DbxdDN_GG84x_NA1rSc5lPfPQQkQkxI862_X"#,
                r#"jyZLHyClVTLoD"#
            )
        );

        // Test SealEvent with pipelined
        // Test with SealEvent
        let seal = Seal::SealEvent(SealEvent::new(
            "DAvCLRr5luWmp7keDvDuLP0kIqcyBYq79b3Dho1QvrjI".to_string(),
            "0".to_string(),
            "EMuNWHss_H_kH4cG7Li1jn2DXfrEaqN7zhqTEhkeDZ2z".to_string(),
        ));
        let msg = messagize(&serder, Some(&sigers), Some(seal), None, None, true)?;

        // Expected output for SealEvent with pipelined
        assert_eq!(
            String::from_utf8(msg.clone())?,
            concat!(
                r#"{"v":"KERI10JSON0000fd_","t":"icp","d":"EFyzzg2Mp5A3ecChc6AhSLTQ"#,
                r#"ssBZAmNvPnGxjJyHxl4F","i":"EFyzzg2Mp5A3ecChc6AhSLTQssBZAmNvPnGxj"#,
                r#"JyHxl4F","s":"0","kt":"1","k":["DOif48whAmpb_4kyksMcz57snMRIuX0b"#,
                r#"qN1FDe09AlRj"],"nt":"0","n":[],"bt":"0","b":[],"c":[],"a":[]}-VA"#,
                r#"0-FABDAvCLRr5luWmp7keDvDuLP0kIqcyBYq79b3Dho1QvrjI0AAAAAAAAAAAAAA"#,
                r#"AAAAAAAAAEMuNWHss_H_kH4cG7Li1jn2DXfrEaqN7zhqTEhkeDZ2z-AABAAB1DuE"#,
                r#"fnZZ6juMZDYiodcWiIqdjuEE-QzdORp-DbxdDN_GG84x_NA1rSc5lPfPQQkQkxI8"#,
                r#"62_XjyZLHyClVTLoD"#
            )
        );

        let (verfers, digers) = manager.incept(
            None,
            Some(1),
            None,
            None,
            Some(0),
            None,
            None,
            None,
            None,
            Some("W"),
            None,
            None,
            Some(false),
            None,
        )?;

        // Test with wigers
        // First create a non-transferable signer
        let wigers: Vec<Siger> = manager
            .sign(
                serder.raw(),
                None,
                Some(verfers),
                None,
                None,
                None,
                None,
                None,
            )?
            .iter()
            .map(|sigmat| match sigmat {
                Sigmat::Indexed(siger) => siger.clone(),
                Sigmat::NonIndexed(_) => {
                    panic!("Unexpected non-indexed signature");
                }
            })
            .collect();

        let msg = messagize(&serder, None, None, Some(&wigers), None, false)?;

        // Expected output for wigers
        assert_eq!(
            String::from_utf8(msg.clone())?,
            concat!(
                r#"{"v":"KERI10JSON0000fd_","t":"icp","d":"EFyzzg2Mp5A3ecChc6AhSLTQ"#,
                r#"ssBZAmNvPnGxjJyHxl4F","i":"EFyzzg2Mp5A3ecChc6AhSLTQssBZAmNvPnGxj"#,
                r#"JyHxl4F","s":"0","kt":"1","k":["DOif48whAmpb_4kyksMcz57snMRIuX0b"#,
                r#"qN1FDe09AlRj"],"nt":"0","n":[],"bt":"0","b":[],"c":[],"a":[]}-BA"#,
                r#"BAABtOhjlKo8WhJQ3EXMIMaQ_IH6yeyxs7_JuO4RioH1NUTtzTuV1bbuB7eoNhEj"#,
                r#"20VJYa4947ZMVrOxKhzI6EqUH"#
            )
        );

        // Test wigers with pipelined
        let msg = messagize(&serder, None, None, Some(&wigers), None, true)?;

        // Expected output for wigers with pipelined
        assert_eq!(
            String::from_utf8(msg.clone())?,
            concat!(
                r#"{"v":"KERI10JSON0000fd_","t":"icp","d":"EFyzzg2Mp5A3ecChc6AhSLTQ"#,
                r#"ssBZAmNvPnGxjJyHxl4F","i":"EFyzzg2Mp5A3ecChc6AhSLTQssBZAmNvPnGxj"#,
                r#"JyHxl4F","s":"0","kt":"1","k":["DOif48whAmpb_4kyksMcz57snMRIuX0b"#,
                r#"qN1FDe09AlRj"],"nt":"0","n":[],"bt":"0","b":[],"c":[],"a":[]}-VA"#,
                r#"X-BABAABtOhjlKo8WhJQ3EXMIMaQ_IH6yeyxs7_JuO4RioH1NUTtzTuV1bbuB7eo"#,
                r#"NhEj20VJYa4947ZMVrOxKhzI6EqUH"#
            )
        );

        // Test with cigars
        // Create a non-transferable signer for cigars (non-indexed signatures)
        let (verfers, digers) = manager.incept(
            None,
            Some(1),
            None,
            None,
            Some(0),
            None,
            None,
            None,
            None,
            Some("R"),
            None,
            None,
            Some(false),
            None,
        )?;

        let cigars: Vec<Cigar> = manager
            .sign(
                serder.raw(),
                None,
                Some(verfers),
                Some(false),
                None,
                None,
                None,
                None,
            )?
            .iter()
            .map(|sigmat| match sigmat {
                Sigmat::Indexed(siger) => {
                    panic!("Unexpected non-indexed signature");
                }
                Sigmat::NonIndexed(cigar) => cigar.clone(),
            })
            .collect();
        let msg = messagize(&serder, None, None, None, Some(&cigars), false)?;

        // Expected output for cigars
        assert_eq!(
            String::from_utf8(msg.clone())?,
            concat!(
                r#"{"v":"KERI10JSON0000fd_","t":"icp","d":"EFyzzg2Mp5A3ecChc6AhSLTQ"#,
                r#"ssBZAmNvPnGxjJyHxl4F","i":"EFyzzg2Mp5A3ecChc6AhSLTQssBZAmNvPnGxj"#,
                r#"JyHxl4F","s":"0","kt":"1","k":["DOif48whAmpb_4kyksMcz57snMRIuX0b"#,
                r#"qN1FDe09AlRj"],"nt":"0","n":[],"bt":"0","b":[],"c":[],"a":[]}-CA"#,
                r#"BBJjH1MCDssEZMnORskF34AwOFDgDL47513GivRvd_QKz0BDwWrxO8RItpgGFtFi"#,
                r#"DF7QoVas-6Bzvj0xtOfbsh31jjtshcEa0rUVX2xsyyH1US2fBWe7FNpn6xko5EVw"#,
                r#"g_TwF"#
            )
        );

        // Test cigars with pipelined
        let msg = messagize(&serder, None, None, None, Some(&cigars), true)?;

        // Expected output for cigars with pipelined
        assert_eq!(
            String::from_utf8(msg.clone())?,
            concat!(
                r#"{"v":"KERI10JSON0000fd_","t":"icp","d":"EFyzzg2Mp5A3ecChc6AhSLTQ"#,
                r#"ssBZAmNvPnGxjJyHxl4F","i":"EFyzzg2Mp5A3ecChc6AhSLTQssBZAmNvPnGxj"#,
                r#"JyHxl4F","s":"0","kt":"1","k":["DOif48whAmpb_4kyksMcz57snMRIuX0b"#,
                r#"qN1FDe09AlRj"],"nt":"0","n":[],"bt":"0","b":[],"c":[],"a":[]}-VA"#,
                r#"i-CABBJjH1MCDssEZMnORskF34AwOFDgDL47513GivRvd_QKz0BDwWrxO8RItpgG"#,
                r#"FtFiDF7QoVas-6Bzvj0xtOfbsh31jjtshcEa0rUVX2xsyyH1US2fBWe7FNpn6xko"#,
                r#"5EVwg_TwF"#
            )
        );

        // Test with wigers and cigars
        let msg = messagize(&serder, None, None, Some(&wigers), Some(&cigars), false)?;

        // Expected output for wigers and cigars
        assert_eq!(
            String::from_utf8(msg.clone())?,
            concat!(
                r#"{"v":"KERI10JSON0000fd_","t":"icp","d":"EFyzzg2Mp5A3ecChc6AhSLTQ"#,
                r#"ssBZAmNvPnGxjJyHxl4F","i":"EFyzzg2Mp5A3ecChc6AhSLTQssBZAmNvPnGxj"#,
                r#"JyHxl4F","s":"0","kt":"1","k":["DOif48whAmpb_4kyksMcz57snMRIuX0b"#,
                r#"qN1FDe09AlRj"],"nt":"0","n":[],"bt":"0","b":[],"c":[],"a":[]}-BA"#,
                r#"BAABtOhjlKo8WhJQ3EXMIMaQ_IH6yeyxs7_JuO4RioH1NUTtzTuV1bbuB7eoNhEj"#,
                r#"20VJYa4947ZMVrOxKhzI6EqUH-CABBJjH1MCDssEZMnORskF34AwOFDgDL47513G"#,
                r#"ivRvd_QKz0BDwWrxO8RItpgGFtFiDF7QoVas-6Bzvj0xtOfbsh31jjtshcEa0rUV"#,
                r#"X2xsyyH1US2fBWe7FNpn6xko5EVwg_TwF"#
            )
        );

        // Test with wigers and cigars and pipelined
        let msg = messagize(&serder, None, None, Some(&wigers), Some(&cigars), true)?;

        // Expected output for wigers and cigars with pipelined
        assert_eq!(
            String::from_utf8(msg.clone())?,
            concat!(
                r#"{"v":"KERI10JSON0000fd_","t":"icp","d":"EFyzzg2Mp5A3ecChc6AhSLTQ"#,
                r#"ssBZAmNvPnGxjJyHxl4F","i":"EFyzzg2Mp5A3ecChc6AhSLTQssBZAmNvPnGxj"#,
                r#"JyHxl4F","s":"0","kt":"1","k":["DOif48whAmpb_4kyksMcz57snMRIuX0b"#,
                r#"qN1FDe09AlRj"],"nt":"0","n":[],"bt":"0","b":[],"c":[],"a":[]}-VA"#,
                r#"5-BABAABtOhjlKo8WhJQ3EXMIMaQ_IH6yeyxs7_JuO4RioH1NUTtzTuV1bbuB7eo"#,
                r#"NhEj20VJYa4947ZMVrOxKhzI6EqUH-CABBJjH1MCDssEZMnORskF34AwOFDgDL47"#,
                r#"513GivRvd_QKz0BDwWrxO8RItpgGFtFiDF7QoVas-6Bzvj0xtOfbsh31jjtshcEa"#,
                r#"0rUVX2xsyyH1US2fBWe7FNpn6xko5EVwg_TwF"#
            )
        );

        // Test with sigers, wigers, and cigars
        let msg = messagize(
            &serder,
            Some(&sigers),
            None,
            Some(&wigers),
            Some(&cigars),
            false,
        )?;

        // Expected output for sigers, wigers, and cigars
        assert_eq!(
            String::from_utf8(msg.clone())?,
            concat!(
                r#"{"v":"KERI10JSON0000fd_","t":"icp","d":"EFyzzg2Mp5A3ecChc6AhSLTQ"#,
                r#"ssBZAmNvPnGxjJyHxl4F","i":"EFyzzg2Mp5A3ecChc6AhSLTQssBZAmNvPnGxj"#,
                r#"JyHxl4F","s":"0","kt":"1","k":["DOif48whAmpb_4kyksMcz57snMRIuX0b"#,
                r#"qN1FDe09AlRj"],"nt":"0","n":[],"bt":"0","b":[],"c":[],"a":[]}-AA"#,
                r#"BAAB1DuEfnZZ6juMZDYiodcWiIqdjuEE-QzdORp-DbxdDN_GG84x_NA1rSc5lPfP"#,
                r#"QQkQkxI862_XjyZLHyClVTLoD-BABAABtOhjlKo8WhJQ3EXMIMaQ_IH6yeyxs7_J"#,
                r#"uO4RioH1NUTtzTuV1bbuB7eoNhEj20VJYa4947ZMVrOxKhzI6EqUH-CABBJjH1MC"#,
                r#"DssEZMnORskF34AwOFDgDL47513GivRvd_QKz0BDwWrxO8RItpgGFtFiDF7QoVas"#,
                r#"-6Bzvj0xtOfbsh31jjtshcEa0rUVX2xsyyH1US2fBWe7FNpn6xko5EVwg_TwF"#
            )
        );

        // Test with sigers, wigers, cigars and pipelined
        let msg = messagize(
            &serder,
            Some(&sigers),
            None,
            Some(&wigers),
            Some(&cigars),
            true,
        )?;

        // Expected output for sigers, wigers, cigars with pipelined
        assert_eq!(
            String::from_utf8(msg)?,
            concat!(
                r#"{"v":"KERI10JSON0000fd_","t":"icp","d":"EFyzzg2Mp5A3ecChc6AhSLTQ"#,
                r#"ssBZAmNvPnGxjJyHxl4F","i":"EFyzzg2Mp5A3ecChc6AhSLTQssBZAmNvPnGxj"#,
                r#"JyHxl4F","s":"0","kt":"1","k":["DOif48whAmpb_4kyksMcz57snMRIuX0b"#,
                r#"qN1FDe09AlRj"],"nt":"0","n":[],"bt":"0","b":[],"c":[],"a":[]}-VB"#,
                r#"Q-AABAAB1DuEfnZZ6juMZDYiodcWiIqdjuEE-QzdORp-DbxdDN_GG84x_NA1rSc5"#,
                r#"lPfPQQkQkxI862_XjyZLHyClVTLoD-BABAABtOhjlKo8WhJQ3EXMIMaQ_IH6yeyx"#,
                r#"s7_JuO4RioH1NUTtzTuV1bbuB7eoNhEj20VJYa4947ZMVrOxKhzI6EqUH-CABBJj"#,
                r#"H1MCDssEZMnORskF34AwOFDgDL47513GivRvd_QKz0BDwWrxO8RItpgGFtFiDF7Q"#,
                r#"oVas-6Bzvj0xtOfbsh31jjtshcEa0rUVX2xsyyH1US2fBWe7FNpn6xko5EVwg_TwF"#
            )
        );

        Ok(())
    }

    #[test]
    fn test_full_kel() -> Result<(), Box<dyn Error>> {
        // Create deterministic salter for testing
        let raw = b"abcdef0123456789";
        let salter = Salter::new(Some(raw), None, None)?;
        assert_eq!(salter.qb64(), "0ABhYmNkZWYwMTIzNDU2Nzg5");

        let lmdber = LMDBer::builder()
            .name("manager_ks")
            .reopen(true)
            .build()
            .expect("Failed to open manager database: {}");
        let keeper = Keeper::new(Arc::new(&lmdber)).expect("Failed to create manager database");
        let mut manager = Manager::new(keeper, None, None, None, None, Some(salter.qb64b()), None)?;
        // Test salty algorithm incept
        let (verfers, digers) = manager.incept(
            None,
            Some(1),
            None,
            None,
            Some(1),
            None,
            None,
            None,
            None,
            Some("C"),
            None,
            None,
            Some(true),
            None,
        )?;
        assert_eq!(verfers.len(), 1);
        assert_eq!(digers.len(), 1);
        assert_eq!(
            verfers[0].qb64(),
            "DCjMCQ638m293JGMIjU7ch0bqmaU6-v4AK_wBf6jl4OX"
        );
        assert_eq!(
            digers[0].qb64(),
            "EEyU3aS2N1JrMq5kDQ4tZ_5PBTRD8ISUx3WUsuj0rU3-"
        );

        // Create inception event
        let serder = InceptionEventBuilder::new(vec![verfers[0].qb64()])
            .with_code(mtr_dex::BLAKE3_256.to_string())
            .with_ndigs(vec![digers[0].qb64()])
            .build()?;

        let oldspre = verfers[0].qb64b();
        let spre = serder.preb().unwrap();
        manager.move_prefix(&oldspre, &spre)?;

        // Sign the serialized event
        let sigers: Vec<Siger> = manager
            .sign(
                serder.raw(),
                None,
                Some(verfers),
                None,
                None,
                None,
                None,
                None,
            )?
            .iter()
            .map(|sigmat| match sigmat {
                Sigmat::Indexed(siger) => siger.clone(),
                Sigmat::NonIndexed(_) => {
                    panic!("Unexpected non-indexed signature");
                }
            })
            .collect();

        // Lets collect the full KEL
        let mut kel = String::new();

        // Test basic messagize with sigers
        let msg = messagize(&serder, Some(&sigers), None, None, None, false)?;
        kel.push_str(&String::from_utf8(msg.clone())?);

        assert_eq!(
            String::from_utf8(msg)?,
            concat!(
                r#"{"v":"KERI10JSON00012b_","t":"icp","d":"EPXgQxGLRPBzBR84e6hZ_SY1l5-WJU8b_n8ibASNDfKM","#,
                r#""i":"EPXgQxGLRPBzBR84e6hZ_SY1l5-WJU8b_n8ibASNDfKM","s":"0","kt":"1","k":["#,
                r#""DCjMCQ638m293JGMIjU7ch0bqmaU6-v4AK_wBf6jl4OX"],"nt":"1","n":["EEyU3aS2N1JrMq5k"#,
                r#"DQ4tZ_5PBTRD8ISUx3WUsuj0rU3-"],"bt":"0","b":[],"c":[],"a":[]}-AABAABGkiiW6C8_"#,
                r#"TTeT0XuWuxjrQ4Fp7hkurrP2oqYFBKMTYcoZDa5_ekzjQDOMX6cCZVeUBbbFnB0D7EX36vz385sM"#
            )
        );

        let (verfers, digers) = manager.rotate(
            &serder.preb().unwrap(),
            None,
            Some(1),
            None,
            None,
            Some(true),
            Some(false),
            Some(false),
        )?;
        assert_eq!(verfers.len(), 1);
        assert_eq!(digers.len(), 1);
        assert_eq!(
            verfers[0].qb64(),
            "DDxkQL-tXDKwAKPnVpmKgmeIP5GAa4nSI6pWFbuYc8Ye"
        );
        assert_eq!(
            digers[0].qb64(),
            "EBIjhA2t-Sfm29atirPEG-VD9ouVzy7i7PrFslG6D7tm"
        );

        let rserder = RotateEventBuilder::new(
            serder.pre().unwrap(),
            vec![verfers[0].qb64()],
            serder.said().unwrap().to_string(),
        )
        .with_ndigs(vec![digers[0].qb64()])
        .build()?;

        // Sign the serialized event
        let rsigers: Vec<Siger> = manager
            .sign(
                rserder.raw(),
                None,
                Some(verfers.clone()),
                None,
                None,
                None,
                None,
                None,
            )?
            .iter()
            .map(|sigmat| match sigmat {
                Sigmat::Indexed(siger) => siger.clone(),
                Sigmat::NonIndexed(_) => {
                    panic!("Unexpected non-indexed signature");
                }
            })
            .collect();

        // Test rotation with messagize with sigers
        let msg = messagize(&rserder, Some(&rsigers), None, None, None, false)?;
        kel.push_str(&String::from_utf8(msg.clone())?);
        assert_eq!(
            String::from_utf8(msg)?,
            concat!(
                r#"{"v":"KERI10JSON000160_","t":"rot","d":"EFFvfdKjytGurVS52KzF5NefoQkVJp9w3vDb5is9mEzP","#,
                r#""i":"EPXgQxGLRPBzBR84e6hZ_SY1l5-WJU8b_n8ibASNDfKM","s":"1","p":"EPXgQxGLRPBzBR84e6hZ_"#,
                r#"SY1l5-WJU8b_n8ibASNDfKM","kt":"1","k":["DDxkQL-tXDKwAKPnVpmKgmeIP5GAa4nSI6pWFbuYc8Ye"],"#,
                r#""nt":"1","n":["EBIjhA2t-Sfm29atirPEG-VD9ouVzy7i7PrFslG6D7tm"],"bt":"0","br":[],"ba":[],"#,
                r#""a":[]}-AABAADKqAHzC9bQ6VZy9HP5uG7-YhFDJsPGvCYj8BkX3z8GWIpcNdeXE4t7XRXxddn6r19uTxsBs-"#,
                r#"zN_-41rgzMM68M"#
            )
        );

        // Create data attachments
        let mut data_map1 = IndexMap::new();
        data_map1.insert(
            "i".to_string(),
            SadValue::String("EbAwspDmOlHDUjGZ8m9JGQ4r7Knt5gu4KBNt0JSL2ZoI".to_string()),
        );
        data_map1.insert("s".to_string(), SadValue::String("3".to_string()));
        data_map1.insert(
            "d".to_string(),
            SadValue::String("EY2L3ycqK9645aEeQKP941xojSiuiHsw4Y6yTW-DpRXs".to_string()),
        );
        let data = vec![SadValue::from(SadValue::Object(data_map1))];

        let xserder =
            InteractEventBuilder::new(serder.pre().unwrap(), rserder.said().unwrap().to_string())
                .with_sn(2)
                .with_data_list(data)
                .build()?;

        // Sign the serialized event
        let xsigers: Vec<Siger> = manager
            .sign(
                xserder.raw(),
                None,
                Some(verfers),
                None,
                None,
                None,
                None,
                None,
            )?
            .iter()
            .map(|sigmat| match sigmat {
                Sigmat::Indexed(siger) => siger.clone(),
                Sigmat::NonIndexed(_) => {
                    panic!("Unexpected non-indexed signature");
                }
            })
            .collect();
        let msg = messagize(&xserder, Some(&xsigers), None, None, None, false)?;
        kel.push_str(&String::from_utf8(msg.clone())?);
        assert_eq!(
            String::from_utf8(msg)?,
            concat!(
                r#"{"v":"KERI10JSON00013a_","t":"ixn","d":"EMljYBNn3JU_oD8O0_JmQ1Q7w3yFnCON9lauFHnDmNju","#,
                r#""i":"EPXgQxGLRPBzBR84e6hZ_SY1l5-WJU8b_n8ibASNDfKM","s":"2","p":"EFFvfdKjytGurVS52KzF5"#,
                r#"NefoQkVJp9w3vDb5is9mEzP","a":[{"i":"EbAwspDmOlHDUjGZ8m9JGQ4r7Knt5gu4KBNt0JSL2ZoI","s":"#,
                r#""3","d":"EY2L3ycqK9645aEeQKP941xojSiuiHsw4Y6yTW-DpRXs"}]}-AABAAAg0JyLoHFC2vezhTm6jz_"#,
                r#"BxbmSbSsvqxzeM8sP9fPekAFCKnlH-tsL_0SYmhA5HDXLcmQ4yWa0oWo4w4sYe0sP"#
            )
        );

        let (verfers, digers) = manager.rotate(
            &serder.preb().unwrap(),
            None,
            Some(1),
            None,
            None,
            Some(true),
            Some(false),
            Some(false),
        )?;
        assert_eq!(verfers.len(), 1);
        assert_eq!(digers.len(), 1);
        assert_eq!(
            verfers[0].qb64(),
            "DNFcsn7EiJemcWD_6bMOdeYUU1j2dC98WCCGjN7PxCIp"
        );
        assert_eq!(
            digers[0].qb64(),
            "EAu_UWkr40QDQWScisiLnv5rCJc5unxnAhu33V1RzzpA"
        );

        let rserder = RotateEventBuilder::new(
            serder.pre().unwrap(),
            vec![verfers[0].qb64()],
            xserder.said().unwrap().to_string(),
        )
        .with_sn(3)
        .with_ndigs(vec![digers[0].qb64()])
        .build()?;

        // Sign the serialized event
        let rsigers: Vec<Siger> = manager
            .sign(
                rserder.raw(),
                None,
                Some(verfers),
                None,
                None,
                None,
                None,
                None,
            )?
            .iter()
            .map(|sigmat| match sigmat {
                Sigmat::Indexed(siger) => siger.clone(),
                Sigmat::NonIndexed(_) => {
                    panic!("Unexpected non-indexed signature");
                }
            })
            .collect();

        // Test rotation with messagize with sigers
        let msg = messagize(&rserder, Some(&rsigers), None, None, None, false)?;
        kel.push_str(&String::from_utf8(msg.clone())?);
        assert_eq!(
            String::from_utf8(msg)?,
            concat!(
                r#"{"v":"KERI10JSON000160_","t":"rot","d":"EGC9ReDqCudaBI65eEmn2M52rr3YLb0j1j3PR0SAvSz9","#,
                r#""i":"EPXgQxGLRPBzBR84e6hZ_SY1l5-WJU8b_n8ibASNDfKM","s":"3","p":"EMljYBNn3JU_oD8O0_JmQ1Q7"#,
                r#"w3yFnCON9lauFHnDmNju","kt":"1","k":["DNFcsn7EiJemcWD_6bMOdeYUU1j2dC98WCCGjN7PxCIp"],"#,
                r#""nt":"1","n":["EAu_UWkr40QDQWScisiLnv5rCJc5unxnAhu33V1RzzpA"],"bt":"0","br":[],"ba":[],"#,
                r#""a":[]}-AABAACe5_Be6a0cYFts3p5clD7X2RCjkWGQVmKvLjr8ONN9azBqPRQGMj6B7eRwHFQ-AdC98PNA"#,
                r#"niDuFv4BGK8GsvoE"#
            )
        );

        println!("{}", kel);

        Ok(())
    }
}