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
use crate::{TestChain, TestDelegatedSpace, TestHandleTree};
use libveritas::cert::{HandleSubtree, NumsSubtree, SpacesSubtree};
use libveritas::msg::{Bundle, ChainProof};
use libveritas::{SovereigntyState, Veritas, msg};
use spacedb::subtree::SubTree;
use spaces_nums::RootAnchor;
use spaces_nums::constants::COMMITMENT_FINALITY_INTERVAL;
use spaces_protocol::sname::SName;

#[derive(Clone, Debug)]
pub enum Step {
    Stage(&'static [&'static str]),
    Commit,
    Finalize,
}

#[derive(Clone, Debug)]
pub struct Fixture {
    pub name: &'static str,
    pub steps: Vec<Step>,
}

pub struct HandleStates {
    /// Handles in each commitment, indexed by commitment number
    pub commits: Vec<Vec<&'static str>>,
    /// Handles staged but not yet committed
    pub staged: Vec<&'static str>,
    /// Number of finalized commitments
    pub finalized_count: usize,
}

impl HandleStates {
    /// All committed handles (any commitment)
    pub fn all_committed(&self) -> Vec<&'static str> {
        self.commits.iter().flatten().copied().collect()
    }

    /// Handles in a specific commitment
    pub fn in_commit(&self, index: usize) -> &[&'static str] {
        self.commits.get(index).map(|v| v.as_slice()).unwrap_or(&[])
    }

    /// Is this handle committed (in any commitment)?
    pub fn is_committed(&self, handle: &str) -> bool {
        self.commits.iter().flatten().any(|&h| h == handle)
    }

    /// Is this handle staged (not yet committed)?
    pub fn is_staged(&self, handle: &str) -> bool {
        self.staged.contains(&handle)
    }

    /// Which commitment contains this handle? None if staged/not found.
    pub fn commit_index(&self, handle: &str) -> Option<usize> {
        self.commits.iter().position(|c| c.contains(&handle))
    }

    /// Latest commitment index (None if no commits)
    pub fn latest_commit(&self) -> Option<&Vec<&str>> {
        self.commits.last()
    }

    pub fn pending_commit(&self) -> Option<&Vec<&str>> {
        if !self.has_pending_commit() {
            return None;
        }

        self.latest_commit()
    }

    /// Total number of commitments
    pub fn commit_count(&self) -> usize {
        self.commits.len()
    }

    /// Is there a pending (non-finalized) commitment?
    pub fn has_pending_commit(&self) -> bool {
        self.commits.len() > self.finalized_count
    }

    /// Does this handle need a receipt when verified?
    /// (Handles in commitment > 0 need receipt verification)
    pub fn needs_receipt(&self, handle: &str) -> bool {
        self.commit_index(handle).map(|i| i > 0).unwrap_or(false)
    }

    /// Expected sovereignty for a committed handle
    pub fn sovereignty(&self, handle: &str) -> Option<SovereigntyState> {
        if self.staged.iter().find(|&&s| s == handle).is_some() {
            return Some(SovereigntyState::Dependent);
        }

        let commit_idx = self.commit_index(handle)?;
        if commit_idx < self.finalized_count {
            Some(SovereigntyState::Sovereign)
        } else {
            Some(SovereigntyState::Pending)
        }
    }
}

impl Fixture {
    pub fn new(name: &'static str) -> Self {
        Self {
            name,
            steps: vec![],
        }
    }

    pub fn stage(mut self, handles: &'static [&'static str]) -> Self {
        self.steps.push(Step::Stage(handles));
        self
    }

    pub fn commit(mut self) -> Self {
        self.steps.push(Step::Commit);
        self
    }

    pub fn finalize(mut self) -> Self {
        self.steps.push(Step::Finalize);
        self
    }

    pub fn then(mut self, other: Fixture) -> Self {
        self.steps.extend(other.steps);
        self
    }

    /// Analyze steps to determine handle states
    pub fn handle_states(&self) -> HandleStates {
        let mut commits: Vec<Vec<&'static str>> = vec![];
        let mut staged: Vec<&'static str> = vec![];
        let mut finalized_count: usize = 0;

        for step in &self.steps {
            match step {
                Step::Stage(handles) => {
                    staged.extend(*handles);
                }
                Step::Commit => {
                    commits.push(std::mem::take(&mut staged));
                }
                Step::Finalize => {
                    finalized_count += 1;
                }
            }
        }

        HandleStates {
            commits,
            staged,
            finalized_count,
        }
    }
}

#[derive(Clone)]
pub struct ChainState {
    pub chain: TestChain,
    pub anchors: Vec<RootAnchor>,
}

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

impl ChainState {
    pub fn new() -> Self {
        Self {
            chain: TestChain::new(),
            anchors: vec![],
        }
    }

