cyphr 0.1.0

Cyphr self-sovereign identity protocol
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
//! Commit types for atomic coz bundles.
//!
//! Per SPEC §4, a Commit is an atomic bundle of cozies.
//! The Commit ID is the Merkle root of only the cozies in a
//! single commit, not cumulatively.

use crate::parsed_coz::VerifiedCoz;
use crate::state::{AuthRoot, PrincipalRoot, StateRoot, TaggedCzd};

// ============================================================================
// Commit
// ============================================================================

/// A finalized, atomic bundle of cozies.
///
/// Per SPEC §4:
/// - `Commit ID = MR(sort(czd₀, czd₁, ...))` for cozies in this commit only
/// - `CS = MR(AS, Commit ID)` binds the auth state to the commit
/// - `pre` of first coz references previous commit's CS (or promoted AS for genesis)
///
/// A Commit is immutable once finalized.
#[derive(Debug, Clone)]
pub struct Commit {
    /// Transactions in this commit.
    pub(crate) transactions: Vec<crate::transaction::Transaction>,
    /// The terminal commit transaction.
    pub(crate) commit_tx: crate::transaction::CommitTransaction,
    /// Transaction Root: Merkle root of coz czds.
    tr: crate::transaction_root::TransactionRoot,
    /// Auth State at the end of this commit.
    ar: AuthRoot,
    /// State Root at the end of this commit.
    sr: StateRoot,
    /// Principal State at the end of this commit.
    pr: PrincipalRoot,
}

impl Commit {
    /// Create a new finalized commit from cozies and computed states.
    ///
    /// # Errors
    ///
    /// Returns `EmptyCommit` if `cozies` is empty.
    pub(crate) fn new(
        transactions: Vec<crate::transaction::Transaction>,
        commit_tx: crate::transaction::CommitTransaction,
        tr: crate::transaction_root::TransactionRoot,
        ar: AuthRoot,
        sr: StateRoot,
        pr: PrincipalRoot,
    ) -> crate::error::Result<Self> {
        if transactions.is_empty() && commit_tx.0.is_empty() {
            return Err(crate::error::Error::EmptyCommit);
        }
        Ok(Self {
            transactions,
            commit_tx,
            tr,
            ar,
            sr,
            pr,
        })
    }

    /// Get the cozies in this commit.
    pub fn transactions(&self) -> &[crate::transaction::Transaction] {
        &self.transactions
    }
    /// Returns the commit transaction, which is the final logical transaction of the atomic bundle.
    pub fn commit_tx(&self) -> &crate::transaction::CommitTransaction {
        &self.commit_tx
    }
    /// Returns a flat vector of all cozies (mutations + commit).
    pub fn all_cozies(&self) -> Vec<VerifiedCoz> {
        self.iter_all_cozies().cloned().collect()
    }
    /// Iterates over all cozies in this commit bundle (mutations followed by the commit/create synthetic coz).
    pub fn iter_all_cozies(&self) -> impl Iterator<Item = &VerifiedCoz> {
        self.transactions
            .iter()
            .flat_map(|tx| tx.0.iter())
            .chain(self.commit_tx.0.iter())
    }

    /// Get the Commit ID (Merkle root of this commit's czds).
    pub fn tr(&self) -> &crate::transaction_root::TransactionRoot {
        &self.tr
    }

    /// Get the State Root at the end of this commit.
    pub fn sr(&self) -> &StateRoot {
        &self.sr
    }

    /// Get the Auth State at the end of this commit.
    pub fn auth_root(&self) -> &AuthRoot {
        &self.ar
    }

    /// Get the Principal State at the end of this commit.
    pub fn pr(&self) -> &PrincipalRoot {
        &self.pr
    }

    /// Get the number of cozies in this commit.
    pub fn len(&self) -> usize {
        self.iter_all_cozies().count()
    }

    /// Check if the commit is empty (should never be true for valid commits).
    pub fn is_empty(&self) -> bool {
        self.len() == 0
    }
}

