libveritas 0.1.2

Offline verification library for Spaces protocol certificates and zone records.
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
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
use bitcoin::hashes::Hash as BitcoinHash;
use bitcoin::key::Keypair;
use bitcoin::key::rand::Rng;
use bitcoin::secp256k1::Secp256k1;
use bitcoin::secp256k1::rand;
use bitcoin::{BlockHash, OutPoint, ScriptBuf, Txid};
use borsh::{BorshDeserialize, BorshSerialize};
use libveritas::cert::{
    Certificate, HandleOut, HandleSubtree, KeyHash, NumsSubtree, Signature, SpacesSubtree, Witness,
};
use libveritas::msg::{self, Message, QueryContext};
use libveritas::{ProvableOption, SovereigntyState, Veritas, Zone, hash_signable_message};
use risc0_zkvm::{FakeReceipt, InnerReceipt, Receipt, ReceiptClaim};
use spacedb::Sha256Hasher;
use spacedb::subtree::{ProofType, SubTree, ValueOrHash};
use spaces_nums::constants::COMMITMENT_FINALITY_INTERVAL;
use spaces_nums::num_id::NumId;
use spaces_nums::snumeric::SNumeric;
use spaces_nums::{
    CommitmentKey, CommitmentTipKey, DelegatorKey, FullNumOut, Num, NumOut, NumOutpointKey,
    RootAnchor, rolling_hash,
};
use spaces_protocol::constants::ChainAnchor;
use spaces_protocol::hasher::{KeyHasher, OutpointKey, SpaceKey};
use spaces_protocol::slabel::SLabel;
use spaces_protocol::sname::{SName, Subname};
use spaces_protocol::{Covenant, FullSpaceOut, Space, SpaceOut};
use std::collections::HashMap;
use std::str::FromStr;

fn sname(s: &str) -> SName {
    SName::from_str(s).unwrap()
}

fn slabel(s: &str) -> SLabel {
    SLabel::from_str(s).unwrap()
}

fn label(s: &str) -> Subname {
    Subname::from_str(s).unwrap()
}

fn sign_zone(zone: &Zone, keypair: &Keypair) -> Signature {
    let msg = hash_signable_message(&zone.signing_bytes());
    let secp = Secp256k1::new();
    let sig = secp.sign_schnorr_no_aux_rand(&msg, keypair);
    Signature(sig.serialize())
}

#[derive(BorshSerialize, BorshDeserialize)]
pub struct EncodableOutpoint(
    #[borsh(
        serialize_with = "borsh_utils::serialize_outpoint",
        deserialize_with = "borsh_utils::deserialize_outpoint"
    )]
    pub OutPoint,
);

fn gen_p2tr_spk() -> (ScriptBuf, Keypair) {
    use bitcoin::opcodes::all::OP_PUSHNUM_1;
    use bitcoin::script::Builder;

    let secp = Secp256k1::new();
    let (secret_key, public_key) = secp.generate_keypair(&mut rand::thread_rng());
    let keypair = Keypair::from_secret_key(&secp, &secret_key);
    let (xonly, _parity) = public_key.x_only_public_key();

    // Build witness v1 script with untweaked pubkey (no taproot tweak)
    let script = Builder::new()
        .push_opcode(OP_PUSHNUM_1)
        .push_slice(xonly.serialize())
        .into_script();

    (script, keypair)
}

#[derive(Clone)]
pub struct TestSpace {
    pub fso: FullSpaceOut,
    pub keypair: Keypair,
}

#[derive(Clone)]
pub struct TestNum {
    pub fso: FullNumOut,
    pub keypair: Keypair,
}

impl TestSpace {
    pub fn new(name: &str, block_height: u32) -> Self {
        let mut rng = rand::thread_rng();
        let mut txid_bytes = [0u8; 32];
        rng.fill(&mut txid_bytes);

        let txid = Txid::from_slice(&txid_bytes).expect("valid txid");
        let n: u32 = rng.r#gen();
        let (script_pubkey, keypair) = gen_p2tr_spk();

        let fso = FullSpaceOut {
            txid,
            spaceout: SpaceOut {
                n: n as usize,
                space: Some(Space {
                    name: slabel(name),
                    covenant: Covenant::Transfer {
                        expire_height: block_height + spaces_protocol::constants::RENEWAL_INTERVAL,
                        data: None,
                    },
                }),
                value: Default::default(),
                script_pubkey,
            },
        };

        TestSpace { fso, keypair }
    }

