libveritas_testutil 0.2.0

Test fixtures and helpers for libveritas — simulated chain state, handle trees, and a fixture generator.
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
//! Test utilities for libveritas.
//!
//! Provides simulated chain state and handle trees for testing certificate
//! verification without a real blockchain.

pub mod fixture;

use bitcoin::hashes::Hash as BitcoinHash;
use bitcoin::key::Keypair;
use bitcoin::key::rand::Rng;
use bitcoin::secp256k1::Secp256k1;
use bitcoin::secp256k1::rand::{self, SeedableRng};
use bitcoin::{BlockHash, OutPoint, ScriptBuf, Txid};
use borsh::{BorshDeserialize, BorshSerialize};
use libveritas::cert::{HandleOut, HandleSubtree, KeyHash, NumsSubtree, Signature, SpacesSubtree};
use libveritas::msg::{self, ChainProof, Message};
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::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;
// ─────────────────────────────────────────────────────────────────────────────
// Helper functions
// ─────────────────────────────────────────────────────────────────────────────

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

pub fn sign_mesage(signable: &[u8], keypair: &Keypair) -> Signature {
    let msg = hash_signable_message(signable);
    let secp = Secp256k1::new();
    let sig = secp.sign_schnorr_no_aux_rand(&msg, keypair);
    Signature(sig.serialize())
}

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

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

pub fn sign_zone(zone: &Zone, keypair: &Keypair) -> Signature {
    sign_mesage(&zone.signing_bytes(), keypair)
}

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

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

    let script = Builder::new()
        .push_opcode(OP_PUSHNUM_1)
        .push_slice(xonly.serialize())
        .into_script();

    (script, keypair)
}

// ─────────────────────────────────────────────────────────────────────────────
// Borsh helper for OutPoint
// ─────────────────────────────────────────────────────────────────────────────

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

// ─────────────────────────────────────────────────────────────────────────────
// Test primitives
// ─────────────────────────────────────────────────────────────────────────────

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

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

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

#[derive(Clone)]
pub struct TestHandle {
    pub name: Subname,
    pub genesis_spk: ScriptBuf,
    pub keypair: Keypair,
    pub records: Option<sip7::RecordSet>,
}

#[derive(Clone)]
pub struct StagedHandle {
    pub handle: TestHandle,
    pub signature: Signature,
}

#[derive(Clone)]
pub struct TestCommitmentBundle {
    pub root: [u8; 32],
    pub block_height: u32,
    pub handles: HashMap<Subname, TestHandle>,
    pub handle_tree: SubTree<Sha256Hasher>,
    pub receipt: Option<Receipt>,
}

fn rng() -> rand::rngs::StdRng {
    let seed = [0u8; 32];
    rand::rngs::StdRng::from_seed(seed)
}

impl TestSpace {
    pub fn new(name: &str, block_height: u32) -> Self {
        let mut rng = 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 id = NumId::from_spk::<KeyHash>(genesis_spk);

        let mut rng = 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,
                    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")
    }
}

// ─────────────────────────────────────────────────────────────────────────────
// TestChain - simulated chain state
// ─────────────────────────────────────────────────────────────────────────────

#[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,
}

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 chain_proof(&self, anchor: &ChainAnchor) -> ChainProof {
        ChainProof {
            anchor: *anchor,
            spaces: SpacesSubtree(self.spaces_tree.clone()),
            nums: NumsSubtree(self.nums_tree.clone()),
        }
    }

    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()));

        self.spaces_tree
            .insert(
                space.outpoint_key().into(),
                ValueOrHash::Value(space.spaceout_bytes()),
            )
            .expect("insert space");
        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()));

        self.nums_tree
            .insert(
                num.outpoint_key().into(),
                ValueOrHash::Value(num.numout_bytes()),
            )
            .expect("insert ptr");

        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 ptr = self.add_num(space.script_pubkey());

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

        TestDelegatedSpace { space, ptr }
    }

    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
    }

    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);
        }

        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;

        let prev_root = commitment.prev_root?;
        let finalized = self.get_commitment(space, Some(prev_root))?;

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

        Some(finalized)
    }
}

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

// ─────────────────────────────────────────────────────────────────────────────
// TestHandleTree - operator's off-chain handle tree
// ─────────────────────────────────────────────────────────────────────────────

#[derive(Clone)]
pub struct TestHandleTree {
    pub space: SLabel,
    pub ds: TestDelegatedSpace,
    pub handle_tree: SubTree<Sha256Hasher>,
    pub commitments: Vec<TestCommitmentBundle>,
    pub staged: HashMap<Subname, StagedHandle>,
}

impl TestHandle {
    pub fn set_records(&mut self, data: sip7::RecordSet, signer: &SName) {
        let unsigned = msg::UnsignedRecordSet {
            handle: signer.clone(),
            canonical: signer.clone(),
            flags: sip7::SIG_PRIMARY_ZONE,
            records: data,
            delegate: false,
        };
        let sig = sign_mesage(&unsigned.signable_bytes(), &self.keypair);
        self.records = Some(unsigned.pack_sig(sig.0.to_vec()));
    }
}

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,
            records: None,
        };

        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,
            anchor_hash: [0u8; 32],
        };

        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,
            };

            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,
            block_height: onchain_commitment.block_height,
            handles,
            handle_tree: self.handle_tree.clone(),
            receipt,
        })
    }

    /// Build a Message with proved (pruned) Merkle proofs.
    pub fn build_message(
        &self,
        chain: &TestChain,
        commitment_idx: usize,
        handle_names: &[&str],
        anchor: &ChainAnchor,
    ) -> Message {
        let tcb = &self.commitments[commitment_idx];

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

        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());

        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);

            let handle = self.commitments[..=commitment_idx]
                .iter()
                .find_map(|c| c.handles.get(&l))
                .expect("handle must exist in a previous commitment");

            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,
            });
        }

        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");

        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 handle.
    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");

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

        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());

        let handle_num_id = NumId::from_spk::<KeyHash>(staged.handle.genesis_spk.clone());
        nums_keys.push(handle_num_id.into());

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

        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,
            }],
        }
    }
}

// ─────────────────────────────────────────────────────────────────────────────
// Veritas builder helper
// ─────────────────────────────────────────────────────────────────────────────

pub fn veritas_from_anchors(anchors: Vec<RootAnchor>) -> Veritas {
    Veritas::new().with_anchors(anchors).expect("valid anchors")
}