// ============================================================================
// PendingCommit
// ============================================================================

/// A commit that is being built but not yet finalized.
/// A commit being built.
/// Accumulates cozies before finalization.
#[derive(Debug, Clone, Default)]
pub struct PendingCommit {
    pub(crate) transactions: Vec<crate::transaction::Transaction>,
    pub(crate) commit_tx: Option<crate::transaction::CommitTransaction>,
}

impl PendingCommit {
    /// Create a new empty pending commit.
    pub fn new() -> Self {
        Self::default()
    }

    /// Add a grouped transaction to the pending commit.
    pub fn push_tx(&mut self, tx: crate::transaction::Transaction) {
        if tx.0.is_empty() {
            return;
        }

        let is_commit = tx.0.iter().any(|cz| cz.arrow().is_some());

        if is_commit {
            match &mut self.commit_tx {
                Some(ctx) => ctx.0.extend(tx.0),
                None => self.commit_tx = Some(crate::transaction::CommitTransaction(tx.0)),
            }
        } else {
            self.transactions.push(tx);
        }
    }

    /// Get the current list of pending cozies.
    pub fn transactions(&self) -> &[crate::transaction::Transaction] {
        &self.transactions
    }
    /// Optionally returns the commit transaction if one has been pushed.
    pub fn commit_tx(&self) -> Option<&crate::transaction::CommitTransaction> {
        self.commit_tx.as_ref()
    }
    /// Returns a flat vector of all cozies (mutations + commit).
    pub fn all_cozies(&self) -> Vec<VerifiedCoz> {
        self.iter_all_cozies().cloned().collect()
    }
    /// Iterates over all current cozies within the pending commit.
    pub fn iter_all_cozies(&self) -> impl Iterator<Item = &VerifiedCoz> {
        self.transactions
            .iter()
            .flat_map(|tx| tx.0.iter())
            .chain(self.commit_tx.iter().flat_map(|ctx| ctx.0.iter()))
    }

    /// Check if the pending commit is empty.
    pub fn is_empty(&self) -> bool {
        self.len() == 0
    }

    /// Get the number of pending cozies.
    pub fn len(&self) -> usize {
        self.iter_all_cozies().count()
    }

    /// Compute the Transaction Roots (TMR, TCR, TR) for the current pending cozies.
    pub fn compute_roots(
        &self,
        algs: &[coz::HashAlg],
    ) -> (
        Option<crate::transaction_root::TransactionMutationRoot>,
        Option<crate::transaction_root::TransactionCommitRoot>,
        Option<crate::transaction_root::TransactionRoot>,
    ) {
        if self.is_empty() {
            return (None, None, None);
        }

        let mut tx_roots = Vec::new();
        for tx in &self.transactions {
            let tx_czds: Vec<TaggedCzd<'_>> =
                tx.0.iter()
                    .map(|t| TaggedCzd::new(t.czd(), t.hash_alg()))
                    .collect();
            if let Some(mh) = crate::transaction_root::compute_tx(&tx_czds, algs) {
                tx_roots.push(mh);
            }
        }
        let tx_refs: Vec<&crate::multihash::MultihashDigest> = tx_roots.iter().collect();
        let tmr = crate::transaction_root::compute_tmr(&tx_refs, algs);

        if let Some(ctx) = &self.commit_tx {
            let ctx_czds: Vec<TaggedCzd<'_>> = ctx
                .0
                .iter()
                .map(|t| TaggedCzd::new(t.czd(), t.hash_alg()))
                .collect();
            if let Some(tcr) = crate::transaction_root::compute_tcr(&ctx_czds, algs) {
                let tr = crate::transaction_root::compute_tr(tmr.as_ref(), &tcr, algs);
                return (tmr, Some(tcr), tr);
            }
        }
        (tmr, None, None)
    }