    pub fn label(&self) -> SLabel {
        self.fso
            .spaceout
            .space
            .as_ref()
            .expect("valid space")
            .name
            .clone()
    }

    pub fn outpoint_key(&self) -> OutpointKey {
        OutpointKey::from_outpoint::<KeyHash>(self.fso.outpoint())
    }

    pub fn script_pubkey(&self) -> ScriptBuf {
        self.fso.spaceout.script_pubkey.clone()
    }

    pub fn space_key(&self) -> SpaceKey {
        SpaceKey::from(KeyHash::hash(self.label().as_ref()))
    }

    pub fn spaceout_bytes(&self) -> Vec<u8> {
        borsh::to_vec(&self.fso.spaceout).expect("valid")
    }

    pub fn outpoint_bytes(&self) -> Vec<u8> {
        borsh::to_vec(&EncodableOutpoint(self.fso.outpoint())).expect("valid")
    }
}

impl TestNum {
    pub fn new(genesis_spk: ScriptBuf, block_height: u32) -> Self {
        let num_id = NumId::from_spk::<KeyHash>(genesis_spk);

        let mut rng = rand::thread_rng();
        let mut txid_bytes = [0u8; 32];
        rng.fill(&mut txid_bytes);

        let txid = Txid::from_slice(&txid_bytes).expect("valid txid");
        let n: u32 = rng.r#gen();
        let (script_pubkey, keypair) = gen_p2tr_spk();

        let fso = FullNumOut {
            txid,
            numout: NumOut {
                n: n as usize,
                num: Num {
                    id: num_id,
                    name: SNumeric::new(0, 0, 0),
                    data: None,
                    last_update: block_height,
                },
                value: Default::default(),
                script_pubkey,
            },
        };

        TestNum { fso, keypair }
    }

    pub fn id(&self) -> NumId {
        self.fso.numout.num.id
    }

    pub fn outpoint_key(&self) -> NumOutpointKey {
        NumOutpointKey::from_outpoint::<KeyHash>(self.fso.outpoint())
    }

    pub fn numout_bytes(&self) -> Vec<u8> {
        borsh::to_vec(&self.fso.numout).expect("valid")
    }

    pub fn outpoint_bytes(&self) -> Vec<u8> {
        borsh::to_vec(&EncodableOutpoint(self.fso.outpoint())).expect("valid")
    }
}

#[derive(Clone)]
pub struct TestChain {
    pub spaces_tree: SubTree<Sha256Hasher>,
    pub nums_tree: SubTree<Sha256Hasher>,
    pub spaces: HashMap<SLabel, TestSpace>,
    pub nums: HashMap<NumId, TestNum>,
    pub block_height: u32,
}

pub struct TestHandleTree {
    pub space: SLabel,
    pub ds: TestDelegatedSpace,
    pub handle_tree: SubTree<Sha256Hasher>,
    pub commitments: Vec<TestCommitmentBundle>,
    pub staged: HashMap<Subname, StagedHandle>,
}

pub struct StagedHandle {
    pub handle: TestHandle,
    pub signature: Signature,
}

pub struct TestCommitmentBundle {
    root: [u8; 32],
    handles: HashMap<Subname, TestHandle>,
    handle_tree: SubTree<Sha256Hasher>,
    receipt: Option<Receipt>,
}

impl Default for TestChain {
    fn default() -> Self {
        Self::new()
    }
}

impl TestChain {
    pub fn new() -> Self {
        Self {
            spaces_tree: SubTree::empty(),
            nums_tree: SubTree::empty(),
            spaces: Default::default(),
            nums: Default::default(),
            block_height: 0,
        }
    }

    pub fn increase_time(&mut self, n: u32) {
        self.block_height += n;
    }

    pub fn add_space(&mut self, name: &str) -> TestSpace {
        let space = TestSpace::new(name, self.block_height);
        assert!(!self.spaces.contains_key(&space.label()));

        // insert outpoint -> spaceout mapping
        self.spaces_tree
            .insert(
                space.outpoint_key().into(),
                ValueOrHash::Value(space.spaceout_bytes()),
            )
            .expect("insert space");
        // insert space -> outpoint mapping
        self.spaces_tree
            .insert(
                space.space_key().into(),
                ValueOrHash::Value(space.outpoint_bytes()),
            )
            .expect("insert outpoint");
        self.spaces.insert(space.label(), space.clone());

        space
    }

