Skip to main content

coven_sync/
creation.rs

1//! A store's slot 1, decided when the store is created (§10.3).
2
3use crate::{
4    history::History,
5    sequence_sync::sequence_copies::{admission_prefix, required_copies},
6    sequence_sync::sequence_operations::{
7        OperationProgress, OperationStep, Request, SequenceOperation,
8    },
9    slot_object, PendingRecord, SyncError,
10};
11use coven_crypto::{MemberIdentity, StoreKeyring};
12use coven_database::{ClaimAttempt, ClaimWork, StoreDatabase};
13use coven_format::{
14    admin::StoreChange,
15    path::ObjectPath,
16    sequence::{SlotFrame, SlotHeader},
17};
18use coven_foundation::id_source::{CircleId, DeviceId, KeyId, StoreId};
19use coven_merge::Slot;
20use std::io::Cursor;
21use std::sync::{Arc, Mutex};
22
23/// A circle slot 1 makes, whose first key `ring` holds.
24#[derive(Clone, Debug)]
25pub struct NewCircle {
26    /// The circle's id.
27    pub circle: CircleId,
28    /// The circle's name.
29    pub name: String,
30    /// The circle's first key.
31    pub key: KeyId,
32}
33
34/// What slot 1 sets up: the store, its first admin with her join facts, her
35/// first device, the first store key and the circles' first keys `ring`
36/// holds.
37pub struct Creation<'a> {
38    /// The new store's id.
39    pub store: StoreId,
40    /// The store's name.
41    pub name: String,
42    /// This installation's device id.
43    pub device: DeviceId,
44    /// The name of this installation, the first admin's first device.
45    pub device_name: String,
46    /// The first admin, who signs slot 1.
47    pub member: &'a MemberIdentity,
48    /// The creator's name, which her devices' joining write reads (§13.2).
49    pub person: String,
50    /// The creator's private circle, whose only member she is.
51    pub circle: NewCircle,
52    /// The circles the creator's first write asks for, each with the
53    /// creator as its first member.
54    pub circles: Vec<NewCircle>,
55    /// The custody ring holding the first store key and each circle's first
56    /// key, and no other.
57    pub ring: &'a StoreKeyring,
58}
59
60/// Seal slot 1, journal its exact bytes as this device's attempt at it with
61/// the operation that sends it, and apply it, all in `database`. The store is
62/// not published yet, so no other device can claim slot 1 first; setup
63/// later sends these bytes (§10.3). The creator's copy of each key slot 1
64/// introduces rides in its clear prefix, as an admission's copies do (§12.1).
65/// Applying slot 1 runs the app's joining write for the creator's device, as
66/// an admission's application does for a joiner's (§13.2).
67pub async fn decide_creation(
68    database: &StoreDatabase,
69    creation: Creation<'_>,
70) -> Result<(), SyncError> {
71    let Creation { store, name, device, device_name, member, person, circle, circles, ring } =
72        creation;
73    let breaking_version = database.breaking_version().await?;
74    let made = |new: NewCircle| {
75        Ok::<_, SyncError>(coven_format::admin::NewCircle {
76            key_hash: ring.circle_key(new.circle, new.key)?.hash(),
77            circle: new.circle,
78            name: new.name,
79            breaking_version,
80            key: new.key,
81        })
82    };
83    let circle = made(circle)?;
84    let circles = circles.into_iter().map(made).collect::<Result<Vec<_>, _>>()?;
85    let key =
86        ring.store_key_ids().next().ok_or(coven_storage::StorageFailure::MemberKeysMissing)?;
87    let change = StoreChange::CreateStore {
88        store,
89        name,
90        admin: member.keys().public_keys(),
91        key,
92        key_hash: ring.store_key(key)?.hash(),
93        device_name,
94        person,
95        circle,
96        circles,
97    };
98    let history = History::default();
99    let copies = required_copies(&history, ring, &change, member.member());
100    let operation = SequenceOperation {
101        request: Request::Change(change.clone()),
102        progress: OperationProgress::Running(OperationStep::Claiming),
103    };
104    let id = database.start_operation(operation.journaled("creation")?).await?;
105    let path = ObjectPath::slot(store, Slot::FIRST.into());
106    let frame = SlotFrame::Admin(change);
107    let sealed = Arc::new(Mutex::new(None));
108    let kept = sealed.clone();
109    let (held, author, claimed) = (ring.clone(), member.clone(), path.clone());
110    database
111        .begin_claim(ClaimWork::Operation(id), move |claim| {
112            let header = SlotHeader { device, claim, author: author.member(), after: 0 };
113            let plaintext = frame.encode(&header, &claimed)?.len();
114            let prefix = admission_prefix(&held, &claimed, key, copies, None, plaintext)??;
115            let bytes =
116                slot_object::seal_bounded(&claimed, &header, &frame, prefix, &held, &author)?;
117            *kept.lock().unwrap_or_else(std::sync::PoisonError::into_inner) = Some(bytes.clone());
118            Ok::<_, SyncError>(ClaimAttempt { path: claimed.clone(), bytes: Cursor::new(bytes) })
119        })
120        .await?;
121    let bytes = sealed
122        .lock()
123        .unwrap_or_else(std::sync::PoisonError::into_inner)
124        .take()
125        .ok_or(coven_database::DbError::Invariant { what: "slot 1 was sealed" })?;
126    let mut history = History::default();
127    let received = slot_object::open_bounded(bytes, &path, ring, &history)?;
128    let incoming = history.consume(received, member.member());
129    let applied = database
130        .apply_slot::<PendingRecord, _, _>(incoming, history.writers(device), || Ok(()))
131        .await
132        .map_err(|error| crate::write_object::database_failure(&path, error))?;
133    match applied {
134        coven_database::ApplyOutcome::Applied => Ok(()),
135        _ => Err(coven_database::DbError::Invariant { what: "slot 1 applies whole" }.into()),
136    }
137}
138
139#[cfg(test)]
140#[path = "creation_tests.rs"]
141pub(crate) mod tests;