    /// Compute the Transaction Root (TR) for the current pending cozies.
    pub fn compute_tr(
        &self,
        algs: &[coz::HashAlg],
    ) -> Option<crate::transaction_root::TransactionRoot> {
        self.compute_roots(algs).2
    }

    /// Finalize the pending commit into an immutable `Commit`.
    ///
    /// # Arguments
    ///
    /// * `auth_root` - The computed Auth State after all cozies
    /// * `sr` - The computed State Root: MR(AR, DR?, embedding?)
    /// * `ps` - The computed Principal State after all cozies
    /// * `tx_algs` - Explicit transaction algorithm set footprint (extracted from Arrow)
    ///
    /// # Errors
    ///
    /// Returns `EmptyCommit` if no cozies exist.
    pub fn finalize(
        self,
        ar: AuthRoot,
        sr: StateRoot,
        pr: PrincipalRoot,
        tx_algs: &[coz::HashAlg],
    ) -> crate::error::Result<Commit> {
        if self.is_empty() {
            return Err(crate::error::Error::EmptyCommit);
        }

        let commit_tx = self
            .commit_tx
            .clone()
            .ok_or(crate::error::Error::MalformedPayload)?; // Must have a commit tx to finalize

        let tr = self
            .compute_tr(tx_algs)
            .ok_or(crate::error::Error::EmptyCommit)?;

        Commit::new(self.transactions, commit_tx, tr, ar, sr, pr)
    }

    /// Consume the pending commit and return the cozies.
    ///
    /// Use this for rollback or when abandoning a pending commit.
    pub fn into_transactions(self) -> Vec<VerifiedCoz> {
        self.iter_all_cozies().cloned().collect()
    }
}

// ============================================================================
// CommitScope
// ============================================================================

/// A scoped commit builder that holds an exclusive borrow of a `Principal`.
///
/// Created via [`Principal::begin_commit()`]. Transactions are applied with
/// [`apply()`](Self::apply), and the commit is finalized by calling
/// [`finalize()`](Self::finalize) which consumes the scope and returns a
/// reference to the new [`Commit`].
///
/// # Typestate Enforcement
///
/// The borrow checker ensures that while a `CommitScope` exists:
/// - No external code can read or mutate the `Principal`
/// - Intermediate state (after apply but before finalize) is unobservable
///
/// This structurally prevents the "pending commit trap" where consumers
/// forget to finalize after applying cozies.
///
/// # Single-ParsedCoz Convenience
///
/// For the common case of applying a single coz as an atomic commit,
/// use [`Principal::apply_transaction()`] instead of creating a scope manually.
///
/// # Example
///
/// ```ignore
/// // Multi-coz commit:
/// let mut scope = principal.begin_commit();
/// scope.apply(vtx1)?;
/// scope.apply(vtx2)?;
/// let commit = scope.finalize()?;
///
/// // Single-coz commit (convenience):
/// let commit = principal.apply_transaction(vtx)?;
/// ```
#[must_use = "a CommitScope must be finalized via .finalize() to produce a Commit"]
pub struct CommitScope<'a> {
    principal: &'a mut crate::principal::Principal,
    pending: PendingCommit,
    /// Snapshot of active keys at commit-start time for authorization.
    ///
    /// Per [pre-mutation-key-rule]: signatures within a commit are verified
    /// against the key set that was active when the commit began, not the
    /// eagerly-mutated live state. This ensures that a key replaced mid-commit
    /// can still sign the terminal commit/create coz.
    pre_commit_keys: std::collections::BTreeMap<String, crate::key::Key>,
}

impl<'a> CommitScope<'a> {
    /// Create a new commit scope for the given principal.
    ///
    /// Snapshots the active key set for [pre-mutation-key-rule] authorization.
    /// This is called by [`Principal::begin_commit()`].
    pub(crate) fn new(principal: &'a mut crate::principal::Principal) -> Self {
        let _hash_alg = principal.hash_alg();
        // Snapshot active keys for pre-mutation authorization checks
        let pre_commit_keys: std::collections::BTreeMap<String, crate::key::Key> = principal
            .active_keys()
            .map(|k| (k.tmb.to_b64(), k.clone()))
            .collect();
        Self {
            principal,
            pending: PendingCommit::new(),
            pre_commit_keys,
        }
    }