    pub fn current_root_anchor(&self) -> RootAnchor {
        let spaces_root = self.spaces_tree.compute_root().expect("spaces root");
        let nums_root = self.nums_tree.compute_root().expect("nums root");

        let block_hash =
            BlockHash::from_byte_array(rolling_hash::<KeyHash>(spaces_root, nums_root));

        RootAnchor {
            spaces_root,
            nums_root: Some(nums_root),
            block: ChainAnchor {
                hash: block_hash,
                height: self.block_height,
            },
        }
    }

    pub fn add_num(&mut self, genesis_spk: ScriptBuf) -> TestNum {
        let num = TestNum::new(genesis_spk, self.block_height);
        assert!(!self.nums.contains_key(&num.id()));

        // Insert outpoint -> numout mapping
        self.nums_tree
            .insert(
                num.outpoint_key().into(),
                ValueOrHash::Value(num.numout_bytes()),
            )
            .expect("insert num");

        // Insert NumId -> outpoint mapping
        self.nums_tree
            .insert(num.id().into(), ValueOrHash::Value(num.outpoint_bytes()))
            .expect("insert outpoint");
        self.nums.insert(num.id(), num.clone());
        num
    }

    pub fn add_space_with_delegation(&mut self, name: &str) -> TestDelegatedSpace {
        let space = self.add_space(name);
        let num = self.add_num(space.script_pubkey());

        // insert NumId -> Space mapping
        let delegator_key = DelegatorKey::from_id::<KeyHash>(num.id());
        self.nums_tree
            .insert(
                delegator_key.into(),
                ValueOrHash::Value(space.label().as_ref().to_vec()),
            )
            .expect("insert delegator key");

        TestDelegatedSpace { space, ptr: num }
    }

    pub fn insert_commitment(
        &mut self,
        ds: &TestDelegatedSpace,
        root: [u8; 32],
    ) -> spaces_nums::Commitment {
        let prev_finalized = self.rollback_to_finalized_commitment(&ds.space.label());

        let commitment = match prev_finalized {
            None => spaces_nums::Commitment {
                state_root: root,
                prev_root: None,
                rolling_hash: root,
                block_height: self.block_height,
            },
            Some(prev) => spaces_nums::Commitment {
                state_root: root,
                prev_root: Some(prev.state_root),
                rolling_hash: rolling_hash::<KeyHash>(prev.rolling_hash, root),
                block_height: self.block_height,
            },
        };

        let commitment_key = CommitmentKey::new::<KeyHash>(&ds.space.label(), root);

        let commitment_bytes = borsh::to_vec(&commitment).expect("valid");

        self.nums_tree
            .insert(commitment_key.into(), ValueOrHash::Value(commitment_bytes))
            .expect("insert commitment");
        let registry_key = CommitmentTipKey::from_slabel::<KeyHash>(&ds.space.label());
        self.nums_tree
            .update(
                registry_key.into(),
                ValueOrHash::Value(commitment.state_root.to_vec()),
            )
            .expect("insert registry");

        commitment
    }

    // If no root specified, will get the tip
    pub fn get_commitment(
        &self,
        space: &SLabel,
        root: Option<[u8; 32]>,
    ) -> Option<spaces_nums::Commitment> {
        let root = match root {
            Some(root) => Some(root),
            None => {
                let registry_key = CommitmentTipKey::from_slabel::<KeyHash>(space);
                let rkh: [u8; 32] = registry_key.into();
                self.nums_tree
                    .iter()
                    .find(|(k, _)| **k == rkh)
                    .map(|(_, v)| {
                        let mut h = [0u8; 32];
                        h.copy_from_slice(v);
                        h
                    })
            }
        }?;

        let commitment_key = CommitmentKey::new::<KeyHash>(space, root);
        let ckh: [u8; 32] = commitment_key.into();
        self.nums_tree
            .iter()
            .find(|(k, _)| **k == ckh)
            .map(|(_, v)| {
                let commitment: spaces_nums::Commitment =
                    borsh::from_slice(v).expect("valid commitment");
                commitment
            })
    }

