gemot 0.1.1

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
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
//! Muniment-backed constitution operation store.

use std::collections::BTreeMap;
use std::path::Path;

use muniment::{Backend, MemoryBackend, RedbBackend, StoreError};
use p2panda_core::{Operation, SigningKey, Topic, VerifyingKey};
use p2panda_store::logs::LogStore;
use p2panda_store::topics::TopicStore;
use proofs::Digest;
use stickleback::{
    Admission, MunimentStore, OperationPolicy, OperationProcessor, ProcessError, Reject,
    StoreTarget,
};

use super::wire::{ConstitutionExt, from_operation, verify};
use super::{
    Constitution, ConstitutionError, ConstitutionEvent, ConstitutionRules, GovernedAction,
    authorize_governed, to_operation_seed,
};

const LOG_ID: u64 = 0;

/// Constitution store or governance rejection.
#[derive(Debug, thiserror::Error)]
pub enum ConstitutionStoreError {
    /// Shared backend failure.
    #[error(transparent)]
    Store(#[from] StoreError),
    /// Shared processor rejection.
    #[error(transparent)]
    Process(#[from] ProcessError),
    /// Signed event was malformed or invalid under the current fold.
    #[error(transparent)]
    Constitution(#[from] ConstitutionError),
    /// The Moot has not accepted genesis.
    #[error("constitution is not founded")]
    NotFounded,
    /// More than one independently valid founder genesis is present.
    #[error("constitution store contains conflicting founder genesis operations")]
    ConflictingFounders,
}

#[derive(Clone, Copy)]
struct ConstitutionPolicy {
    moot_id: [u8; 32],
    founder: [u8; 32],
}

impl OperationPolicy<ConstitutionExt> for ConstitutionPolicy {
    type LogId = u64;

    fn admit(
        &self,
        operation: &Operation<ConstitutionExt>,
    ) -> Result<Admission<Self::LogId>, Reject> {
        if operation.header.extensions.moot_id != self.moot_id {
            return Err(Reject::new(
                "wrong-moot",
                "constitution operation addresses another moot",
            ));
        }
        let event = from_operation(operation).map_err(|_| {
            Reject::new(
                "invalid-constitution-event",
                "operation body is not a constitution event",
            )
        })?;
        if !event.rules_are_bound() {
            return Err(Reject::new(
                "invalid-rules-digest",
                "constitution rules do not match their digest",
            ));
        }
        let author = *operation.header.verifying_key.as_bytes();
        match event {
            ConstitutionEvent::Genesis {
                moot_id, founder, ..
            } if moot_id == self.moot_id && founder == self.founder && author == self.founder => {}
            // Amendment authority is evaluated against the prior accepted
            // constitution in `accept`. The processor must retain individual
            // quorum signatures before their threshold is met.
            ConstitutionEvent::Amended { .. } => {}
            ConstitutionEvent::Genesis { .. } => {
                return Err(Reject::new(
                    "wrong-founder",
                    "genesis does not bind the Moot founder",
                ));
            }
        }
        Ok(Admission::keep(StoreTarget::new(
            Topic::from(self.moot_id),
            LOG_ID,
        )))
    }
}

/// One Moot's constitution log over a shared backend.
#[derive(Clone)]
pub struct ConstitutionStore<B> {
    moot_id: [u8; 32],
    founder: [u8; 32],
    store: MunimentStore<B, ConstitutionExt>,
}

/// Durable redb constitution store.
pub type ConstitutionFileStore = ConstitutionStore<RedbBackend>;

impl ConstitutionStore<MemoryBackend> {
    /// Create an ephemeral store rooted in the Moot declaration's founder.
    pub fn in_memory(moot_id: [u8; 32], founder: [u8; 32]) -> Self {
        Self {
            moot_id,
            founder,
            store: MunimentStore::new(MemoryBackend::new()),
        }
    }
}

impl ConstitutionStore<RedbBackend> {
    /// Open durable constitutional state for one declared Moot.
    pub fn open(
        path: impl AsRef<Path>,
        moot_id: [u8; 32],
        founder: [u8; 32],
    ) -> Result<Self, ConstitutionStoreError> {
        Ok(Self {
            moot_id,
            founder,
            store: MunimentStore::new(RedbBackend::open(path)?),
        })
    }

    /// Open durable constitutional state by discovering the founder from the
    /// retained, signed genesis operation.
    ///
    /// This is the restart path for consumers which retain only the Moot id.
    /// The discovered key is accepted only when the genesis operation verifies,
    /// addresses `moot_id`, names the same founder as its signer, and is the
    /// sole valid founder claim in the retained topic.
    pub async fn open_existing(
        path: impl AsRef<Path>,
        moot_id: [u8; 32],
    ) -> Result<Self, ConstitutionStoreError> {
        if !path.as_ref().is_file() {
            return Err(ConstitutionStoreError::NotFounded);
        }
        let store = MunimentStore::new(RedbBackend::open(path)?);
        let probe = Self {
            moot_id,
            founder: [0; 32],
            store,
        };
        let mut founders = std::collections::BTreeSet::new();
        for operation in probe.operations().await? {
            if !verify(&operation) || operation.header.extensions.moot_id != moot_id {
                continue;
            }
            let Ok(ConstitutionEvent::Genesis {
                moot_id: event_moot,
                founder,
                ..
            }) = from_operation(&operation)
            else {
                continue;
            };
            if event_moot == moot_id && operation.header.verifying_key.as_bytes() == &founder {
                founders.insert(founder);
            }
        }
        let founder = match founders.len() {
            0 => return Err(ConstitutionStoreError::NotFounded),
            1 => *founders
                .first()
                .expect("a one-element founder set has a first element"),
            _ => return Err(ConstitutionStoreError::ConflictingFounders),
        };
        let service = Self { founder, ..probe };
        if service.constitution().await?.is_none() {
            return Err(ConstitutionStoreError::NotFounded);
        }
        Ok(service)
    }
}

impl<B: Backend + Clone> ConstitutionStore<B> {
    pub(crate) fn moot_id(&self) -> [u8; 32] {
        self.moot_id
    }

    pub(crate) fn founder(&self) -> [u8; 32] {
        self.founder
    }

    /// Shared LogSync store surface.
    pub fn sync_store(&self) -> MunimentStore<B, ConstitutionExt> {
        self.store.clone()
    }

    /// Admit a signed operation after governance preflight.
    pub async fn accept(
        &self,
        operation: &Operation<ConstitutionExt>,
    ) -> Result<bool, ConstitutionStoreError> {
        if self.store.has_operation(&operation.hash).await? {
            return Ok(false);
        }
        let event = from_operation(operation).map_err(|_| ConstitutionError::Malformed)?;
        let current = self.constitution().await?;
        match (&current, &event) {
            (None, ConstitutionEvent::Genesis { .. }) => {}
            (None, ConstitutionEvent::Amended { .. }) => {
                return Err(ConstitutionStoreError::NotFounded);
            }
            (Some(_), ConstitutionEvent::Genesis { .. }) => {
                return Err(ConstitutionError::AlreadyFounded.into());
            }
            (Some(state), ConstitutionEvent::Amended { previous, .. }) => {
                if *previous != state.revision {
                    return Err(ConstitutionError::StaleRevision.into());
                }
                let actor = *operation.header.verifying_key.as_bytes();
                if !authorize_governed(GovernedAction::AmendConstitution, actor, state) {
                    return Err(ConstitutionError::Unauthorized.into());
                }
            }
        }
        let processor = OperationProcessor::new(
            self.store.clone(),
            ConstitutionPolicy {
                moot_id: self.moot_id,
                founder: self.founder,
            },
        );
        Ok(processor.process(operation).await?.inserted())
    }

    /// Fold every retained operation into the accepted current law.
    pub async fn constitution(&self) -> Result<Option<Constitution>, ConstitutionStoreError> {
        let operations = self.operations().await?;
        Ok(Constitution::fold(
            self.moot_id,
            self.founder,
            operations.iter(),
        ))
    }

    /// Author genesis with the configured founder key.
    pub async fn author_genesis(
        &self,
        signing_seed: [u8; 32],
        parent_constitution: Option<Digest>,
        divergence_point: Option<Digest>,
        rules: ConstitutionRules,
        at_ms: u64,
    ) -> Result<Operation<ConstitutionExt>, ConstitutionStoreError> {
        if self.constitution().await?.is_some() {
            return Err(ConstitutionError::AlreadyFounded.into());
        }
        let author = *SigningKey::from_bytes(&signing_seed)
            .verifying_key()
            .as_bytes();
        if author != self.founder {
            return Err(ConstitutionError::Unauthorized.into());
        }
        let event = ConstitutionEvent::genesis(
            self.moot_id,
            self.founder,
            parent_constitution,
            divergence_point,
            rules,
            at_ms,
        );
        self.author_event(signing_seed, &event).await
    }

    /// Author the next amendment under the prior accepted rule.
    pub async fn author_amendment(
        &self,
        signing_seed: [u8; 32],
        rules: ConstitutionRules,
        at_ms: u64,
    ) -> Result<Operation<ConstitutionExt>, ConstitutionStoreError> {
        let state = self
            .constitution()
            .await?
            .ok_or(ConstitutionStoreError::NotFounded)?;
        let actor = *SigningKey::from_bytes(&signing_seed)
            .verifying_key()
            .as_bytes();
        if !authorize_governed(GovernedAction::AmendConstitution, actor, &state) {
            return Err(ConstitutionError::Unauthorized.into());
        }
        let event = ConstitutionEvent::amended(state.revision, rules, at_ms);
        self.author_event(signing_seed, &event).await
    }

    async fn author_event(
        &self,
        signing_seed: [u8; 32],
        event: &ConstitutionEvent,
    ) -> Result<Operation<ConstitutionExt>, ConstitutionStoreError> {
        let author = SigningKey::from_bytes(&signing_seed).verifying_key();
        let (seq_num, backlink) = match self.latest(&author).await? {
            Some(previous) => (previous.header.seq_num + 1, Some(*previous.hash.as_bytes())),
            None => (0, None),
        };
        let operation = to_operation_seed(signing_seed, self.moot_id, event, seq_num, backlink);
        self.accept(&operation).await?;
        Ok(operation)
    }

    async fn latest(
        &self,
        author: &VerifyingKey,
    ) -> Result<Option<Operation<ConstitutionExt>>, ConstitutionStoreError> {
        Ok(self.store.get_latest_entry(author, &LOG_ID).await?)
    }

    /// Retained accepted-operation corpus. Aggregate carriers use this to bind
    /// checkpoint authority evidence beside Moot object records.
    pub(crate) async fn operations(
        &self,
    ) -> Result<Vec<Operation<ConstitutionExt>>, ConstitutionStoreError> {
        let logs: BTreeMap<VerifyingKey, Vec<u64>> =
            self.store.resolve(&Topic::from(self.moot_id)).await?;
        let mut operations = Vec::new();
        for (author, log_ids) in logs {
            for log_id in log_ids {
                if let Some(entries) = self
                    .store
                    .get_log_entries(&author, &log_id, None, None)
                    .await?
                {
                    operations.extend(entries.into_iter().map(|(operation, _)| operation));
                }
            }
        }
        Ok(operations)
    }
}

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

    const MOOT: [u8; 32] = [0x63; 32];

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

    #[tokio::test]
    async fn founder_amends_and_two_stores_converge() {
        let founder = keypair(1);
        let founder_id = founder.public_key().to_bytes();
        let first = ConstitutionStore::in_memory(MOOT, founder_id);
        let genesis = first
            .author_genesis(
                founder.to_seed(),
                None,
                None,
                ConstitutionRules::founder_only(founder_id),
                1,
            )
            .await
            .unwrap();
        let mut next_rules = ConstitutionRules::founder_only(founder_id);
        next_rules.checkpoint_signers.insert([9; 32]);
        let amendment = first
            .author_amendment(founder.to_seed(), next_rules.clone(), 2)
            .await
            .unwrap();

        let second = ConstitutionStore::in_memory(MOOT, founder_id);
        second.accept(&genesis).await.unwrap();
        second.accept(&amendment).await.unwrap();
        let first_state = first.constitution().await.unwrap().unwrap();
        let second_state = second.constitution().await.unwrap().unwrap();
        assert_eq!(first_state, second_state);
        assert_eq!(first_state.rules, next_rules);

        let authority = GovernedCheckpointAuthority::from_state(&first_state);
        assert!(authority.permits_checkpoint([9; 32], &first_state.revision));
        assert!(!authority.permits_checkpoint([8; 32], &first_state.revision));
    }

    #[tokio::test]
    async fn durable_restart_discovers_founder_from_signed_genesis() {
        let directory = tempfile::tempdir().unwrap();
        let path = directory.path().join("constitution.redb");
        let founder = keypair(7);
        let founder_id = founder.public_key().to_bytes();
        let first = ConstitutionStore::open(&path, MOOT, founder_id).unwrap();
        first
            .author_genesis(
                founder.to_seed(),
                None,
                None,
                ConstitutionRules::founder_only(founder_id),
                1,
            )
            .await
            .unwrap();
        drop(first);

        let reopened = ConstitutionStore::open_existing(&path, MOOT).await.unwrap();
        assert_eq!(reopened.founder(), founder_id);
        assert_eq!(
            reopened.constitution().await.unwrap().unwrap().founder,
            founder_id
        );
    }

    #[tokio::test]
    async fn non_founder_amendment_is_rejected_before_mutation() {
        let founder = keypair(1);
        let intruder = keypair(2);
        let founder_id = founder.public_key().to_bytes();
        let store = ConstitutionStore::in_memory(MOOT, founder_id);
        store
            .author_genesis(
                founder.to_seed(),
                None,
                None,
                ConstitutionRules::founder_only(founder_id),
                1,
            )
            .await
            .unwrap();
        let state = store.constitution().await.unwrap().unwrap();
        let event = ConstitutionEvent::amended(
            state.revision.clone(),
            ConstitutionRules::founder_only(founder_id),
            2,
        );
        let operation = to_operation_seed(intruder.to_seed(), MOOT, &event, 0, None);
        assert!(store.accept(&operation).await.is_err());
        assert_eq!(store.constitution().await.unwrap().unwrap(), state);
    }
}