    /// Apply a verified coz within this commit scope.
    ///
    /// The coz mutates the principal's state eagerly (keys, timestamps,
    /// etc.). The borrow checker ensures no external code can observe this
    /// intermediate state.
    ///
    /// The coz is accumulated in the pending commit for finalization.
    ///
    /// # Errors
    ///
    /// - `TimestampPast`: ParsedCoz timestamp is older than latest seen
    /// - `TimestampFuture`: ParsedCoz timestamp is too far in the future
    /// - `InvalidPrior`: ParsedCoz's `pre` doesn't match current CS
    /// - `NoActiveKeys`: Would leave principal with no active keys
    /// - `DuplicateKey`: Adding key already in KS
    pub fn apply(&mut self, vtx: VerifiedCoz) -> crate::error::Result<()> {
        self.principal.apply_verified_internal(vtx.clone())?;
        self.pending
            .push_tx(crate::transaction::Transaction(vec![vtx]));
        Ok(())
    }

    /// Apply a grouped transaction (multiple cozies) within this commit scope.
    ///
    /// State mutations are applied sequentially, but the cozies are grouped in the Merkle tree.
    pub fn apply_tx(&mut self, vts: Vec<VerifiedCoz>) -> crate::error::Result<()> {
        let mut tx = Vec::with_capacity(vts.len());
        for vt in vts {
            self.principal.apply_verified_internal(vt.clone())?;
            tx.push(vt);
        }
        self.pending.push_tx(crate::transaction::Transaction(tx));
        Ok(())
    }