    pub fn rollback_to_finalized_commitment(
        &mut self,
        space: &SLabel,
    ) -> Option<spaces_nums::Commitment> {
        let commitment = self.get_commitment(space, None)?;
        if commitment.is_finalized(self.block_height) {
            return Some(commitment);
        }

        // it's not finalized, so delete it
        let registry_key = CommitmentTipKey::from_slabel::<KeyHash>(space);
        let commitment_key = CommitmentKey::new::<KeyHash>(space, commitment.state_root);
        let mut nums_tree = self.nums_tree.clone();
        nums_tree = nums_tree.delete(&registry_key.into()).expect("delete");
        nums_tree = nums_tree.delete(&commitment_key.into()).expect("delete");
        self.nums_tree = nums_tree;

        // there can only be one unfinalized commitment, so prev is finalized if it exists
        let prev_root = commitment.prev_root?;
        let finalized = self.get_commitment(space, Some(prev_root))?;

        // update tip pointer
        self.nums_tree
            .update(
                registry_key.into(),
                ValueOrHash::Value(finalized.state_root.to_vec()),
            )
            .expect("update");

        Some(finalized)
    }
}

pub struct TestHandle {
    pub name: Subname,
    pub genesis_spk: ScriptBuf,
    pub keypair: Keypair,
}

impl TestHandleTree {
    pub fn new(ds: &TestDelegatedSpace) -> Self {
        Self {
            space: ds.space.label(),
            ds: ds.clone(),
            handle_tree: SubTree::empty(),
            commitments: vec![],
            staged: Default::default(),
        }
    }

    pub fn add_handle(&mut self, name: &str) {
        let label = label(name);
        let label_hash = KeyHash::hash(label.as_slabel().as_ref());
        assert!(
            !self
                .handle_tree
                .contains(&label_hash)
                .expect("complete tree"),
            "already exists"
        );
        assert!(!self.staged.contains_key(&label), "already staged");

        let (genesis_spk, keypair) = gen_p2tr_spk();
        let handle = TestHandle {
            name: label,
            genesis_spk: genesis_spk.clone(),
            keypair,
        };

        let h = sname(&format!("{}{}", name, self.space));
        let num_id = Some(NumId::from_spk::<KeyHash>(genesis_spk.clone()));
        let zone = Zone {
            anchor: 0,
            sovereignty: SovereigntyState::Dependent,
            canonical: h.clone(),
            handle: h,
            alias: None,
            script_pubkey: genesis_spk,
            fallback_records: sip7::RecordSet::default(),
            records: sip7::RecordSet::default(),
            delegate: ProvableOption::Unknown,
            commitment: ProvableOption::Unknown,
            num_id,
        };

        let signature = sign_zone(&zone, &self.ds.ptr.keypair);
        let staged = StagedHandle { handle, signature };

        self.staged.insert(staged.handle.name.clone(), staged);
    }

    pub fn commit(&mut self, chain: &mut TestChain) {
        assert!(!self.staged.is_empty(), "no handles to commit");

        let initial_root = self.handle_tree.compute_root().expect("compute root");
        let handles: HashMap<Subname, TestHandle> = std::mem::take(&mut self.staged)
            .into_iter()
            .map(|(k, v)| (k, v.handle))
            .collect();

        for (_, handle) in handles.iter() {
            let handle_key = KeyHash::hash(handle.name.as_slabel().as_ref());
            let handle_out = HandleOut {
                name: handle.name.as_slabel().clone(),
                spk: handle.genesis_spk.clone(),
            };
            self.handle_tree
                .insert(handle_key, ValueOrHash::Value(handle_out.to_vec()))
                .expect("insert handle");
        }

        let final_root = self.handle_tree.compute_root().expect("compute root");
        let onchain_commitment = chain.insert_commitment(&self.ds, final_root);

        let receipt = if onchain_commitment.prev_root.is_some() {
            let commitment = libveritas_zk::guest::Commitment {
                policy_step: libveritas::constants::STEP_ID,
                policy_fold: libveritas::constants::FOLD_ID,
                initial_root,
                final_root,
                rolling_hash: onchain_commitment.rolling_hash,
                kind: libveritas_zk::guest::CommitmentKind::Fold,
            };

            // Serialize using risc0 serde format (u32 words → le bytes),
            // matching what a real guest would write via env::commit()
            let words = risc0_zkvm::serde::to_vec(&commitment).expect("serialize commitment");
            let journal_bytes: Vec<u8> = words.iter().flat_map(|w| w.to_le_bytes()).collect();

            let receipt_claim =
                ReceiptClaim::ok(libveritas::constants::FOLD_ID, journal_bytes.clone());
            Some(Receipt::new(
                InnerReceipt::Fake(FakeReceipt::new(receipt_claim)),
                journal_bytes,
            ))
        } else {
            None
        };

        self.commitments.push(TestCommitmentBundle {
            root: final_root,
            handles,
            handle_tree: self.handle_tree.clone(),
            receipt,
        })
    }

