gemot 0.1.0

Community domain and assembly layer for Moot lifecycle, governance, replication, and Tessera.
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
//! Aggregate domain service for one Moot.
//!
//! This is the application boundary above constitutional governance and the
//! replicated Moot object store. Commands take seeds and domain values, persist
//! through the shared processor, and return plain receipts and snapshots.

use std::path::Path;

use muniment::{Backend, MemoryBackend, RedbBackend};
use proofs::Digest;

use crate::constitution::ConstitutionRules;

use super::MootId;
use super::governance::{MootGovernance, MootGovernanceError, MootGovernanceSnapshot};
use super::retention::{AvailabilityPolicy, ErasurePolicy, MootRetentionPolicy, PolicyRevision};
use super::roster::MootRoster;
use super::store::{MootStore, MootStoreError};
use super::wire::MootEvent;

/// Retention settings supplied by the Moot's governed configuration.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct MootRetentionSettings {
    pub revision: PolicyRevision,
    pub availability: AvailabilityPolicy,
    pub erasure: ErasurePolicy,
}

impl MootRetentionSettings {
    fn resolve(
        &self,
        checkpoint_authority: super::GovernedCheckpointAuthority,
    ) -> MootRetentionPolicy {
        MootRetentionPolicy {
            revision: self.revision.clone(),
            checkpoint_authority,
            availability: self.availability,
            erasure: self.erasure,
        }
    }
}

/// Latest accepted checkpoint, presented without wire-operation types.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct MootCheckpointSnapshot {
    pub operation: [u8; 32],
    pub policy_revision: PolicyRevision,
    pub authority_revision: Digest,
    pub previous_checkpoint: Option<[u8; 32]>,
    pub frontier_count: usize,
    pub at_ms: u64,
}

/// Readable current state of one Moot.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct MootSnapshot {
    pub moot_id: MootId,
    pub governance: MootGovernanceSnapshot,
    pub roster: MootRoster,
    pub checkpoint: Option<MootCheckpointSnapshot>,
}

/// Result of an object command. The operation id is enough for citations and
/// outbox tracking while the p2panda operation remains inside the store.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct MootCommandReceipt {
    pub operation: [u8; 32],
    pub snapshot: MootSnapshot,
}