    /// Finalize the commit scope, producing an immutable `Commit`.
    ///
    /// Consumes this scope and returns a reference to the newly created
    /// `Commit` within the principal's auth ledger.
    ///
    /// # Errors
    ///
    /// Returns `EmptyCommit` if no cozies were applied.
    pub fn finalize(self) -> crate::error::Result<&'a Commit> {
        self.principal.finalize_commit(self.pending)
    }

    /// Verify a coz signature and apply it within this commit scope.
    ///
    /// This combines signature verification and application in one call,
    /// analogous to `Principal::verify_and_apply_transaction` but within
    /// a multi-coz commit scope.
    ///
    /// # Arguments
    ///
    /// * `pay_json` - Raw JSON bytes of the Pay object
    /// * `sig` - Signature bytes
    /// * `czd` - Coz digest for this coz
    /// * `new_key` - New key to add (required for KeyCreate/KeyReplace)
    pub fn verify_and_apply(
        &mut self,
        pay_json: &[u8],
        sig: &[u8],
        czd: coz::Czd,
        new_key: Option<crate::key::Key>,
    ) -> crate::error::Result<()> {
        use crate::parsed_coz::verify_coz;

        // Parse Pay to get signer thumbprint
        let pay: coz::Pay =
            serde_json::from_slice(pay_json).map_err(|_| crate::error::Error::MalformedPayload)?;
        let signer_tmb = pay
            .tmb
            .as_ref()
            .ok_or(crate::error::Error::MalformedPayload)?;

        // [pre-mutation-key-rule]: Check authorization against the snapshot
        // of keys that were active when this commit began, not the eagerly
        // mutated live state. Keys added during the commit are also accepted.
        let tmb_str = signer_tmb.to_b64();
        let signer_key = if let Some(key) = self.pre_commit_keys.get(&tmb_str) {
            key
        } else if self.principal.is_key_active(signer_tmb) {
            // Key was added during this commit — accept it
            self.principal
                .get_key(signer_tmb)
                .ok_or(crate::error::Error::UnknownKey)?
        } else if self.principal.is_key_revoked(signer_tmb) {
            return Err(crate::error::Error::KeyRevoked);
        } else {
            return Err(crate::error::Error::UnknownKey);
        };

        // Verify signature and parse coz
        let vtx = verify_coz(pay_json, sig, signer_key, czd, new_key)?;

        // Apply within this scope
        self.apply(vtx)
    }

    /// Get the principal's primary hash algorithm.
    pub fn principal_hash_alg(&self) -> crate::state::HashAlg {
        self.principal.hash_alg()
    }
    /// Get the number of cozies applied so far.
    pub fn len(&self) -> usize {
        self.pending.len()
    }

    /// Check if no cozies have been applied yet.
    pub fn is_empty(&self) -> bool {
        self.pending.is_empty()
    }

    /// Finalize the commit by generating and signing a `commit/create` coz with the `arrow` field.
    ///
    /// This replaces `finalize_with_commit` and splits the mutation from finality.
    /// The caller MUST have previously applied transactions via `verify_and_apply` or `apply`.
    ///
    /// # Arguments
    ///
    /// * `alg` - Signer algorithm string (e.g. "ES256")
    /// * `prv_key` - Private key bytes for signing the Arrow
    /// * `pub_key` - Public key bytes
    /// * `tmb` - The thumbprint of the signer key
    /// * `now` - Timestamp for the commit coz
    ///
    /// # Errors
    ///
    /// - `EmptyCommit`: if no mutations exist.
    pub fn finalize_with_arrow(
        mut self,
        alg: &str,
        prv_key: &[u8],
        pub_key: &[u8],
        tmb: &coz::Thumbprint,
        now: i64,
        authority: &str,
    ) -> crate::error::Result<&'a Commit> {
        use crate::parsed_coz::{ParsedCoz, VerifiedCoz};
        use crate::state::{hash_alg_from_str, hash_sorted_concat_bytes};
        use coz::base64ct::{Base64UrlUnpadded, Encoding};
        use serde_json::json;

        if self.is_empty() {
            return Err(crate::error::Error::EmptyCommit);
        }

        let signer_hash_alg = hash_alg_from_str(alg)?;

        // 1. Recompute KR → AR → SR to get post-mutation SR for Arrow construction.
        //    This does not mutate self.principal; it reads the current key set.
        let key_refs: Vec<&crate::key::Key> = self.principal.auth.keys.values().collect();
        let active_algs = crate::state::derive_hash_algs(&key_refs);
        let thumbprints: Vec<&coz::Thumbprint> =
            self.principal.auth.keys.values().map(|k| &k.tmb).collect();
        let (_kr, _ar, sr) = crate::state::derive_auth_state(
            &thumbprints,
            self.principal.dr.as_ref(),
            &active_algs,
        )?;

        // For TMR we just use compute_roots early
        let (tmr, _, _) = self.pending.compute_roots(&[signer_hash_alg]);
        let tmr = tmr.ok_or(crate::error::Error::EmptyCommit)?;

        // 2. Compute Arrow = MR(pre, sr, tmr)
        // Arrow computation requires pre, sr, tmr slices
        // Wait, pre is the principal root of the previous state!
        // Where is pre? It's self.principal.pr!
        let pre = &self.principal.pr;

        let pre_bytes = pre.0.get_or_err(signer_hash_alg)?;
        let sr_bytes = sr.0.get_or_err(signer_hash_alg)?;
        let tmr_bytes = tmr.0.get_or_err(signer_hash_alg)?;

        // Arrow = MR(pre, fwd, TMR)
        let arrow_digest =
            hash_sorted_concat_bytes(signer_hash_alg, &[pre_bytes, sr_bytes, tmr_bytes]);

        // Arrow string format
        let arrow_tagged = format!(
            "{}:{}",
            signer_hash_alg,
            Base64UrlUnpadded::encode_string(&arrow_digest)
        );

        // 3. Construct commit/create payload
        // Full typ = "{authority}/{suffix}" per SPEC §7.2.
        let commit_typ = format!("{authority}/{}", crate::parsed_coz::typ::COMMIT_CREATE);
        let mut pay = serde_json::Map::new();
        pay.insert("alg".to_string(), json!(alg));
        pay.insert("arrow".to_string(), json!(arrow_tagged));
        pay.insert("now".to_string(), json!(now));
        pay.insert("tmb".to_string(), json!(tmb.to_b64()));
        pay.insert("typ".to_string(), json!(commit_typ));

        let mut pay_obj = serde_json::Value::Object(pay);
        // Ensure deterministic order
        if let Some(obj) = pay_obj.as_object_mut() {
            obj.sort_keys();
        }

        let pay_vec =
            serde_json::to_vec(&pay_obj).map_err(|_| crate::error::Error::MalformedPayload)?;
        let (sig, cad) = coz::sign_json(&pay_vec, alg, prv_key, pub_key)
            .ok_or(crate::error::Error::MalformedPayload)?;
        let czd = coz::czd_for_alg(&cad, &sig, alg).ok_or(crate::error::Error::MalformedPayload)?;

        let raw = coz::CozJson {
            pay: pay_obj.clone(),
            sig: sig.clone(),
        };

        let parsed_pay: coz::Pay = serde_json::from_value(pay_obj.clone())
            .map_err(|_| crate::error::Error::MalformedPayload)?;

        let arrow_tx = ParsedCoz::from_pay(&parsed_pay, czd, signer_hash_alg, raw)?;
        let arrow_vtx = VerifiedCoz::from_parts(arrow_tx, None);

        // 4. Push commit marker and finalize
        self.pending
            .push_tx(crate::transaction::Transaction(vec![arrow_vtx]));
        self.finalize()
    }
}