    /// Build a Message with proved (pruned) Merkle proofs.
    ///
    /// * `chain` - The chain snapshot at the anchor time (must match anchor roots)
    /// * `commitment_idx` - Which commitment to include
    /// * `handle_names` - Handle subjects to include (empty for root-only)
    /// * `anchor` - The chain anchor for the message
    pub fn build_message(
        &self,
        chain: &TestChain,
        commitment_idx: usize,
        handle_names: &[&str],
        anchor: &ChainAnchor,
    ) -> Message {
        let tcb = &self.commitments[commitment_idx];

        // --- Spaces tree keys ---
        let spaces_keys: Vec<[u8; 32]> = vec![
            self.ds.space.outpoint_key().into(),
            self.ds.space.space_key().into(),
        ];

        // --- Nums tree keys ---
        let mut nums_keys: Vec<[u8; 32]> =
            vec![self.ds.ptr.outpoint_key().into(), self.ds.ptr.id().into()];

        // Registry key (commitment tip pointer)
        nums_keys.push(CommitmentTipKey::from_slabel::<KeyHash>(&self.space).into());

        // Commitment key for the commitment being proven
        nums_keys.push(CommitmentKey::new::<KeyHash>(&self.space, tcb.root).into());

        // --- Handle tree keys + handles ---
        let mut handle_keys: Vec<[u8; 32]> = Vec::new();
        let mut handles: Vec<msg::Handle> = Vec::new();

        for &name in handle_names {
            let l = label(name);
            let label_hash = KeyHash::hash(l.as_slabel().as_ref());
            handle_keys.push(label_hash);

            // Find handle across all commitments up to this one
            let handle = self.commitments[..=commitment_idx]
                .iter()
                .find_map(|c| c.handles.get(&l))
                .expect("handle must exist in a previous commitment");

            // Handle's num ID for key rotation lookup (proves non-existence in nums tree)
            let handle_num_id = NumId::from_spk::<KeyHash>(handle.genesis_spk.clone());
            nums_keys.push(handle_num_id.into());

            handles.push(msg::Handle {
                name: l,
                genesis_spk: handle.genesis_spk.clone(),
                records: None,
                signature: None, // Final cert - no signature
            });
        }

        // --- Create proved subtrees ---
        let spaces_proof = chain
            .spaces_tree
            .prove(&spaces_keys, ProofType::Standard)
            .expect("prove spaces");
        let nums_proof = chain
            .nums_tree
            .prove(&nums_keys, ProofType::Standard)
            .expect("prove nums");
        let handles_proof = tcb
            .handle_tree
            .prove(&handle_keys, ProofType::Standard)
            .expect("prove handles");

        // --- Build message ---
        Message {
            chain: msg::ChainProof {
                anchor: *anchor,
                spaces: SpacesSubtree(spaces_proof),
                nums: NumsSubtree(nums_proof),
            },
            spaces: vec![msg::Bundle {
                subject: self.space.clone(),
                receipt: tcb.receipt.clone(),
                epochs: vec![msg::Epoch {
                    tree: HandleSubtree(handles_proof),
                    handles,
                }],
                records: None,
                delegate_records: None,
            }],
        }
    }