    pub fn veritas(&self) -> Veritas {
        let mut anchors = self.anchors.clone();
        if anchors.is_empty() {
            anchors.push(self.chain.current_root_anchor());
        }
        anchors.reverse();
        Veritas::new().with_anchors(anchors).expect("valid anchors")
    }

    pub fn message(&self, bundles: Vec<Bundle>) -> msg::Message {
        msg::Message {
            chain: ChainProof {
                anchor: self.chain.current_root_anchor().block,
                spaces: SpacesSubtree(self.chain.spaces_tree.clone()),
                nums: NumsSubtree(self.chain.nums_tree.clone()),
            },
            spaces: bundles,
        }
    }
}

#[derive(Clone)]
pub struct FixtureRunner {
    pub fixture: Fixture,
    pub step: std::vec::IntoIter<Step>,
    pub space: TestDelegatedSpace,
    pub handles: TestHandleTree,
    pub anchors: Vec<RootAnchor>,
}

impl FixtureRunner {
    pub fn new(state: &mut ChainState, fixture: Fixture) -> Self {
        let space = state.chain.add_space_with_delegation(fixture.name);
        let handles = TestHandleTree::new(&space);
        Self {
            step: fixture.steps.clone().into_iter(),
            space,
            fixture,
            anchors: vec![],
            handles,
        }
    }

    pub fn build_bundle(&mut self) -> msg::Bundle {
        let mut bundle = msg::Bundle {
            subject: self.space.space.label(),
            receipt: None,
            epochs: vec![],
            records: None,
            delegate_records: None,
        };

        let space_label = self.space.space.label();
        for c in &mut self.handles.commitments {
            bundle.receipt = c.receipt.clone();
            let mut epoch = msg::Epoch {
                tree: HandleSubtree(c.handle_tree.clone()),
                handles: vec![],
            };
            for handle in c.handles.values_mut() {
                let signer = SName::join(&handle.name, &space_label).expect("join handle name");
                // Add some off-chain data
                handle.set_records(
                    sip7::RecordSet::pack(vec![sip7::Record::txt(
                        "name",
                        &[&handle.name.to_string()],
                    )])
                    .expect("pack records"),
                    &signer,
                );

                epoch.handles.push(msg::Handle {
                    name: handle.name.clone(),
                    genesis_spk: handle.genesis_spk.clone(),
                    records: handle.records.clone(),
                    signature: None,
                })
            }
            bundle.epochs.push(epoch);
        }

        let mut empty_epoch = msg::Epoch {
            tree: HandleSubtree(SubTree::empty()),
            handles: vec![],
        };
        let staging = bundle.epochs.last_mut().unwrap_or(&mut empty_epoch);

        for staged in self.handles.staged.values_mut() {
            let signer = SName::join(&staged.handle.name, &space_label).expect("join handle name");
            // add some off-chain data
            staged.handle.set_records(
                sip7::RecordSet::pack(vec![sip7::Record::txt(
                    "name",
                    &[&staged.handle.name.to_string()],
                )])
                .expect("pack records"),
                &signer,
            );
            staging.handles.push(msg::Handle {
                name: staged.handle.name.clone(),
                genesis_spk: staged.handle.genesis_spk.clone(),
                records: staged.handle.records.clone(),
                signature: Some(staged.signature),
            })
        }
        if !empty_epoch.handles.is_empty() {
            bundle.epochs.push(empty_epoch);
        }
        bundle
    }

    pub fn run_next(&mut self, state: &mut ChainState) -> Option<Step> {
        let step = self.step.next()?;
        match &step {
            Step::Stage(stage) => {
                for &name in *stage {
                    self.handles.add_handle(name);
                }
            }
            Step::Commit => {
                self.handles.commit(&mut state.chain);
                state.anchors.push(state.chain.current_root_anchor())
            }
            Step::Finalize => {
                state.chain.increase_time(COMMITMENT_FINALITY_INTERVAL + 1);
            }
        }
        Some(step)
    }

    pub fn run(&mut self, state: &mut ChainState) {
        while self.run_next(state).is_some() {}
    }
}

// ═══════════════════════════════════════════════════════════════════════════
// FIXTURES
// ═══════════════════════════════════════════════════════════════════════════

/// No commitments, just staged handles. Temp certs need no exclusion proof.
pub fn staged_only() -> Fixture {
    Fixture::new("@staged").stage(&["alice", "bob"])
}

/// Single commitment, not yet finalized. Handles are Pending.
pub fn single_commit_pending() -> Fixture {
    Fixture::new("@pending").stage(&["alice", "bob"]).commit()
}

/// Single commitment, finalized. Handles are Sovereign. No receipt needed.
pub fn single_commit_finalized() -> Fixture {
    Fixture::new("@sovereign")
        .stage(&["alice", "bob"])
        .commit()
        .finalize()
}