// ============================================================================
// Tests
// ============================================================================

#[cfg(test)]
mod tests {
    use super::*;
    use crate::multihash::MultihashDigest;
    use crate::parsed_coz::{ParsedCoz, VerifiedCoz};
    use crate::state::HashAlg;
    use coz::{Czd, PayBuilder, Thumbprint};
    use serde_json::json;

    // Valid alg:digest format for 32-byte SHA-256 digests
    const TEST_PRE: &str = "SHA-256:U5XUZots-WmQYcQWmsO751Xk0yeVi9XUKWQ2mGz6Aqg";
    const TEST_ID: &str = "xrYMu87EXes58PnEACcDW1t0jF2ez4FCN-njTF0MHNo";

    /// Create a test coz. When `is_commit` is true, creates a commit/create
    /// coz with an arrow field (routes to commit_tx via push). When false,
    /// creates a mutation coz (routes to transactions).
    fn make_test_tx(is_commit: bool, czd_byte: u8) -> VerifiedCoz {
        let typ = if is_commit {
            "cyphr.me/cyphr/commit/create"
        } else {
            "cyphr.me/cyphr/key/create"
        };
        let mut pay = PayBuilder::new()
            .typ(typ)
            .alg("ES256")
            .now(1000)
            .tmb(Thumbprint::from_bytes(vec![0xAA; 32]))
            .build();
        if !is_commit {
            pay.extra.insert("pre".into(), json!(TEST_PRE));
            pay.extra.insert("id".into(), json!(TEST_ID));
        }
        if is_commit {
            pay.extra.insert(
                "arrow".into(),
                json!("SHA-256:U5XUZots-WmQYcQWmsO751Xk0yeVi9XUKWQ2mGz6Aqg"),
            );
        }

        let czd = Czd::from_bytes(vec![czd_byte; 32]);
        let raw = coz::CozJson {
            pay: serde_json::to_value(&pay).unwrap(),
            sig: vec![0; 64],
        };
        let cz = ParsedCoz::from_pay(&pay, czd, HashAlg::Sha256, raw).unwrap();
        VerifiedCoz::from_transaction_unsafe(cz, None)
    }

    // ========================================================================
    // PendingCommit Tests
    // ========================================================================