    /// Build a temporary certificate message for a staged (uncommitted) handle.
    ///
    /// The handle must be in `staged`. The message includes an exclusion proof
    /// (handle not in tree) and the pre-computed signature from the delegate.
    pub fn build_temporary_message(
        &self,
        chain: &TestChain,
        commitment_idx: usize,
        handle_name: &str,
        anchor: &ChainAnchor,
    ) -> Message {
        let tcb = &self.commitments[commitment_idx];
        let staged = self
            .staged
            .get(&label(handle_name))
            .expect("handle must be staged");

        // --- Spaces tree keys ---
        let spaces_keys: Vec<[u8; 32]> = vec![
            self.ds.space.outpoint_key().into(),
            self.ds.space.space_key().into(),
        ];

        // --- Nums tree keys ---
        let mut nums_keys: Vec<[u8; 32]> =
            vec![self.ds.ptr.outpoint_key().into(), self.ds.ptr.id().into()];
        nums_keys.push(CommitmentTipKey::from_slabel::<KeyHash>(&self.space).into());
        nums_keys.push(CommitmentKey::new::<KeyHash>(&self.space, tcb.root).into());

        // Handle's num ID for key rotation (exclusion proof — handle never on-chain)
        let handle_num_id = NumId::from_spk::<KeyHash>(staged.handle.genesis_spk.clone());
        nums_keys.push(handle_num_id.into());

        // --- Handle exclusion proof ---
        let handle_key = KeyHash::hash(staged.handle.name.as_slabel().as_ref());
        let handle_keys: Vec<[u8; 32]> = vec![handle_key];

        // --- Create proved subtrees ---
        let spaces_proof = chain
            .spaces_tree
            .prove(&spaces_keys, ProofType::Standard)
            .expect("prove spaces");
        let nums_proof = chain
            .nums_tree
            .prove(&nums_keys, ProofType::Standard)
            .expect("prove nums");
        let handles_proof = tcb
            .handle_tree
            .prove(&handle_keys, ProofType::Standard)
            .expect("prove handles exclusion");

        Message {
            chain: msg::ChainProof {
                anchor: *anchor,
                spaces: SpacesSubtree(spaces_proof),
                nums: NumsSubtree(nums_proof),
            },
            spaces: vec![msg::Bundle {
                subject: self.space.clone(),
                receipt: tcb.receipt.clone(),
                epochs: vec![msg::Epoch {
                    tree: HandleSubtree(handles_proof),
                    handles: vec![msg::Handle {
                        name: staged.handle.name.clone(),
                        genesis_spk: staged.handle.genesis_spk.clone(),
                        records: None,
                        signature: Some(staged.signature),
                    }],
                }],
                records: None,
                delegate_records: None,
            }],
        }
    }
}

#[derive(Clone)]
pub struct TestDelegatedSpace {
    pub space: TestSpace,
    pub ptr: TestNum,
}

/// Shared test fixture: a delegated space (@bitcoin) with two commitments.
///
/// Commitment 0: alice + bob  (finalized, no receipt needed)
/// Commitment 1: charlie      (pending, has ZK receipt)
struct Fixture {
    finalized_chain: TestChain,
    latest_chain: TestChain,
    handles: TestHandleTree,
    finalized_anchor: RootAnchor,
    latest_anchor: RootAnchor,
}

impl Fixture {
    fn new() -> Self {
        let mut chain = TestChain::new();
        let ds = chain.add_space_with_delegation("@bitcoin");

        let mut handles = TestHandleTree::new(&ds);
        handles.add_handle("alice");
        handles.add_handle("bob");
        handles.commit(&mut chain);

        chain.increase_time(COMMITMENT_FINALITY_INTERVAL + 1);
        let finalized_anchor = chain.current_root_anchor();
        let finalized_chain = chain.clone();

        chain.increase_time(1);
        handles.add_handle("charlie");
        handles.commit(&mut chain);
        let latest_anchor = chain.current_root_anchor();

        // add a staged handle for temporary cert testing
        handles.add_handle("staged");

        Fixture {
            finalized_chain,
            latest_chain: chain,
            handles,
            finalized_anchor,
            latest_anchor,
        }
    }

    fn veritas(&self) -> Veritas {
        let anchors = vec![self.latest_anchor.clone(), self.finalized_anchor.clone()];
        Veritas::new().with_anchors(anchors).expect("valid anchors")
    }

    /// Message proving commitment 0 (finalized) against the finalized anchor.
    fn finalized_message(&self, handles: &[&str]) -> Message {
        self.handles.build_message(
            &self.finalized_chain,
            0,
            handles,
            &self.finalized_anchor.block,
        )
    }

    /// Message proving commitment 1 (pending) against the latest anchor.
    fn pending_message(&self, handles: &[&str]) -> Message {
        self.handles
            .build_message(&self.latest_chain, 1, handles, &self.latest_anchor.block)
    }

    /// Temporary certificate message for a staged handle (not yet committed).
    fn temporary_message(&self, handle_name: &str) -> Message {
        self.handles.build_temporary_message(
            &self.latest_chain,
            1,
            handle_name,
            &self.latest_anchor.block,
        )
    }
}

