chio-store-sqlite 0.1.2

SQLite-backed persistence, query, and report implementations for Chio
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
use std::sync::{Arc, Mutex, MutexGuard};

use chio_core::StoreMutationFence;
use chio_federation_authority::{FrostAuthenticatedDkgPackage, FrostCeremonySecret};
use rusqlite::{Connection, Transaction, TransactionBehavior};
use serde::{Deserialize, Serialize};

use crate::admission_operation_store::verify_active_owner;
use crate::encrypted_blob::TenantKey;
use crate::serving_owner::SqliteServingOwner;

mod ceremony;
mod commit;
mod coordinator;
mod rotation;
mod rotation_validation;
mod schema;
mod signer;

use schema::FROST_STORE_SCHEMA;

const FROST_STORE_SCHEMA_KEY: &str = "frost";
pub(crate) const FROST_STORE_SUPPORTED_SCHEMA_VERSION: i32 = 0;
const FROST_STORE_SCHEMA_ANCHORS: &[&str] = &[
    "frost_ceremonies",
    "chio_serving_owner",
    "capability_grant_budgets",
];

#[derive(Debug, thiserror::Error)]
pub enum FrostStoreError {
    #[error("sqlite FROST store is fenced")]
    Fenced,
    #[error("sqlite FROST store conflict: {0}")]
    Conflict(&'static str),
    #[error("sqlite FROST store state is invalid: {0}")]
    InvalidState(String),
    #[error("sqlite FROST custody failed: {0}")]
    Custody(&'static str),
    #[error("sqlite FROST store unavailable: {0}")]
    Unavailable(String),
    #[error(transparent)]
    Ceremony(#[from] chio_federation_authority::FrostCeremonyError),
}

pub struct FrostCustodyKey {
    generation: String,
    key: TenantKey,
}

impl std::fmt::Debug for FrostCustodyKey {
    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        formatter
            .debug_struct("FrostCustodyKey")
            .field("generation", &self.generation)
            .field("key", &"<redacted>")
            .finish()
    }
}

impl FrostCustodyKey {
    pub fn new(
        generation: impl Into<String>,
        key_bytes: [u8; 32],
    ) -> Result<Self, FrostStoreError> {
        let generation = generation.into();
        if generation.is_empty()
            || generation.len() > 128
            || generation.trim() != generation
            || !generation.bytes().all(|byte| byte.is_ascii_graphic())
        {
            return Err(FrostStoreError::Custody(
                "generation must be unpadded printable ASCII",
            ));
        }
        Ok(Self {
            generation,
            key: TenantKey::from_bytes(key_bytes),
        })
    }

    #[must_use]
    pub fn generation(&self) -> &str {
        &self.generation
    }

    pub(super) fn key(&self) -> &TenantKey {
        &self.key
    }
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum FrostCeremonyState {
    Round1Ready,
    Round2Ready,
    Completed,
}

impl FrostCeremonyState {
    pub(super) const fn as_str(self) -> &'static str {
        match self {
            Self::Round1Ready => "round1_ready",
            Self::Round2Ready => "round2_ready",
            Self::Completed => "completed",
        }
    }

    pub(super) fn parse(value: &str) -> Result<Self, FrostStoreError> {
        match value {
            "round1_ready" => Ok(Self::Round1Ready),
            "round2_ready" => Ok(Self::Round2Ready),
            "completed" => Ok(Self::Completed),
            _ => Err(FrostStoreError::InvalidState(
                "unknown ceremony state".to_string(),
            )),
        }
    }
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub struct FrostCeremonyRecord {
    pub ceremony_id: String,
    pub state: FrostCeremonyState,
    pub state_version: u64,
    pub participant_set_digest: String,
    pub scope_id: String,
    pub key_epoch: u64,
    pub local_participant_id: String,
    pub input_transcript_digest: Option<String>,
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub struct FrostCeremonyRound1Record {
    pub ceremony_id: String,
    pub state: FrostCeremonyState,
    pub state_version: u64,
    pub package: FrostAuthenticatedDkgPackage,
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub struct FrostCeremonyRound2Record {
    pub ceremony_id: String,
    pub state: FrostCeremonyState,
    pub state_version: u64,
    pub packages: Vec<FrostAuthenticatedDkgPackage>,
    pub round1_transcript_digest: String,
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub struct StoredFrostCeremonyCompletion {
    pub ceremony_id: String,
    pub state: FrostCeremonyState,
    pub state_version: u64,
    pub public_key_package: Vec<u8>,
    pub group_public_key: String,
    pub verification_shares: std::collections::BTreeMap<String, String>,
    pub transcript_digest: String,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum FrostRotationState {
    Staged,
    AnchorAdvanced,
    Active,
    Discarded,
}

impl FrostRotationState {
    pub(super) const fn as_str(self) -> &'static str {
        match self {
            Self::Staged => "staged",
            Self::AnchorAdvanced => "anchor_advanced",
            Self::Active => "active",
            Self::Discarded => "discarded",
        }
    }

    pub(super) fn parse(value: &str) -> Result<Self, FrostStoreError> {
        match value {
            "staged" => Ok(Self::Staged),
            "anchor_advanced" => Ok(Self::AnchorAdvanced),
            "active" => Ok(Self::Active),
            "discarded" => Ok(Self::Discarded),
            _ => Err(FrostStoreError::InvalidState(
                "unknown FROST rotation state".to_string(),
            )),
        }
    }
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub struct FrostActiveRosterRecord {
    pub scope_id: String,
    pub key_epoch: u64,
    pub roster_digest: String,
    pub checkpoint_sequence: u64,
    pub checkpoint_digest: String,
    pub activation_fence: u64,
    pub clock_high_water: u64,
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub struct FrostRotationRecord {
    pub rotation_id: String,
    pub scope_id: String,
    pub state: FrostRotationState,
    pub state_version: u64,
    pub predecessor_checkpoint_digest: String,
    pub target_roster_digest: String,
    pub target_key_epoch: u64,
    pub anchored_checkpoint_digest: Option<String>,
}

#[derive(Debug, Clone)]
pub struct StagedFrostRotation {
    rotation_id: String,
    advance: chio_federation::frost::VerifiedFrostEpochAdvance,
}

pub struct FrostSignerSessionRequest<'a> {
    pub body: &'a chio_federation::frost::FrostAuthorizationBodyV1,
    pub active_roster: &'a chio_federation::frost::VerifiedActiveFrostRoster,
    pub epoch_anchor: &'a dyn chio_federation::frost::FrostEpochAnchor,
    pub slot_anchor: &'a dyn chio_federation::frost::FrostAuthorizationSlotAnchorWriter,
    pub artifact_trust: &'a chio_federation::frost::FrostArtifactTrustStore,
    pub ceremony_id: &'a str,
    pub participant_id: &'a str,
    pub coordinator_id: &'a str,
}

pub struct FrostCoordinatorSessionRequest<'a> {
    pub body: &'a chio_federation::frost::FrostAuthorizationBodyV1,
    pub active_roster: &'a chio_federation::frost::VerifiedActiveFrostRoster,
    pub epoch_anchor: &'a dyn chio_federation::frost::FrostEpochAnchor,
    pub slot_anchor: &'a dyn chio_federation::frost::FrostAuthorizationSlotAnchorWriter,
    pub artifact_trust: &'a chio_federation::frost::FrostArtifactTrustStore,
    pub coordinator_id: &'a str,
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase", deny_unknown_fields)]
pub struct FrostCoordinatorLease {
    pub session_id: String,
    pub authorization_slot_id: String,
    pub coordinator_id: String,
    pub worker_id: String,
    pub lease_id: String,
    pub owner_epoch: u64,
    pub expires_at_unix_ms: u64,
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase", deny_unknown_fields)]
pub struct FrostCoordinatorCommitment {
    pub participant_id: String,
    pub signer_identifier: Vec<u8>,
    pub commitment_bytes: Vec<u8>,
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase", deny_unknown_fields)]
pub struct FrostCoordinatorShare {
    pub participant_id: String,
    pub share_bytes: Vec<u8>,
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase", deny_unknown_fields)]
pub struct FrostCoordinatorSigningPackage {
    pub session_id: String,
    pub participant_ids: Vec<String>,
    pub signing_package_bytes: Vec<u8>,
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase", deny_unknown_fields)]
pub struct FrostCoordinatorSessionRecord {
    pub session_id: String,
    pub authorization_slot_id: String,
    pub state: FrostCoordinatorSessionState,
    pub row_version: u64,
    pub commitment_count: usize,
    pub share_count: usize,
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase", deny_unknown_fields)]
pub struct FrostCoordinatorCancellation {
    pub session: FrostCoordinatorSessionRecord,
    pub participant_ids: Vec<String>,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum FrostCoordinatorSessionState {
    CollectingCommitments,
    PackageReady,
    AuthorizationReady,
    Completed,
    Burned,
}

impl FrostCoordinatorSessionState {
    #[must_use]
    pub const fn as_str(self) -> &'static str {
        match self {
            Self::CollectingCommitments => "collecting_commitments",
            Self::PackageReady => "package_ready",
            Self::AuthorizationReady => "authorization_ready",
            Self::Completed => "completed",
            Self::Burned => "burned",
        }
    }

    pub(super) fn parse(value: &str) -> Result<Self, FrostStoreError> {
        match value {
            "collecting_commitments" => Ok(Self::CollectingCommitments),
            "package_ready" => Ok(Self::PackageReady),
            "authorization_ready" => Ok(Self::AuthorizationReady),
            "completed" => Ok(Self::Completed),
            "burned" => Ok(Self::Burned),
            _ => Err(FrostStoreError::InvalidState(
                "unknown FROST coordinator state".to_string(),
            )),
        }
    }
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub struct FrostSignerSessionRecord {
    pub session_id: String,
    pub participant_id: String,
    pub authorization_slot_id: String,
    pub state: FrostSignerSessionState,
    pub state_version: u64,
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub struct FrostSignerCommitment {
    pub session_id: String,
    pub participant_id: String,
    pub signer_identifier: Vec<u8>,
    pub commitment_bytes: Vec<u8>,
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub struct FrostSignerShare {
    pub session_id: String,
    pub participant_id: String,
    pub share_bytes: Vec<u8>,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum FrostSignerSessionState {
    Prepared,
    CommitmentPublished,
    ShareReady,
    Completed,
    Burned,
}

impl FrostSignerSessionState {
    #[must_use]
    pub const fn as_str(self) -> &'static str {
        match self {
            Self::Prepared => "prepared",
            Self::CommitmentPublished => "commitment_published",
            Self::ShareReady => "share_ready",
            Self::Completed => "completed",
            Self::Burned => "burned",
        }
    }

    pub(super) fn parse(value: &str) -> Result<Self, FrostStoreError> {
        match value {
            "prepared" => Ok(Self::Prepared),
            "commitment_published" => Ok(Self::CommitmentPublished),
            "share_ready" => Ok(Self::ShareReady),
            "completed" => Ok(Self::Completed),
            "burned" => Ok(Self::Burned),
            _ => Err(FrostStoreError::InvalidState(
                "unknown FROST signer state".to_string(),
            )),
        }
    }
}

impl StagedFrostRotation {
    #[must_use]
    pub fn rotation_id(&self) -> &str {
        &self.rotation_id
    }

    #[must_use]
    pub fn advance(&self) -> &chio_federation::frost::VerifiedFrostEpochAdvance {
        &self.advance
    }
}

#[derive(Clone)]
pub struct SqliteFrostStore {
    connection: Arc<Mutex<Connection>>,
    serving_owner: Arc<SqliteServingOwner>,
}

impl SqliteFrostStore {
    pub(crate) fn open_alongside(
        connection: Arc<Mutex<Connection>>,
        serving_owner: Arc<SqliteServingOwner>,
    ) -> Self {
        Self {
            connection,
            serving_owner,
        }
    }

    fn connection(&self) -> Result<MutexGuard<'_, Connection>, FrostStoreError> {
        self.connection.lock().map_err(|_| {
            FrostStoreError::Unavailable("sqlite FROST store lock is poisoned".to_string())
        })
    }

    fn begin_read<'a>(
        &self,
        connection: &'a mut Connection,
        fence: Option<&StoreMutationFence>,
    ) -> Result<Transaction<'a>, FrostStoreError> {
        let transaction = connection
            .transaction_with_behavior(TransactionBehavior::Deferred)
            .map_err(sqlite_error)?;
        verify_active_owner(&transaction, &self.serving_owner, fence).map_err(owner_error)?;
        self.serving_owner
            .verify_authority_anchor(&transaction)
            .map_err(|error| FrostStoreError::Unavailable(error.to_string()))?;
        Ok(transaction)
    }

    fn begin_write<'a>(
        &self,
        connection: &'a mut Connection,
        fence: &StoreMutationFence,
    ) -> Result<Transaction<'a>, FrostStoreError> {
        let transaction = connection
            .transaction_with_behavior(TransactionBehavior::Immediate)
            .map_err(sqlite_error)?;
        verify_active_owner(&transaction, &self.serving_owner, Some(fence)).map_err(owner_error)?;
        self.serving_owner
            .verify_authority_anchor(&transaction)
            .map_err(|error| FrostStoreError::Unavailable(error.to_string()))?;
        Ok(transaction)
    }

    fn commit_write(&self, transaction: Transaction<'_>) -> Result<(), FrostStoreError> {
        transaction.commit().map_err(|error| {
            FrostStoreError::Unavailable(
                self.serving_owner
                    .outcome_unknown(format!("sqlite FROST commit outcome is unknown: {error}"))
                    .to_string(),
            )
        })
    }

    fn sync_after_write(&self, connection: &Connection) -> Result<(), FrostStoreError> {
        self.serving_owner
            .sync_authority_anchor(connection)
            .map_err(|error| FrostStoreError::Unavailable(error.to_string()))
    }
}

pub(crate) fn initialize_frost_schema(connection: &mut Connection) -> Result<(), FrostStoreError> {
    crate::check_schema_version(
        connection,
        FROST_STORE_SCHEMA_KEY,
        FROST_STORE_SUPPORTED_SCHEMA_VERSION,
        FROST_STORE_SCHEMA_ANCHORS,
    )
    .map_err(|error| FrostStoreError::InvalidState(error.to_string()))?;
    let transaction = connection
        .transaction_with_behavior(TransactionBehavior::Immediate)
        .map_err(sqlite_error)?;
    transaction
        .execute_batch(FROST_STORE_SCHEMA)
        .map_err(sqlite_error)?;
    crate::stamp_schema_version(
        &transaction,
        FROST_STORE_SCHEMA_KEY,
        FROST_STORE_SUPPORTED_SCHEMA_VERSION,
    )
    .map_err(|error| FrostStoreError::InvalidState(error.to_string()))?;
    verify_frost_store_invariants(&transaction)?;
    transaction.commit().map_err(sqlite_error)
}

pub(crate) fn verify_frost_store_invariants(
    connection: &Connection,
) -> Result<(), FrostStoreError> {
    let expected = Connection::open_in_memory().map_err(sqlite_error)?;
    expected
        .execute_batch(FROST_STORE_SCHEMA)
        .map_err(sqlite_error)?;
    if frost_schema_catalog(connection)? != frost_schema_catalog(&expected)? {
        return Err(FrostStoreError::InvalidState(
            "FROST store schema differs from the canonical definition".to_string(),
        ));
    }
    ceremony::verify_ceremony_invariants(connection)?;
    rotation::verify_rotation_invariants(connection)?;
    signer::verify_signer_invariants(connection)?;
    coordinator::verify_coordinator_invariants(connection)
}

type FrostSchemaCatalogEntry = (String, String, String, Option<String>);

fn frost_schema_catalog(
    connection: &Connection,
) -> Result<Vec<FrostSchemaCatalogEntry>, FrostStoreError> {
    let mut statement = connection
        .prepare(
            r#"
            SELECT type, name, tbl_name, sql FROM sqlite_schema
            WHERE name GLOB 'frost_*' OR tbl_name GLOB 'frost_*'
            ORDER BY type, name, tbl_name
            "#,
        )
        .map_err(sqlite_error)?;
    let catalog = statement
        .query_map([], |row| {
            Ok((row.get(0)?, row.get(1)?, row.get(2)?, row.get(3)?))
        })
        .map_err(sqlite_error)?
        .collect::<Result<Vec<_>, _>>()
        .map_err(sqlite_error)?;
    Ok(catalog)
}

fn sqlite_error(error: rusqlite::Error) -> FrostStoreError {
    FrostStoreError::Unavailable(error.to_string())
}

fn owner_error(
    error: chio_kernel::admission_operation::AdmissionOperationStoreError,
) -> FrostStoreError {
    if matches!(
        error,
        chio_kernel::admission_operation::AdmissionOperationStoreError::Fenced
    ) {
        FrostStoreError::Fenced
    } else {
        FrostStoreError::Unavailable(error.to_string())
    }
}

#[derive(Serialize, Deserialize)]
#[serde(tag = "state", content = "output", rename_all = "snake_case")]
enum StoredCeremonyOutput {
    Round1(Box<FrostAuthenticatedDkgPackage>),
    Round2(Vec<FrostAuthenticatedDkgPackage>),
}

pub(super) fn secret_kind_name(secret: &FrostCeremonySecret) -> &'static str {
    match secret.kind() {
        chio_federation_authority::FrostCeremonySecretKind::Round1 => "round1",
        chio_federation_authority::FrostCeremonySecretKind::Round2 => "round2",
        chio_federation_authority::FrostCeremonySecretKind::KeyPackage => "key_package",
    }
}