    #[test]
    fn pending_commit_empty_state() {
        let pending = PendingCommit::new();
        assert!(pending.is_empty());
        assert_eq!(pending.len(), 0);
        assert!(pending.compute_tr(&[coz::HashAlg::Sha256]).is_none());
    }

    #[test]
    fn pending_commit_push_adds_transactions() {
        let mut pending = PendingCommit::new();

        // Push cozies
        let tx1 = make_test_tx(false, 0x01);
        pending.push_tx(crate::transaction::Transaction(vec![tx1]));
        assert_eq!(pending.len(), 1);

        let tx2 = make_test_tx(true, 0x02);
        pending.push_tx(crate::transaction::Transaction(vec![tx2]));
        assert_eq!(pending.len(), 2);
    }

    #[test]
    fn pending_commit_compute_tr_returns_merkle_root() {
        let mut pending = PendingCommit::new();
        let tx1 = make_test_tx(false, 0x01);
        pending
            .transactions
            .push(crate::transaction::Transaction(vec![tx1.clone()]));
        let ctx = crate::transaction::CommitTransaction(vec![tx1]);
        pending.commit_tx = Some(ctx);

        let tr = pending.compute_tr(&[coz::HashAlg::Sha256]);
        assert!(tr.is_some());
        // Commit ID should be 32 bytes (SHA256)
        assert_eq!(
            tr.clone().unwrap().0.get(HashAlg::Sha256).unwrap().len(),
            32
        );
    }

    #[test]
    fn pending_commit_finalize_succeeds_with_finalizer() {
        let mut pending = PendingCommit::new();
        let cz = make_test_tx(true, 0x01);
        pending.push_tx(crate::transaction::Transaction(vec![cz]));

        let auth_root = AuthRoot(MultihashDigest::from_single(
            HashAlg::Sha256,
            vec![0xAA; 32],
        ));
        let sr = StateRoot(MultihashDigest::from_single(
            HashAlg::Sha256,
            vec![0xCC; 32],
        ));
        let ps = PrincipalRoot(MultihashDigest::from_single(
            HashAlg::Sha256,
            vec![0xBB; 32],
        ));

        let commit = pending.finalize(
            auth_root.clone(),
            sr.clone(),
            ps.clone(),
            &[coz::HashAlg::Sha256],
        );
        assert!(commit.is_ok());

        let commit = commit.unwrap();
        assert_eq!(commit.len(), 1);
        assert_eq!(commit.auth_root(), &auth_root);
        assert_eq!(commit.sr(), &sr);
        assert_eq!(commit.pr(), &ps);
    }

    #[test]
    fn pending_commit_finalize_fails_without_finalizer_marker() {
        // Finalizer must be present to distinguish the commit transaction
        let mut pending = PendingCommit::new();
        let cz = make_test_tx(false, 0x01); // No finalizer marker
        pending.push_tx(crate::transaction::Transaction(vec![cz]));

        let auth_root = AuthRoot(MultihashDigest::from_single(
            HashAlg::Sha256,
            vec![0xAA; 32],
        ));
        let sr = StateRoot(MultihashDigest::from_single(
            HashAlg::Sha256,
            vec![0xCC; 32],
        ));
        let ps = PrincipalRoot(MultihashDigest::from_single(
            HashAlg::Sha256,
            vec![0xBB; 32],
        ));

        let result = pending.finalize(auth_root, sr, ps, &[coz::HashAlg::Sha256]);
        assert!(
            matches!(result, Err(crate::error::Error::MalformedPayload)),
            "finalize should fail without finalizer marker"
        );
    }

    #[test]
    fn pending_commit_finalize_fails_when_empty() {
        let pending = PendingCommit::new();

        let auth_root = AuthRoot(MultihashDigest::from_single(
            HashAlg::Sha256,
            vec![0xAA; 32],
        ));
        let sr = StateRoot(MultihashDigest::from_single(
            HashAlg::Sha256,
            vec![0xCC; 32],
        ));
        let ps = PrincipalRoot(MultihashDigest::from_single(
            HashAlg::Sha256,
            vec![0xBB; 32],
        ));

        let result = pending.finalize(auth_root, sr, ps, &[coz::HashAlg::Sha256]);
        assert!(result.is_err(), "should fail when empty");
    }