#[test]
fn verify_root_finalized() {
    let f = Fixture::new();
    let veritas = f.veritas();
    let ctx = QueryContext::new();

    let result = veritas
        .verify_with_options(&ctx, f.finalized_message(&[]), libveritas::VERIFY_DEV_MODE)
        .expect("verify");

    assert_eq!(result.zones.len(), 1);
    let zone = &result.zones[0];
    assert_eq!(zone.handle, sname("@bitcoin"));
    assert!(matches!(zone.sovereignty, SovereigntyState::Sovereign));
    let ProvableOption::Exists { value: c } = &zone.commitment else {
        panic!("expected commitment Exists");
    };
    assert_eq!(c.onchain.state_root, f.handles.commitments[0].root);
    assert!(c.receipt_hash.is_none()); // First commitment, no receipt needed
    assert!(matches!(zone.delegate, ProvableOption::Exists { .. }));
}

#[test]
fn verify_leaf_finalized() {
    let f = Fixture::new();
    let veritas = f.veritas();
    let ctx = QueryContext::new();

    let result = veritas
        .verify_with_options(
            &ctx,
            f.finalized_message(&["alice"]),
            libveritas::VERIFY_DEV_MODE,
        )
        .expect("verify");

    // Should have root zone + alice zone
    assert_eq!(result.zones.len(), 2);
    let alice = result
        .zones
        .iter()
        .find(|z| z.handle == sname("alice@bitcoin"))
        .expect("alice");
    assert!(matches!(alice.sovereignty, SovereigntyState::Sovereign));

    let result = veritas
        .verify_with_options(
            &ctx,
            f.finalized_message(&["bob"]),
            libveritas::VERIFY_DEV_MODE,
        )
        .expect("verify");
    let bob = result
        .zones
        .iter()
        .find(|z| z.handle == sname("bob@bitcoin"))
        .expect("bob");
    assert!(matches!(bob.sovereignty, SovereigntyState::Sovereign));
}

#[test]
fn verify_root_pending() {
    let f = Fixture::new();
    let veritas = f.veritas();
    let ctx = QueryContext::new();

    let result = veritas
        .verify_with_options(&ctx, f.pending_message(&[]), libveritas::VERIFY_DEV_MODE)
        .expect("verify");

    assert_eq!(result.zones.len(), 1);
    let zone = &result.zones[0];
    assert!(matches!(zone.sovereignty, SovereigntyState::Sovereign));
    let ProvableOption::Exists { value: c } = &zone.commitment else {
        panic!("expected commitment Exists");
    };
    assert_eq!(c.onchain.state_root, f.handles.commitments[1].root);
    assert!(c.receipt_hash.is_some()); // Non-first commitment, receipt verified
}

#[test]
fn verify_leaf_pending() {
    let f = Fixture::new();
    let veritas = f.veritas();
    let ctx = QueryContext::new();

    let result = veritas
        .verify_with_options(
            &ctx,
            f.pending_message(&["charlie"]),
            libveritas::VERIFY_DEV_MODE,
        )
        .expect("verify");
    let charlie = result
        .zones
        .iter()
        .find(|z| z.handle == sname("charlie@bitcoin"))
        .expect("charlie");
    assert!(matches!(charlie.sovereignty, SovereigntyState::Pending));
}

#[test]
fn verify_leaf_across_anchors() {
    let f = Fixture::new();
    let veritas = f.veritas();
    let ctx = QueryContext::new();

    // alice was committed in commitment 0, verified against the latest anchor
    let result = veritas
        .verify_with_options(
            &ctx,
            f.pending_message(&["alice"]),
            libveritas::VERIFY_DEV_MODE,
        )
        .expect("verify");
    let alice = result
        .zones
        .iter()
        .find(|z| z.handle == sname("alice@bitcoin"))
        .expect("alice");
    assert_eq!(alice.handle, sname("alice@bitcoin"));
}

#[test]
fn verify_leaf_temporary() {
    let f = Fixture::new();
    let veritas = f.veritas();
    let ctx = QueryContext::new();

    // "staged" is in staged but not committed — uses delegate's signature
    let result = veritas
        .verify_with_options(
            &ctx,
            f.temporary_message("staged"),
            libveritas::VERIFY_DEV_MODE,
        )
        .expect("verify");
    let staged = result
        .zones
        .iter()
        .find(|z| z.handle == sname("staged@bitcoin"))
        .expect("staged");
    assert_eq!(staged.handle, sname("staged@bitcoin"));
    assert!(matches!(staged.sovereignty, SovereigntyState::Dependent));
}

