Skip to main content

coven_format/
test_utils.rs

1//! Deterministic examples for consumer tests, built from the production owners' types.
2
3/// The store shared by the deterministic storage and format fixtures.
4pub const STORE_ID: coven_foundation::id_source::StoreId =
5    coven_foundation::id_source::StoreId(uuid::Uuid::from_bytes([0x10; 16]));
6
7use crate::admin::*;
8use crate::codes::{InviteAdmits, InviteCode, KeychainRestoreCode, PairingCode, RestoreCode};
9use crate::key::encode_key;
10use crate::objects::*;
11use crate::snapshot::{SnapshotEncoder, SnapshotHeader, SnapshotRecord};
12use crate::snapshot_rows::*;
13use crate::value::*;
14use crate::write::*;
15use crate::Object;
16use coven_crypto::{InviteSecret, MemberIdentity, MemberKeys, SecretBytes};
17use coven_foundation::id_source::{CircleId, DeviceId, InviteId, KeyId, MemberId, StoreId};
18use coven_merge::slot;
19use coven_merge::{
20    Audience, Cell, Change, ColumnValue, LostKey, LostValue, MergeError, Operation, Parent, RowId,
21    RowState, Timestamp, WriteId, WriteOracle,
22};
23use std::collections::{BTreeMap, BTreeSet};
24use uuid::Uuid;
25use zeroize::Zeroizing;
26
27/// Decode a pinned hexadecimal fixture for consumer tests.
28pub fn fixture_bytes(text: &str) -> Vec<u8> {
29    hex::decode(text.trim()).expect("pinned hexadecimal fixture")
30}
31
32/// An original write by device one.
33pub fn position() -> WriteId {
34    WriteId { device: DeviceId(1), number: 3 }
35}
36/// The fixture write's timestamp.
37pub fn timestamp() -> Timestamp {
38    Timestamp::new(6, 3, DeviceId(1)).unwrap()
39}
40/// A row with a text key in the store.
41pub fn row() -> RowId {
42    RowId {
43        table: "t".into(),
44        key: encode_key(&[Value::Text("k".into())]).unwrap(),
45        audience: Audience::Store,
46    }
47}
48/// A value with no foreign-key metadata.
49pub fn column(value: Value) -> ColumnValue<Value> {
50    ColumnValue { value, parents: BTreeMap::new() }
51}
52/// A private pair whose signing and sealing seeds are both `seed`: public test data.
53pub fn keys_from_seed(seed: u8) -> MemberKeys {
54    MemberKeys::from_seed(seed)
55}
56/// The fixture member Ana's stable id, independent of every key she holds.
57pub fn member_id() -> MemberId {
58    MemberId(Uuid::from_bytes([0x4d; 16]))
59}
60/// Ana's original private pair, with fixed public test seeds 0x33.
61pub fn member_keys() -> MemberKeys {
62    keys_from_seed(0x33)
63}
64/// Ana's id with her original pair, as identity custody holds it.
65pub fn identity() -> MemberIdentity {
66    MemberIdentity::new(member_id(), member_keys())
67}
68/// The public halves of Ana's original pair.
69pub fn member() -> MemberPublicKeys {
70    member_keys().public_keys()
71}
72/// Ana's replacement private pair, with fixed public test seeds 0x34 (ยง10).
73pub fn replacement_keys() -> MemberKeys {
74    keys_from_seed(0x34)
75}
76/// The public halves of Ana's replacement pair, bound to the same id.
77pub fn replacement() -> MemberPublicKeys {
78    replacement_keys().public_keys()
79}
80/// Another member, Ben, whom the fixtures add and remove.
81pub fn other_member_id() -> MemberId {
82    MemberId(Uuid::from_bytes([0x42; 16]))
83}
84/// Ben's initial public pair, with fixed public test seeds 0x35.
85pub fn other_member() -> MemberPublicKeys {
86    keys_from_seed(0x35).public_keys()
87}
88/// A write updating one cell, with named foreign-key metadata on its new value.
89pub fn write() -> WriteRecord {
90    let mut new = column(Value::Integer(2));
91    new.parents.insert(
92        coven_merge::ForeignKey::new(["parent_fk"], "p", ["id"]),
93        Parent {
94            row: RowId {
95                table: "p".into(),
96                key: encode_key(&[Value::Text("q".into())]).unwrap(),
97                audience: Audience::Store,
98            },
99            generation: 1,
100        },
101    );
102    WriteRecord {
103        header: WriteHeader {
104            read_through: 5,
105            position: position(),
106            timestamp: timestamp(),
107            schema_version: 1,
108            disposition: WriteDisposition::Apply,
109        },
110        parts: vec![WritePart {
111            dismissals: Vec::new(),
112            audience: Audience::Store,
113            executions: vec![transient_execution(Audience::Store)],
114            rows: vec![RowChange {
115                row: row(),
116                creator: None,
117                execution: Execution {
118                    steps: vec![Step {
119                        sequence: 0,
120                        change: Change {
121                            generation: 1,
122                            operation: Operation::Update(BTreeMap::from([(
123                                "x".into(),
124                                new.clone(),
125                            )])),
126                        },
127                        half: Half::Whole,
128                    }],
129                    sources: Default::default(),
130                },
131                change: Change {
132                    generation: 1,
133                    operation: Operation::Update(BTreeMap::from([("x".into(), new)])),
134                },
135                old: BTreeMap::new(),
136                sources: crate::write_sources::WriteSources {
137                    generation: Some(crate::write_sources::ChangeId {
138                        write: WriteId { device: DeviceId(1), number: 1 },
139                        row: row(),
140                    }),
141                    setters: [(
142                        "x".into(),
143                        crate::write_sources::CellSource {
144                            change: crate::write_sources::ChangeId {
145                                write: WriteId { device: DeviceId(2), number: 1 },
146                                row: row(),
147                            },
148                            column: "x".into(),
149                        },
150                    )]
151                    .into(),
152                },
153            }],
154        }],
155    }
156}
157/// A row the fixture write inserts and deletes again: no net change, two
158/// operations, which still reach the write's authorship leaves (D5).
159pub fn transient_execution(audience: Audience) -> RowExecution {
160    let row = RowId { key: encode_key(&[Value::Text("l".into())]).unwrap(), audience, ..row() };
161    RowExecution {
162        row,
163        execution: Execution {
164            steps: vec![
165                Step {
166                    sequence: 1,
167                    change: Change {
168                        generation: 0,
169                        operation: Operation::Insert(BTreeMap::from([(
170                            "x".into(),
171                            column(Value::Integer(5)),
172                        )])),
173                    },
174                    half: Half::Whole,
175                },
176                Step {
177                    sequence: 2,
178                    change: Change { generation: 1, operation: Operation::Delete },
179                    half: Half::Whole,
180                },
181            ],
182            sources: Default::default(),
183        },
184    }
185}
186/// The public fixture's store key, whose bytes are committed by creation.
187pub fn store_key() -> coven_crypto::StoreKey {
188    coven_crypto::StoreKey::from_bytes(KeyId(Uuid::from_bytes([1; 16])), [17; 32])
189}
190/// The first admin change, carried by slot one.
191pub fn creation_change() -> StoreChange {
192    StoreChange::CreateStore {
193        store: STORE_ID,
194        name: "S".into(),
195        admin: member(),
196        key: store_key().id(),
197        key_hash: store_key().hash(),
198        device_name: "D".into(),
199        person: "A".into(),
200        circle: created_circle(),
201        circles: vec![],
202    }
203}
204/// The slot-one fixture creating the store: an admission-kind slot whose
205/// prefix carries the creator's copy of the first store key and of her
206/// private circle's first key (D6, D9).
207pub fn creation_slot() -> Vec<u8> {
208    hex::decode(include_str!("../fixtures/sealed-creation.hex").trim()).unwrap()
209}
210/// A member-removal admin change.
211pub fn member_removal() -> StoreChange {
212    StoreChange::RemoveMember { member: other_member_id() }
213}
214/// A reset's slot used by loss examples.
215pub fn loss_entry() -> Slot {
216    slot(2)
217}
218/// A canonical path for one positive slot number.
219pub fn slot_path(number: u64) -> crate::path::ObjectPath {
220    crate::path::ObjectPath::slot(STORE_ID, number.try_into().unwrap())
221}
222/// The deterministic header of a device-one claim.
223pub fn slot_header(slot: u64, claim: u64) -> crate::sequence::SlotHeader {
224    crate::sequence::SlotHeader { device: DeviceId(1), claim, author: member_id(), after: slot - 1 }
225}
226/// Seal and sign a bounded slot with public test keys and deterministic nonces.
227pub fn bounded_slot(
228    slot: u64,
229    claim: u64,
230    kind: crate::sealed_slot::SlotKind,
231    frame: crate::sequence::SlotFrame,
232) -> Vec<u8> {
233    let path = slot_path(slot);
234    let prefix = crate::sealed_slot::SlotObjectPrefix {
235        format: crate::FormatVersion::CURRENT,
236        key: store_key().id(),
237        kind,
238    };
239    let plain = frame.encode(&slot_header(slot, claim), &path).unwrap();
240    let chunk = store_key().derive().reseal_object_chunk(
241        path.as_str(),
242        &prefix.encode().unwrap(),
243        0,
244        0,
245        &plain,
246    );
247    let mut bytes = prefix.encode_chunk(&chunk).unwrap();
248    let mut hash = coven_crypto::ObjectHasher::new();
249    hash.update(&bytes);
250    bytes.extend_from_slice(member_keys().sign_object(path.as_str(), &hash.finish()).as_bytes());
251    bytes
252}
253/// An earlier snapshot announcement preserved by the fixture snapshot.
254pub fn announcement() -> crate::sequence::SnapshotAnnouncement {
255    crate::sequence::SnapshotAnnouncement {
256        snapshot: snapshot_header().id,
257        covers: 6,
258        breaking_version: 0,
259        purpose: crate::sequence::Purpose::Ordinary,
260        digest: [0x99; 32],
261    }
262}
263/// An oracle of applied metadata that tests may populate from streamed records.
264#[derive(Clone)]
265pub struct TestOracle {
266    /// Metadata indexed by merge's write identity; no write bodies are reconstructed.
267    pub writes: BTreeMap<WriteId, AppliedWrite>,
268}
269impl WriteOracle for TestOracle {
270    type Error = crate::Error;
271    fn timestamp(&self, id: WriteId) -> Result<Option<Timestamp>, crate::Error> {
272        Ok(self.writes.get(&id).map(|w| w.timestamp))
273    }
274    fn had_read(&self, reader: WriteId, earlier: WriteId) -> Result<bool, crate::Error> {
275        let write = self.writes.get(&reader).ok_or(MergeError::MissingWrite(reader))?;
276        let slot = self.writes.get(&earlier).map(|earlier| earlier.slot);
277        Ok(coven_merge::had_read(reader, write.read_through, earlier, slot))
278    }
279}
280impl crate::snapshot::WriteSlots for TestOracle {
281    fn slot(&self, write: WriteId) -> Result<Option<Slot>, crate::Error> {
282        Ok(self.writes.get(&write).map(|write| write.slot))
283    }
284    fn landed(&self, write: WriteId) -> Result<bool, crate::Error> {
285        Ok(self.writes.keys().any(|id| id.device == write.device && id.number >= write.number))
286    }
287}
288/// Three applied writes, including two concurrent setters of the fixture row.
289pub fn oracle() -> TestOracle {
290    let first = WriteId { device: DeviceId(1), number: 1 };
291    let winner = WriteId { device: DeviceId(1), number: 2 };
292    let loser = WriteId { device: DeviceId(2), number: 1 };
293    TestOracle {
294        writes: [
295            AppliedWrite {
296                id: first,
297                slot: slot(3),
298                timestamp: Timestamp::new(1, 0, first.device).unwrap(),
299                read_through: 0,
300            },
301            AppliedWrite {
302                id: winner,
303                slot: slot(5),
304                timestamp: Timestamp::new(4, 0, winner.device).unwrap(),
305                read_through: 0,
306            },
307            AppliedWrite {
308                id: loser,
309                slot: slot(4),
310                timestamp: Timestamp::new(3, 0, loser.device).unwrap(),
311                read_through: 3,
312            },
313            AppliedWrite { id: position(), slot: slot(6), timestamp: timestamp(), read_through: 5 },
314        ]
315        .into_iter()
316        .map(|w| (w.id, w))
317        .collect(),
318    }
319}
320/// The fixture's merged row, with an actual concurrent loss validated by merge.
321pub fn merge_row() -> MergeRow {
322    merge_row_of(row(), Value::Integer(2))
323}
324/// A merge row of `row` whose cell `x` holds `value`.
325pub fn merge_row_of(row: RowId, value: Value) -> MergeRow {
326    let state = RowState::from_parts(
327        row,
328        BTreeMap::from([(1, WriteId { device: DeviceId(1), number: 1 })]),
329        BTreeMap::from([(
330            "x".into(),
331            Cell { write: WriteId { device: DeviceId(1), number: 2 }, value: column(value) },
332        )]),
333        BTreeMap::new(),
334        &oracle(),
335    )
336    .unwrap();
337    MergeRow { state }
338}
339/// The header for the fixture's eleven snapshot sections.
340pub fn snapshot_header() -> SnapshotHeader {
341    SnapshotHeader {
342        id: SnapshotId { device: DeviceId(1), number: 1, audience: Audience::Store },
343        schema_version: 2,
344        covers: 9,
345        counts: [4, 1, 1, 4, 5, 1, 1, 1, 1, 1, 2],
346    }
347}
348/// The sealed prefix carrying a snapshot's coverage, with a fixed test key.
349pub fn snapshot_prefix(header: &SnapshotHeader) -> crate::sealed_snapshot::SnapshotObjectPrefix {
350    crate::sealed_snapshot::SnapshotObjectPrefix {
351        audience: header.id.audience.clone(),
352        key: KeyId(Uuid::from_bytes([1; 16])),
353        covers: header.covers,
354        purpose: crate::sequence::Purpose::Raise(header.schema_version),
355    }
356}
357/// Records in their canonical section and identity order.
358pub fn snapshot_records() -> Vec<SnapshotRecord> {
359    let mut writes = oracle().writes;
360    let header = write().header;
361    writes.insert(
362        header.position,
363        AppliedWrite {
364            id: header.position,
365            timestamp: header.timestamp,
366            slot: slot(6),
367            read_through: header.read_through,
368        },
369    );
370    let mut records: Vec<_> = writes.into_values().map(SnapshotRecord::Write).collect();
371    records.push(SnapshotRecord::Column(SyncedColumn { table: "t".into(), column: "x".into() }));
372    records.push(SnapshotRecord::Merge(merge_row()));
373    records.extend(
374        retained_losses()
375            .into_iter()
376            .chain([concurrent_loss(), excluded_loss()])
377            .map(SnapshotRecord::Loss),
378    );
379    records.extend(authored_records().into_iter().map(SnapshotRecord::Authored));
380    records.push(SnapshotRecord::Creation(creation()));
381    records.push(SnapshotRecord::Evidence(write_evidence()));
382    records.push(SnapshotRecord::Admin(crate::floor::OriginalSlot {
383        slot: slot(1),
384        object: creation_slot(),
385    }));
386    records.push(SnapshotRecord::KeyCopy(crate::floor::OriginalSlot {
387        slot: slot(2),
388        object: hex::decode(include_str!("../fixtures/sealed-store-key.hex").trim()).unwrap(),
389    }));
390    records.push(SnapshotRecord::Announcement(crate::floor::OriginalSlot {
391        slot: slot(7),
392        object: bounded_slot(
393            7,
394            6,
395            crate::sealed_slot::SlotKind::Announcement,
396            crate::sequence::SlotFrame::Announcement(announcement()),
397        ),
398    }));
399    records.push(SnapshotRecord::Claim(crate::snapshot::LastClaim {
400        device: DeviceId(1),
401        number: 8,
402        digest: Some([0x81; 32]),
403    }));
404    records.push(SnapshotRecord::Claim(crate::snapshot::LastClaim {
405        device: DeviceId(2),
406        number: 1,
407        digest: Some([0x21; 32]),
408    }));
409    records
410}
411/// The fixture row's selected creation, by device one's first write.
412pub fn creation() -> crate::authorship::Creation {
413    let write = WriteId { device: DeviceId(1), number: 1 };
414    crate::authorship::Creation {
415        row: row(),
416        write,
417        creator: crate::write_sources::ChangeId { write, row: row() },
418    }
419}
420/// Evidence for the fixture write's store part, opening its updated cell.
421pub fn write_evidence() -> crate::authorship::WriteEvidence {
422    let leaves = crate::authorship::part_leaves(&write().parts[0]);
423    let hasher = store_key().derive().authorship_hasher();
424    let proof = crate::authorship::Multiproof::prove(&hasher, &leaves, |leaf| {
425        matches!(leaf, crate::authorship::Leaf::Cell { .. })
426    })
427    .unwrap();
428    let mut header = 7u32.to_be_bytes().to_vec();
429    header.extend([0x23; 24 + 7 + 16]);
430    crate::authorship::WriteEvidence {
431        write: position(),
432        prefix: crate::sealed_write::WriteObjectPrefix {
433            format: crate::FormatVersion::CURRENT,
434            store_key: KeyId(Uuid::from_bytes([1; 16])),
435            part_keys: vec![KeyId(Uuid::from_bytes([1; 16]))],
436        }
437        .encode()
438        .unwrap(),
439        header,
440        roots: vec![crate::authorship::root(&hasher, &leaves).unwrap()],
441        signature: [0x22; 64],
442        proof,
443    }
444}
445/// The fixture's kept source evidence, each change applied by its author:
446/// the first write's insert of the row, its value kept as a digest, then the
447/// fixture write's store part, whose reference `x` is kept in full, and its
448/// execution-only row.
449pub fn authored_records() -> Vec<crate::snapshot_rows::AuthoredRecord> {
450    use crate::snapshot_rows::{
451        AuthoredChange, AuthoredPart, AuthoredRecord, ChangeVerdict, KeptChange, KeptRecord,
452        KeptValue,
453    };
454    let first = WriteId { device: DeviceId(1), number: 1 };
455    let created = KeptRecord::Change(KeptChange {
456        row: row(),
457        change: Change {
458            generation: 0,
459            operation: Operation::Insert(BTreeMap::from([(
460                "x".into(),
461                ColumnValue {
462                    value: KeptValue::Digest(KeptValue::digest(&Value::Integer(1)).unwrap()),
463                    parents: BTreeMap::new(),
464                },
465            )])),
466        },
467        creator: None,
468        steps: 1,
469    });
470    let write = write();
471    let part = &write.parts[0];
472    let applied = |record, stop| {
473        AuthoredRecord::Change(AuthoredChange { record, verdict: ChangeVerdict::Applied, stop })
474    };
475    vec![
476        AuthoredRecord::Part(AuthoredPart {
477            header: WriteHeader {
478                position: first,
479                timestamp: Timestamp::new(1, 0, first.device).unwrap(),
480                read_through: 0,
481                schema_version: 1,
482                disposition: WriteDisposition::Apply,
483            },
484        }),
485        applied(created, None),
486        AuthoredRecord::Part(AuthoredPart { header: write.header.clone() }),
487        applied(KeptRecord::keep(PartRecord::Change(&part.rows[0]), |_| true).unwrap(), None),
488        // An execution never becomes current: it stops at its own slot.
489        applied(
490            KeptRecord::keep(PartRecord::Execution(&part.executions[0]), |_| true).unwrap(),
491            Some(slot(6)),
492        ),
493    ]
494}
495/// A concurrent cell loss of the fixture row.
496pub fn concurrent_loss() -> crate::loss::Loss {
497    crate::loss::Loss::cell(
498        row(),
499        LostKey { column: "x".into(), write: WriteId { device: DeviceId(2), number: 1 } },
500        LostValue {
501            incarnation: 1,
502            value: column(Value::Integer(1)),
503            replaced_by: WriteId { device: DeviceId(1), number: 2 },
504        },
505    )
506}
507/// Both kinds of loss after their row's merge history has been discarded.
508pub fn retained_losses() -> Vec<crate::loss::Loss> {
509    use crate::loss::Loss;
510    let row = RowId { table: "removed".into(), ..row() };
511    let mut cell = concurrent_loss();
512    cell.row = row.clone();
513    cell.frozen = true;
514    let mut removed =
515        Loss::removed(&merge_row().state, [coven_merge::Rule::Check("valid".into())].into());
516    removed.row = row;
517    removed.frozen = true;
518    vec![cell, removed]
519}
520/// The row values of a write excluded by a schema change.
521pub fn excluded_loss() -> crate::loss::Loss {
522    use crate::loss::{Loss, LossCause, LossValues};
523    let change = write().parts.remove(0).rows.remove(0);
524    let Operation::Update(values) = change.change.operation else { unreachable!() };
525    Loss {
526        row: change.row,
527        generation: change.change.generation,
528        frozen: true,
529        values: LossValues::Row(
530            values
531                .into_iter()
532                .map(|(name, mut value)| {
533                    value.parents.clear();
534                    (name, Cell { write: position(), value })
535                })
536                .collect(),
537        ),
538        cause: LossCause::Excluded { write: write().header.position, version: 2 },
539    }
540}
541/// A plaintext queue value produced by the format's queue encoder.
542#[expect(clippy::map_err_ignore, reason = "a length past usize cannot be allocated")]
543pub fn write_plaintext(record: &WriteRecord) -> Result<Vec<u8>, crate::Error> {
544    let encoder = crate::write_stream::WriteEncoder::new(record)?;
545    let length =
546        usize::try_from(encoder.plaintext_length()).map_err(|_| crate::Error::Allocation)?;
547    let mut bytes = vec![0; length];
548    encoder.encode_plaintext(&mut bytes)?;
549    Ok(bytes)
550}
551/// A complete example snapshot emitted by the production streaming encoder.
552pub fn snapshot_frames() -> Vec<Vec<u8>> {
553    let (mut encoder, header) = SnapshotEncoder::start(snapshot_header()).unwrap();
554    let mut frames = vec![header];
555    for record in snapshot_records() {
556        frames.push(encoder.record(record).unwrap());
557    }
558    frames.push(encoder.finish().unwrap());
559    frames
560}
561/// The S3 location `coven-storage` packs into a code's storage part
562/// (D13): provider 0, bucket `bucket`, region `region`, no endpoint, no
563/// profile.
564const S3_LOCATION: &[u8] = b"\0\0\0\0\x06bucket\0\0\0\x06region\0\0";
565
566/// Restore contents with test seeds and that S3 location, without a key.
567pub fn restore() -> RestoreCode {
568    RestoreCode {
569        store: StoreId(Uuid::from_bytes([0x10; 16])),
570        member: member_id(),
571        member_keys: member_keys(),
572        storage: SecretBytes::new([S3_LOCATION, b"\0"].concat()),
573    }
574}
575/// The restore code as coven saves it for the person, named by a rename at slot 41.
576pub fn keychain_restore() -> KeychainRestoreCode {
577    KeychainRestoreCode { name: "Family".into(), named_at: slot(41), code: restore() }
578}
579/// Invite contents with a fixed test secret.
580pub fn invite() -> InviteCode {
581    InviteCode {
582        store: StoreId(Uuid::from_bytes([0x10; 16])),
583        name: "S".into(),
584        inviter: "A".into(),
585        // A re-binding invite recovers Ana, whose profile has her name.
586        admits: InviteAdmits::MemberKeys,
587        expires_at: 86_400,
588        invite: InviteId(Uuid::from_bytes([0x55; 16])),
589        // A re-binding invite names Ana's existing id (D13).
590        member: member_id(),
591        secret: InviteSecret::from_bytes([0x66; 32]),
592        initial_key: store_key().id(),
593        inviting_writer: DeviceId(1),
594        read_through: 12,
595        // The S3 location, then the key made for the invite.
596        storage: SecretBytes::new([S3_LOCATION, b"\0\0\0\x02id\0\0\0\x06secret"].concat()),
597    }
598}
599/// A pairing code for Ana's member, shown by device one, with the S3 location
600/// and the key the showing device connects with: the QR code (D13).
601pub fn pairing() -> PairingCode {
602    PairingCode {
603        store: StoreId(Uuid::from_bytes([0x10; 16])),
604        expires_at: 1_800,
605        pairing: InviteId(Uuid::from_bytes([0x57; 16])),
606        member: member_id(),
607        secret: InviteSecret::from_bytes([0x67; 32]),
608        showing: DeviceId(1),
609        storage: SecretBytes::new([S3_LOCATION, b"\x01\0\0\0\x02id\0\0\0\x06secret"].concat()),
610    }
611}
612/// The same pairing's code Ana copies or shares as text: no key follows.
613pub fn pairing_without_key() -> PairingCode {
614    PairingCode { storage: SecretBytes::new([S3_LOCATION, b"\0"].concat()), ..pairing() }
615}
616/// A pairing code for Household on Dropbox, in the shared folder with namespace
617/// id `4815162342`, which Ana signed in to as `ana@example.com` (D13).
618pub fn pairing_on_dropbox() -> PairingCode {
619    let location: &[u8] = b"\x01\x01\0\0\0\x0a4815162342\x01\0\0\0\x0fana@example.com";
620    PairingCode { storage: SecretBytes::new(location.to_vec()), ..pairing() }
621}
622/// The laptop's request answering that pairing with its fresh pair, which
623/// signs it: the member's own device, with no name.
624pub fn pairing_request() -> JoinRequest {
625    JoinRequest { invite: pairing().pairing, joiner: Joiner::OwnDevice, ..join_request() }
626}
627/// Where the laptop's request goes, and the handover takes its place.
628pub fn pairing_request_path() -> crate::path::ObjectPath {
629    pairing().request_path()
630}
631/// Each admin operation in its canonical tag order.
632pub fn store_changes() -> Vec<StoreChange> {
633    let c = CircleId(uuid::Uuid::from_bytes([2; 16]));
634    let m = member_id();
635    vec![
636        creation_change(),
637        StoreChange::AdmitMember {
638            member: other_member_id(),
639            keys: other_member(),
640            role: MemberRole::Member,
641            access: crate::MemberAccess::ProviderAccount("member@example.test".into()),
642            device: DeviceId(2),
643            device_name: "D".into(),
644            person: "P".into(),
645            circle: admitted_circle(),
646        },
647        member_removal(),
648        StoreChange::ChangeRole { member: m, role: MemberRole::Admin },
649        StoreChange::AddDevice { name: "D".into(), replaces: None },
650        StoreChange::RemoveDevice { device: DeviceId(2) },
651        StoreChange::CreateCircle {
652            circle: c,
653            name: "C".into(),
654            key: coven_foundation::id_source::KeyId(uuid::Uuid::from_bytes([1; 16])),
655            key_hash: store_key().hash(),
656            breaking_version: 2,
657        },
658        StoreChange::RenameCircle { circle: c, name: "N".into() },
659        StoreChange::DeleteCircle { circle: c },
660        StoreChange::AddCircleMember { circle: c, member: m },
661        StoreChange::RemoveCircleMember {
662            circle: c,
663            member: m,
664            key: KeyId(Uuid::from_bytes([5; 16])),
665            key_hash: [0xb3; 32],
666        },
667        StoreChange::RaiseSchema { version: 2, announcement: slot(7) },
668        StoreChange::Reset { announcement: slot(8) },
669        StoreChange::SetAccess {
670            member: m,
671            access: crate::MemberAccess::S3AccessKey { access_key_id: "replacement-key".into() },
672        },
673        StoreChange::RotateKey {
674            audience: Audience::Store,
675            key: KeyId(Uuid::from_bytes([3; 16])),
676            key_hash: [0x91; 32],
677        },
678        StoreChange::RotateKey {
679            audience: Audience::Circle(c),
680            key: KeyId(Uuid::from_bytes([4; 16])),
681            key_hash: [0xa2; 32],
682        },
683        StoreChange::ReplaceMemberKeys { member: m, expected: member(), keys: replacement() },
684        StoreChange::RenameStore { name: "N".into() },
685        StoreChange::AddInviteShare {
686            invite: InviteId(Uuid::from_bytes([0x55; 16])),
687            account: "dan@example.org".into(),
688        },
689        StoreChange::EndInviteShare { invite: InviteId(Uuid::from_bytes([0x55; 16])) },
690        StoreChange::RecoverMember {
691            member: m,
692            expected: member(),
693            keys: replacement(),
694            access: Some(crate::MemberAccess::S3AccessKey {
695                access_key_id: "recovered-key".into(),
696            }),
697            device: DeviceId(3),
698            device_name: "D".into(),
699            circle: recovered_circle(),
700        },
701        StoreChange::SetUpStorage {
702            access: crate::MemberAccess::S3AccessKey { access_key_id: "fixture-access-key".into() },
703        },
704    ]
705}
706/// Ana's private circle, which the store's creation makes: its key's bytes
707/// are 21 repeated, and its copy is in the creation fixture's prefix.
708pub fn created_circle() -> NewCircle {
709    new_circle(10, 11, 21, "A")
710}
711/// Ana's private circle's first key, whose copy the creation fixture carries.
712pub fn created_circle_key() -> coven_crypto::CircleKey {
713    let circle = created_circle();
714    coven_crypto::CircleKey::from_bytes(circle.circle, circle.key, [21; 32])
715}
716/// The circle Ben's admission makes: its key's bytes are 19 repeated, and its
717/// copy is Ben's own copy in the admission fixture.
718pub fn admitted_circle() -> NewCircle {
719    new_circle(6, 7, 19, "B")
720}
721/// The circle Ana's recovery makes: its key's bytes are 20 repeated, and its
722/// copy is the one her request carries.
723pub fn recovered_circle() -> NewCircle {
724    new_circle(8, 9, 20, "R")
725}
726fn new_circle(circle: u8, key: u8, bytes: u8, name: &str) -> NewCircle {
727    let circle = CircleId(Uuid::from_bytes([circle; 16]));
728    let key = KeyId(Uuid::from_bytes([key; 16]));
729    NewCircle {
730        circle,
731        name: name.into(),
732        breaking_version: 2,
733        key,
734        key_hash: coven_crypto::CircleKey::from_bytes(circle, key, [bytes; 32]).hash(),
735    }
736}
737/// Ana's own copy of her recovery circle's key, sealed to her replacement
738/// pair for her request, as the independent generator wrote it.
739pub fn recovered_circle_copy() -> crate::sealed_key::CopyBox {
740    let bytes = fixture_bytes(include_str!("../fixtures/own-copy.hex"));
741    let mut input = crate::wire::Decoder::new(&bytes).expect("pinned own copy");
742    let copy = <crate::sealed_key::CopyBox as crate::wire::Wire>::get(&mut input)
743        .expect("pinned own copy");
744    input.finish().expect("pinned own copy");
745    copy
746}
747/// Every independently decoded ordinary object kind.
748pub fn objects() -> Vec<Object> {
749    store_changes()
750        .into_iter()
751        .map(Object::Admin)
752        .chain([Object::JoinRequest(join_request())])
753        .collect()
754}
755/// Ana's request answering the re-binding invite with her replacement pair,
756/// which signs it (D8, D13).
757pub fn join_request() -> JoinRequest {
758    JoinRequest {
759        invite: InviteId(Uuid::from_bytes([0x55; 16])),
760        member: member_id(),
761        keys: replacement(),
762        device: DeviceId(3),
763        device_name: "D".into(),
764        joiner: Joiner::MemberKeys {
765            circle: JoiningCircle { circle: recovered_circle(), copy: recovered_circle_copy() },
766        },
767    }
768}
769/// A two-audience write with a row frame spanning three chunks.
770pub fn chunked_write() -> WriteRecord {
771    let mut record = write();
772    let mut circle = record.parts[0].clone();
773    circle.audience = Audience::Circle(CircleId(Uuid::from_u128(1)));
774    circle.rows[0].row.audience = circle.audience.clone();
775    circle.executions = vec![transient_execution(circle.audience.clone())];
776    record.parts.push(circle);
777    let blob = Operation::Update(BTreeMap::from([(
778        "x".into(),
779        column(Value::Blob(vec![0x41; crate::chunks::CHUNK_SIZE * 2 + 29])),
780    )]));
781    record.parts[0].rows[0].change.operation = blob.clone();
782    record.parts[0].rows[0].execution.steps[0].change.operation = blob;
783    record
784}
785/// A snapshot with a merge row spanning chunk boundaries.
786pub fn chunked_snapshot_frames() -> Vec<Vec<u8>> {
787    let (mut encoder, header) = SnapshotEncoder::start(snapshot_header()).unwrap();
788    let mut records = snapshot_records();
789    let large = records.iter_mut().find(|record| matches!(record, SnapshotRecord::Merge(_)));
790    *large.expect("the fixture's merge row") = SnapshotRecord::Merge(merge_row_of(
791        row(),
792        Value::Blob(vec![0x42; crate::chunks::CHUNK_SIZE + 31]),
793    ));
794    let mut frames = vec![header];
795    for record in records {
796        frames.push(encoder.record(record).unwrap());
797    }
798    frames.push(encoder.finish().unwrap());
799    frames
800}
801/// Bounded canonical frames used to exercise every byte and truncation.
802pub fn frame_examples() -> Vec<Zeroizing<Vec<u8>>> {
803    let mut frames: Vec<_> =
804        objects().iter().map(|v| Zeroizing::new(v.encode().unwrap())).collect();
805    let record = write();
806    let encoder = crate::write_stream::WriteEncoder::new(&record).unwrap();
807    frames.push(Zeroizing::new(encoder.header_frame().to_vec()));
808    frames.push(Zeroizing::new(record.parts[0].rows[0].encode().unwrap()));
809    frames.push(Zeroizing::new(
810        crate::dismissal::Dismissal {
811            row: row(),
812            target: crate::dismissal::DismissalTarget::Cell("x".into()),
813            write: position(),
814        }
815        .encode()
816        .unwrap(),
817    ));
818    let mut migration = record.clone();
819    migration.header.disposition = WriteDisposition::Migration;
820    migration.parts.clear();
821    frames.push(Zeroizing::new(write_plaintext(&migration).unwrap()));
822    frames.extend(snapshot_frames().into_iter().map(Zeroizing::new));
823    frames
824}
825/// Pinned plaintext frames, then a write prefix/header/part chunks and a
826/// snapshot prefix/plaintext chunks. Crypto supplies sealed bytes separately.
827pub fn encoded_examples() -> Vec<Zeroizing<Vec<u8>>> {
828    let mut pieces = frame_examples();
829    let record = chunked_write();
830    let encoder = crate::write_stream::WriteEncoder::new(&record).unwrap();
831    pieces.push(Zeroizing::new(
832        crate::sealed_write::WriteObjectPrefix {
833            format: crate::FormatVersion::CURRENT,
834            store_key: KeyId(Uuid::from_bytes([1; 16])),
835            part_keys: vec![KeyId(Uuid::from_bytes([1; 16])), KeyId(Uuid::from_bytes([2; 16]))],
836        }
837        .encode()
838        .unwrap(),
839    ));
840    pieces.push(Zeroizing::new(encoder.header_frame().to_vec()));
841    for index in 0..record.parts.len() {
842        pieces.extend(encoder.part_chunks(index).unwrap().map(|v| Zeroizing::new(v.unwrap())));
843    }
844    pieces.push(Zeroizing::new(snapshot_prefix(&snapshot_header()).encode().unwrap()));
845    pieces.extend(
846        crate::chunks::PlaintextChunks::new(chunked_snapshot_frames().into_iter().map(Ok))
847            .map(|v| Zeroizing::new(v.unwrap())),
848    );
849    pieces
850}
851
852/// The fixture author has read these original writes.
853pub fn past() -> BTreeSet<WriteId> {
854    [(1, 1), (1, 2), (2, 1)]
855        .map(|(device, number)| WriteId { device: DeviceId(device), number })
856        .into()
857}
858/// Validate the fixture write against its explicitly supplied past.
859pub fn check_past(record: &WriteRecord) -> Result<(), crate::Error> {
860    let past = past();
861    for part in &record.parts {
862        for row in &part.rows {
863            row.validate_past(&past)?;
864        }
865        for execution in &part.executions {
866            execution.execution.sources.validate_past(&past)?;
867        }
868        for dismissal in &part.dismissals {
869            dismissal.validate_past(&past)?;
870        }
871    }
872    Ok(())
873}