    #[test]
    fn pending_commit_into_transactions_returns_accumulated() {
        let mut pending = PendingCommit::new();
        pending.push_tx(crate::transaction::Transaction(vec![make_test_tx(
            false, 0x01,
        )]));
        pending.push_tx(crate::transaction::Transaction(vec![make_test_tx(
            true, 0x02,
        )]));

        let cozies = pending.into_transactions();
        assert_eq!(cozies.len(), 2);
    }

    // ========================================================================
    // Commit Tests
    // ========================================================================

    #[test]
    fn commit_accessors_return_correct_values() {
        let mut pending = PendingCommit::new();
        pending.push_tx(crate::transaction::Transaction(vec![make_test_tx(
            true, 0x01,
        )]));

        let auth_root = AuthRoot(MultihashDigest::from_single(
            HashAlg::Sha256,
            vec![0xAA; 32],
        ));
        let sr = StateRoot(MultihashDigest::from_single(
            HashAlg::Sha256,
            vec![0xCC; 32],
        ));
        let ps = PrincipalRoot(MultihashDigest::from_single(
            HashAlg::Sha256,
            vec![0xBB; 32],
        ));

        let commit = pending
            .finalize(
                auth_root.clone(),
                sr.clone(),
                ps.clone(),
                &[coz::HashAlg::Sha256],
            )
            .unwrap();

        // Test all accessors
        assert_eq!(commit.iter_all_cozies().count(), 1);
        assert!(!commit.is_empty());
        assert_eq!(commit.len(), 1);
        assert_eq!(commit.auth_root(), &auth_root);
        assert_eq!(commit.sr(), &sr);
        assert_eq!(commit.pr(), &ps);
        assert_eq!(commit.tr().0.get(HashAlg::Sha256).unwrap().len(), 32);
    }

    #[test]
    fn commit_multi_transaction_computes_correct_tr() {
        let mut pending = PendingCommit::new();
        pending.push_tx(crate::transaction::Transaction(vec![make_test_tx(
            false, 0x01,
        )]));
        pending.push_tx(crate::transaction::Transaction(vec![make_test_tx(
            false, 0x02,
        )]));
        pending.push_tx(crate::transaction::Transaction(vec![make_test_tx(
            true, 0x03,
        )])); // finalizer

        let auth_root = AuthRoot(MultihashDigest::from_single(
            HashAlg::Sha256,
            vec![0xAA; 32],
        ));
        let sr = StateRoot(MultihashDigest::from_single(
            HashAlg::Sha256,
            vec![0xCC; 32],
        ));
        let ps = PrincipalRoot(MultihashDigest::from_single(
            HashAlg::Sha256,
            vec![0xBB; 32],
        ));

        let commit = pending
            .finalize(auth_root, sr, ps, &[coz::HashAlg::Sha256])
            .unwrap();
        assert_eq!(commit.len(), 3);

        // Commit ID should be Merkle root of all 3 coz czds
        let cid = &commit.tr().0;
        assert_eq!(cid.get(HashAlg::Sha256).unwrap().len(), 32);
    }

    #[test]
    fn test_cozjson_serialization() {
        let mut pay = json!({"typ": "test", "now": 1234});
        pay.as_object_mut()
            .unwrap()
            .insert("commit".to_string(), json!("SHA-256:abc"));

        // Use coz::CozJson directly to see if it drops the field!
        let raw = coz::CozJson {
            pay: pay.clone(),
            sig: vec![0, 1, 2],
        };

        let out = serde_json::to_string(&raw).unwrap();
        assert!(
            out.contains("commit"),
            "coz::CozJson serialization dropped 'commit'! Output: {}",
            out
        );
    }
}