#[test]
fn verify_with_request_filter() {
    let f = Fixture::new();
    let veritas = f.veritas();

    // Request only alice, not the root
    let mut ctx = QueryContext::new();
    ctx.add_request(sname("alice@bitcoin"));

    let result = veritas
        .verify_with_options(
            &ctx,
            f.finalized_message(&["alice", "bob"]),
            libveritas::VERIFY_DEV_MODE,
        )
        .expect("verify");

    // Should only return alice (root not requested, bob not requested)
    assert_eq!(result.zones.len(), 1);
    assert_eq!(result.zones[0].handle, sname("alice@bitcoin"));
}

#[test]
fn verify_with_cached_parent_zone() {
    let f = Fixture::new();
    let veritas = f.veritas();

    // First verify to get parent zone
    let ctx = QueryContext::new();
    let result = veritas
        .verify_with_options(&ctx, f.finalized_message(&[]), libveritas::VERIFY_DEV_MODE)
        .expect("verify");
    let parent_zone = result.zones[0].clone();

    // Now verify with cached parent
    let ctx = QueryContext::from_zones(vec![parent_zone]);
    let result = veritas
        .verify_with_options(
            &ctx,
            f.finalized_message(&["alice"]),
            libveritas::VERIFY_DEV_MODE,
        )
        .expect("verify");

    // Should succeed and include alice
    let alice = result
        .zones
        .iter()
        .find(|z| z.handle == sname("alice@bitcoin"))
        .expect("alice");
    assert_eq!(alice.handle, sname("alice@bitcoin"));
}

#[test]
fn verify_uses_better_cached_zone() {
    let f = Fixture::new();
    let veritas = f.veritas();

    // Create a "worse" cached zone with lower anchor
    let cached_zone = Zone {
        anchor: 0, // Lower than actual anchor
        sovereignty: SovereigntyState::Dependent,
        canonical: sname("alice@bitcoin"),
        handle: sname("alice@bitcoin"),
        alias: None,
        script_pubkey: ScriptBuf::new(),
        fallback_records: sip7::RecordSet::default(),
        records: sip7::RecordSet::default(),
        delegate: ProvableOption::Unknown,
        commitment: ProvableOption::Unknown,
        num_id: None,
    };

    let ctx = QueryContext::from_zones(vec![cached_zone.clone()]);
    let result = veritas
        .verify_with_options(
            &ctx,
            f.finalized_message(&["alice"]),
            libveritas::VERIFY_DEV_MODE,
        )
        .expect("verify");

    // Should return the newly verified zone (better anchor)
    let alice = result
        .zones
        .iter()
        .find(|z| z.handle == sname("alice@bitcoin"))
        .expect("alice");
    assert!(alice.anchor > 0);
    assert!(matches!(alice.sovereignty, SovereigntyState::Sovereign));
}

#[test]
fn certificate_iterator() {
    let f = Fixture::new();
    let veritas = f.veritas();
    let ctx = QueryContext::new();

    // Verify root + two leaves
    let result = veritas
        .verify_with_options(
            &ctx,
            f.finalized_message(&["alice", "bob"]),
            libveritas::VERIFY_DEV_MODE,
        )
        .expect("verify");

    let certs: Vec<Certificate> = result.certificates().collect();

    // Should have 3 certs: root, alice, bob
    assert_eq!(certs.len(), 3);

    // First should be root
    assert_eq!(certs[0].subject, sname("@bitcoin"));
    assert!(matches!(certs[0].witness, Witness::Root { .. }));

    // Then leaves
    let alice_cert = certs
        .iter()
        .find(|c| c.subject == sname("alice@bitcoin"))
        .expect("alice cert");
    assert!(matches!(alice_cert.witness, Witness::Leaf { .. }));

    let bob_cert = certs
        .iter()
        .find(|c| c.subject == sname("bob@bitcoin"))
        .expect("bob cert");
    assert!(matches!(bob_cert.witness, Witness::Leaf { .. }));
}

#[test]
fn certificate_iterator_leaves_only() {
    let f = Fixture::new();
    let veritas = f.veritas();

    // Request only alice, not the root
    let mut ctx = QueryContext::new();
    ctx.add_request(sname("alice@bitcoin"));

    let result = veritas
        .verify_with_options(
            &ctx,
            f.finalized_message(&["alice"]),
            libveritas::VERIFY_DEV_MODE,
        )
        .expect("verify");

    let certs: Vec<Certificate> = result.certificates().collect();

    // Should have only alice (no root since it wasn't requested)
    assert_eq!(certs.len(), 1);
    assert_eq!(certs[0].subject, sname("alice@bitcoin"));
    assert!(matches!(certs[0].witness, Witness::Leaf { .. }));
}