/// Two commitments: first finalized, second pending. Receipt required.
pub fn two_commits_second_pending() -> Fixture {
    Fixture::new("@two-pending")
        .stage(&["alice", "bob"])
        .commit()
        .finalize()
        .stage(&["charlie"])
        .commit()
}

/// Two commitments, both finalized.
pub fn two_commits_both_finalized() -> Fixture {
    Fixture::new("@two-finalized")
        .stage(&["alice", "bob"])
        .commit()
        .finalize()
        .stage(&["charlie"])
        .commit()
        .finalize()
}

/// Finalized commit + new staged handle (for temp cert with exclusion proof).
pub fn finalized_with_staged() -> Fixture {
    Fixture::new("@finalized-staged")
        .stage(&["alice"])
        .commit()
        .finalize()
        .stage(&["bob"])
}

/// Kitchen sink: multiple commitments, mixed finality, plus staged handles.
/// - Commit 0 (finalized): alice, bob
/// - Commit 1 (finalized): charlie, dave
/// - Commit 2 (pending):   eve, frank
/// - Staged (no commit):   grace, heidi
pub fn kitchen_sink() -> Fixture {
    Fixture::new("@kitchensink")
        .stage(&["alice", "bob"])
        .commit()
        .finalize()
        .stage(&["charlie", "dave"])
        .commit()
        .finalize()
        .stage(&["eve", "frank"])
        .commit()
        .stage(&["grace", "heidi"])
}

// ═══════════════════════════════════════════════════════════════════════════
// TESTS
// ═══════════════════════════════════════════════════════════════════════════

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_handle_states_staged_only() {
        let states = staged_only().handle_states();

        assert_eq!(states.commits.len(), 0);
        assert_eq!(states.staged, vec!["alice", "bob"]);
        assert!(states.is_staged("alice"));
        assert!(!states.is_committed("alice"));
        assert!(!states.has_pending_commit());
    }

    #[test]
    fn test_handle_states_single_commit_finalized() {
        let states = single_commit_finalized().handle_states();

        assert_eq!(states.commits.len(), 1);
        assert_eq!(states.in_commit(0), &["alice", "bob"]);
        assert!(states.staged.is_empty());
        assert!(states.is_committed("alice"));
        assert_eq!(states.commit_index("alice"), Some(0));
        assert!(!states.has_pending_commit());
        assert_eq!(
            states.sovereignty("alice"),
            Some(SovereigntyState::Sovereign)
        );
    }

    #[test]
    fn test_handle_states_two_commits_second_pending() {
        let states = two_commits_second_pending().handle_states();

        assert_eq!(states.commits.len(), 2);
        assert_eq!(states.finalized_count, 1);
        assert!(states.has_pending_commit());

        // alice is in finalized commit 0
        assert_eq!(states.commit_index("alice"), Some(0));
        assert_eq!(
            states.sovereignty("alice"),
            Some(SovereigntyState::Sovereign)
        );
        assert!(!states.needs_receipt("alice"));

        // charlie is in pending commit 1
        assert_eq!(states.commit_index("charlie"), Some(1));
        assert_eq!(
            states.sovereignty("charlie"),
            Some(SovereigntyState::Pending)
        );
        assert!(states.needs_receipt("charlie"));
    }

    #[test]
    fn test_handle_states_kitchen_sink() {
        let states = kitchen_sink().handle_states();

        assert_eq!(states.commits.len(), 3);
        assert_eq!(states.finalized_count, 2);
        assert!(states.has_pending_commit());

        // Commit 0 (finalized): alice, bob
        assert_eq!(states.in_commit(0), &["alice", "bob"]);
        assert_eq!(
            states.sovereignty("alice"),
            Some(SovereigntyState::Sovereign)
        );
        assert!(!states.needs_receipt("alice"));

        // Commit 1 (finalized): charlie, dave
        assert_eq!(states.in_commit(1), &["charlie", "dave"]);
        assert_eq!(
            states.sovereignty("charlie"),
            Some(SovereigntyState::Sovereign)
        );
        assert!(states.needs_receipt("charlie")); // commit > 0

        // Commit 2 (pending): eve, frank
        assert_eq!(states.in_commit(2), &["eve", "frank"]);
        assert_eq!(states.sovereignty("eve"), Some(SovereigntyState::Pending));
        assert!(states.needs_receipt("eve"));

        // Staged: grace, heidi
        assert_eq!(states.staged, vec!["grace", "heidi"]);
        assert!(states.is_staged("grace"));
        assert!(!states.is_committed("grace"));
        assert_eq!(
            states.sovereignty("grace"),
            Some(SovereigntyState::Dependent)
        );
    }
}