/// Aggregate Moot service failure.
#[derive(Debug, thiserror::Error)]
pub enum MootError {
    #[error(transparent)]
    Governance(#[from] MootGovernanceError),
    #[error(transparent)]
    Store(#[from] MootStoreError),
    #[error("moot has no accepted retention checkpoint")]
    CheckpointMissing,
    #[error("moot storage directory: {0}")]
    Io(#[from] std::io::Error),
}

/// One Moot's constitutional and replicated object services.
#[derive(Clone)]
pub struct Moot<B> {
    moot_id: MootId,
    governance: MootGovernance<B>,
    objects: MootStore<B>,
    retention: MootRetentionSettings,
}

/// Durable redb-backed aggregate Moot service.
pub type MootFile = Moot<RedbBackend>;

impl Moot<MemoryBackend> {
    pub fn in_memory(moot_id: MootId, founder: [u8; 32], retention: MootRetentionSettings) -> Self {
        Self {
            moot_id,
            governance: MootGovernance::in_memory(moot_id.0, founder),
            objects: MootStore::in_memory(),
            retention,
        }
    }
}

impl Moot<RedbBackend> {
    /// Open one Moot beneath `directory`. Governance and object data use
    /// separate redb files while presenting one domain service.
    pub async fn open(
        directory: impl AsRef<Path>,
        moot_id: MootId,
        founder: [u8; 32],
        retention: MootRetentionSettings,
    ) -> Result<Self, MootError> {
        std::fs::create_dir_all(directory.as_ref())?;
        let service = Self {
            moot_id,
            governance: MootGovernance::open(
                directory.as_ref().join("constitution.redb"),
                moot_id.0,
                founder,
            )?,
            objects: MootStore::at_path(directory.as_ref().join("objects.redb"))?,
            retention,
        };
        match service.governance.snapshot().await {
            Ok(_) => service.refresh_retention_authority().await?,
            Err(MootGovernanceError::NotFounded) => {}
            Err(error) => return Err(error.into()),
        }
        Ok(service)
    }
}

impl<B: Backend + Clone> Moot<B> {
    pub fn moot_id(&self) -> MootId {
        self.moot_id
    }

    /// Lower store boundary for host-composed LogSync and native-drop adapters.
    pub fn object_store(&self) -> &MootStore<B> {
        &self.objects
    }

    async fn refresh_retention_authority(&self) -> Result<(), MootError> {
        let authority = self.governance.checkpoint_authority().await?;
        self.objects
            .set_retention_policy(Some(self.retention.resolve(authority)));
        Ok(())
    }

    /// Establish this Moot's first constitution and activate its checkpoint
    /// authority for subsequent object commands.
    pub async fn found(
        &self,
        founder_seed: [u8; 32],
        parent_constitution: Option<Digest>,
        divergence_point: Option<Digest>,
        rules: ConstitutionRules,
        at_ms: u64,
    ) -> Result<MootSnapshot, MootError> {
        self.governance
            .found(
                founder_seed,
                parent_constitution,
                divergence_point,
                rules,
                at_ms,
            )
            .await?;
        self.refresh_retention_authority().await?;
        self.snapshot().await
    }

    /// Amend the constitution and atomically switch future checkpoint
    /// admission to the accepted authority revision.
    pub async fn amend(
        &self,
        actor_seed: [u8; 32],
        rules: ConstitutionRules,
        at_ms: u64,
    ) -> Result<MootSnapshot, MootError> {
        self.governance.amend(actor_seed, rules, at_ms).await?;
        self.refresh_retention_authority().await?;
        self.snapshot().await
    }

    pub async fn declare(
        &self,
        actor_seed: [u8; 32],
        name: String,
        charter: String,
        at_ms: u64,
    ) -> Result<MootCommandReceipt, MootError> {
        self.governance.snapshot().await?;
        self.author_object(
            actor_seed,
            MootEvent::Declared {
                name,
                charter,
                at_ms,
            },
        )
        .await
    }

    pub async fn join(
        &self,
        actor_seed: [u8; 32],
        name: String,
        at_ms: u64,
    ) -> Result<MootCommandReceipt, MootError> {
        self.governance.snapshot().await?;
        self.author_object(actor_seed, MootEvent::Joined { name, at_ms })
            .await
    }

    pub async fn share(
        &self,
        actor_seed: [u8; 32],
        manifest_id: [u8; 32],
        schema_id: String,
        title: String,
        at_ms: u64,
    ) -> Result<MootCommandReceipt, MootError> {
        self.governance.snapshot().await?;
        self.author_object(
            actor_seed,
            MootEvent::Shared {
                manifest_id,
                schema_id,
                title,
                at_ms,
            },
        )
        .await
    }

    async fn author_object(
        &self,
        actor_seed: [u8; 32],
        event: MootEvent,
    ) -> Result<MootCommandReceipt, MootError> {
        let operation = self
            .objects
            .author_seed(actor_seed, self.moot_id.0, &event)
            .await?;
        Ok(MootCommandReceipt {
            operation: *operation.hash.as_bytes(),
            snapshot: self.snapshot().await?,
        })
    }

    /// Author the next checkpoint under the currently accepted constitution.
    pub async fn checkpoint(
        &self,
        actor_seed: [u8; 32],
        at_ms: u64,
    ) -> Result<MootCommandReceipt, MootError> {
        self.refresh_retention_authority().await?;
        let checkpoint = self.objects.build_checkpoint(self.moot_id.0, at_ms).await?;
        self.author_object(
            actor_seed,
            MootEvent::RetentionCheckpoint {
                checkpoint: Box::new(checkpoint),
            },
        )
        .await
    }

    /// Retire this actor's event prefix at the latest accepted checkpoint.
    pub async fn prune_current(
        &self,
        actor_seed: [u8; 32],
        at_ms: u64,
    ) -> Result<MootCommandReceipt, MootError> {
        let checkpoint = self
            .objects
            .latest_checkpoint(self.moot_id.0)
            .await?
            .ok_or(MootError::CheckpointMissing)?;
        let operation = self
            .objects
            .author_prune_seed(actor_seed, self.moot_id.0, checkpoint.operation, at_ms)
            .await?;
        Ok(MootCommandReceipt {
            operation: *operation.hash.as_bytes(),
            snapshot: self.snapshot().await?,
        })
    }

    pub async fn snapshot(&self) -> Result<MootSnapshot, MootError> {
        let governance = self.governance.snapshot().await?;
        let roster = self.objects.roster(self.moot_id.0).await?;
        let checkpoint = self
            .objects
            .latest_checkpoint(self.moot_id.0)
            .await?
            .map(|stored| MootCheckpointSnapshot {
                operation: stored.operation,
                policy_revision: stored.checkpoint.policy_revision,
                authority_revision: stored.checkpoint.authority_revision,
                previous_checkpoint: stored.checkpoint.previous_checkpoint,
                frontier_count: stored.checkpoint.frontier.len(),
                at_ms: stored.checkpoint.at_ms,
            });
        Ok(MootSnapshot {
            moot_id: self.moot_id,
            governance,
            roster,
            checkpoint,
        })
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::moot::{KeepBound, MootStoreError};
    use identity::{IdentityProvider, InMemoryProvider};

    const ID: MootId = MootId([0x6d; 32]);

    fn keypair(seed: u8) -> identity::Ed25519Keypair {
        InMemoryProvider::from_seed([seed; 32])
            .derive_keypair(b"moot-service")
            .unwrap()
    }

    fn retention() -> MootRetentionSettings {
        MootRetentionSettings {
            revision: PolicyRevision(Digest::blake3(b"moot retention settings")),
            availability: AvailabilityPolicy {
                promised_floor: KeepBound::Forever,
            },
            erasure: ErasurePolicy {
                history_ceiling: KeepBound::UntilCheckpoint,
            },
        }
    }

    #[tokio::test]
    async fn one_service_runs_governance_roster_checkpoint_and_rotation() {
        let founder = keypair(1);
        let successor = keypair(2);
        let service = Moot::in_memory(ID, founder.public_key().to_bytes(), retention());
        service
            .found(
                founder.to_seed(),
                None,
                None,
                ConstitutionRules::founder_only(founder.public_key().to_bytes()),
                1,
            )
            .await
            .unwrap();
        service
            .declare(
                founder.to_seed(),
                "printing circle".into(),
                "shared type".into(),
                2,
            )
            .await
            .unwrap();
        service
            .join(founder.to_seed(), "mark".into(), 3)
            .await
            .unwrap();
        let first = service.checkpoint(founder.to_seed(), 10).await.unwrap();

        let mut rotated = ConstitutionRules::founder_only(founder.public_key().to_bytes());
        rotated.checkpoint_signers.clear();
        rotated
            .checkpoint_signers
            .insert(successor.public_key().to_bytes());
        service.amend(founder.to_seed(), rotated, 11).await.unwrap();
        assert!(matches!(
            service.checkpoint(founder.to_seed(), 12).await,
            Err(MootError::Store(MootStoreError::Process(_)))
        ));
        let second = service.checkpoint(successor.to_seed(), 13).await.unwrap();
        assert_eq!(
            second
                .snapshot
                .checkpoint
                .as_ref()
                .unwrap()
                .previous_checkpoint,
            Some(first.operation)
        );

        service.prune_current(founder.to_seed(), 14).await.unwrap();
        let snapshot = service.snapshot().await.unwrap();
        assert_eq!(snapshot.roster.declaration.unwrap().name, "printing circle");
        assert_eq!(snapshot.roster.members.len(), 1);
        assert_eq!(snapshot.checkpoint.unwrap().operation, second.operation);
    }

    #[tokio::test]
    async fn durable_service_reopens_both_governance_and_roster() {
        let directory = tempfile::tempdir().unwrap();
        let founder = keypair(3);
        let founder_id = founder.public_key().to_bytes();
        let service = MootFile::open(directory.path(), ID, founder_id, retention())
            .await
            .unwrap();
        service
            .found(
                founder.to_seed(),
                None,
                None,
                ConstitutionRules::founder_only(founder_id),
                1,
            )
            .await
            .unwrap();
        service
            .join(founder.to_seed(), "mark".into(), 2)
            .await
            .unwrap();
        drop(service);

        let reopened = MootFile::open(directory.path(), ID, founder_id, retention())
            .await
            .unwrap();
        assert_eq!(reopened.snapshot().await.unwrap().roster.members.len(), 1);
    }
}