use std::io::{Read, Write};
use std::path::Path;
use muniment::{Backend, MemoryBackend, RedbBackend};
use p2panda_core::cbor::{decode_cbor, encode_cbor};
use proofs::Digest;
use serde::{Deserialize, Serialize};
use stickleback::{
DropExportBudget, DropExportDecision, DropExportProfile, DropExportSelector, DropId,
DropImportReport, DropLimits, DropProtector, DropRecord, DropWriteReceipt, EvidenceKind,
MunimentStore, NativeDropError, decode_operation_record, export_topic_operations,
read_plain_drop, read_protected_drop, write_plain_drop, write_protected_drop,
};
use super::constitution::{
ConstitutionExt, ConstitutionRules, MootGovernance, MootGovernanceError, MootGovernanceSnapshot,
};
use super::delegation::{
MootDelegationProjection, MootDelegationStore, MootDelegationStoreError, MootDelegations,
MootScopeKeyEpoch,
};
use super::group::store::{MootGroupStore, MootGroupStoreError};
use super::group::wire::MootGroupExt;
use super::group::{MootGroup, MootGroupSnapshot, MootMembershipAction};
use super::MootId;
use super::records::{
AvailabilityPolicy, ErasurePolicy, FaunaEntry, MootEvent, MootRetentionPolicy, MootRoster,
MootStore, MootStoreError, PolicyRevision,
};
use super::tessera::{
GateDecision, TesseraEvent, TesseraExt, TesseraFacts, TesseraFileStore, TesseraStore,
TesseraStoreError, authorize,
};
use super::typed_authorization::MootAuthority;
const CONSTITUTION_EVIDENCE_VERSION: u16 = 1;
const DELEGATION_EVIDENCE_VERSION: u16 = 1;
const DOMAIN_EVIDENCE_VERSION: u16 = 1;
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct MootDropSelector {
pub checkpoint_priority: u32,
pub roster_priority: u32,
pub fauna_priority: u32,
}
impl Default for MootDropSelector {
fn default() -> Self {
Self {
checkpoint_priority: 100,
roster_priority: 80,
fauna_priority: 40,
}
}
}
impl DropExportSelector<super::MootExt> for MootDropSelector {
fn select(&self, operation: &p2panda_core::Operation<super::MootExt>) -> DropExportDecision {
let priority = match super::from_operation(operation) {
Ok((_, MootEvent::RetentionCheckpoint { .. })) => self.checkpoint_priority,
Ok((_, MootEvent::Declared { .. } | MootEvent::Joined { .. })) => self.roster_priority,
Ok((_, MootEvent::Shared { .. } | MootEvent::HistoryPruned { .. })) => {
self.fauna_priority
}
Err(_) => return DropExportDecision::Omit,
};
DropExportDecision::Full { priority }
}
}
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
struct ConstitutionEvidence {
version: u16,
operations: Vec<DropRecord>,
}
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
struct DelegationEvidence {
version: u16,
operations: Vec<DropRecord>,
}
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
struct DomainEvidence {
version: u16,
membership_operations: Vec<DropRecord>,
tessera_operations: Vec<DropRecord>,
}
#[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,
checkpoint_authority_history: Vec<super::GovernedCheckpointAuthority>,
) -> MootRetentionPolicy {
MootRetentionPolicy {
revision: self.revision.clone(),
checkpoint_authority,
checkpoint_authority_history,
availability: self.availability,
erasure: self.erasure,
}
}
}
#[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,
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct MootSnapshot {
pub moot_id: MootId,
pub governance: MootGovernanceSnapshot,
pub membership: MootGroupSnapshot,
pub roster: MootRoster,
pub checkpoint: Option<MootCheckpointSnapshot>,
pub delegated_certificates: usize,
pub tessera_operations: usize,
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct MootAuthorizationRequest {
pub subject: [u8; 32],
pub capability_path: String,
pub at_ms: u64,
}
#[derive(Clone, Debug, Default)]
pub struct MootAuthorizationInputs {
pub capability_covers: bool,
pub facts: TesseraFacts,
}
pub trait MootAuthorizationProvider {
fn inputs(&self, request: &MootAuthorizationRequest) -> MootAuthorizationInputs;
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct MootCommandReceipt {
pub operation: [u8; 32],
pub lane: MootLane,
pub snapshot: MootSnapshot,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum MootLane {
Membership,
Objects,
Tessera,
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum MootOutboundOperation {
Membership(p2panda_core::Operation<MootGroupExt>),
Object(p2panda_core::Operation<super::MootExt>),
Tessera(p2panda_core::Operation<TesseraExt>),
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct MootDropImportReceipt {
pub import: DropImportReport,
pub constitution_operations: u64,
pub delegation_operations: u64,
pub membership_operations: u64,
pub tessera_operations: u64,
pub snapshot: MootSnapshot,
}
#[derive(Debug, thiserror::Error)]
pub enum MootError {
#[error(transparent)]
Governance(#[from] MootGovernanceError),
#[error(transparent)]
Store(#[from] MootStoreError),
#[error(transparent)]
Tessera(#[from] TesseraStoreError),
#[error(transparent)]
Delegation(#[from] MootDelegationStoreError),
#[error(transparent)]
Membership(#[from] MootGroupStoreError),
#[error("moot has no accepted retention checkpoint")]
CheckpointMissing,
#[error("moot storage directory: {0}")]
Io(#[from] std::io::Error),
#[error(transparent)]
Drop(#[from] NativeDropError),
#[error("Moot drop needs full operation bodies")]
HeaderOnlyDrop,
#[error("Moot drop selection omitted {0} retained records; increase its byte budget")]
IncompleteDropBudget(u64),
#[error("Moot drop is missing critical constitution authority evidence")]
ConstitutionEvidenceMissing,
#[error("Moot drop carries malformed constitution authority evidence")]
ConstitutionEvidenceMalformed,
#[error("Moot drop carries malformed delegation authority evidence")]
DelegationEvidenceMalformed,
#[error("Moot drop carries malformed auxiliary domain evidence")]
DomainEvidenceMalformed,
#[error("authored operation is absent from its retained lane")]
OutboundMissing,
}
#[derive(Clone)]
pub struct Moot<B> {
moot_id: MootId,
governance: MootGovernance<B>,
objects: MootStore<B>,
tessera: TesseraStore<B>,
delegations: MootDelegationStore<B>,
membership: MootGroupStore<B>,
retention: MootRetentionSettings,
}
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(),
tessera: TesseraStore::in_memory(),
delegations: MootDelegationStore::in_memory(moot_id.0),
membership: MootGroupStore::in_memory(moot_id.0),
retention,
}
}
}
impl Moot<RedbBackend> {
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"))?,
tessera: TesseraFileStore::open(directory.as_ref().join("tessera.redb"))?,
delegations: super::delegation::MootDelegationFileStore::open(
directory.as_ref().join("delegations.redb"),
moot_id.0,
)?,
membership: super::group::store::MootGroupFileStore::open(
directory.as_ref().join("membership.redb"),
moot_id.0,
)?,
retention,
};
match service.governance.snapshot().await {
Ok(_) => service.refresh_retention_authority().await?,
Err(MootGovernanceError::NotFounded) => {}
Err(error) => return Err(error.into()),
}
Ok(service)
}
pub async fn open_existing(
directory: impl AsRef<Path>,
moot_id: MootId,
retention: MootRetentionSettings,
) -> Result<Self, MootError> {
let service = Self {
moot_id,
governance: MootGovernance::open_existing(
directory.as_ref().join("constitution.redb"),
moot_id.0,
)
.await?,
objects: MootStore::at_path(directory.as_ref().join("objects.redb"))?,
tessera: TesseraFileStore::open(directory.as_ref().join("tessera.redb"))?,
delegations: super::delegation::MootDelegationFileStore::open(
directory.as_ref().join("delegations.redb"),
moot_id.0,
)?,
membership: super::group::store::MootGroupFileStore::open(
directory.as_ref().join("membership.redb"),
moot_id.0,
)?,
retention,
};
service.refresh_retention_authority().await?;
Ok(service)
}
}
impl<B: Backend + Clone> Moot<B> {
pub fn moot_id(&self) -> MootId {
self.moot_id
}
pub fn constitution_store(&self) -> MunimentStore<B, ConstitutionExt> {
self.governance.sync_store()
}
pub fn object_store(&self) -> &MootStore<B> {
&self.objects
}
pub fn tessera_store(&self) -> &TesseraStore<B> {
&self.tessera
}
pub fn delegation_store(&self) -> &MootDelegationStore<B> {
&self.delegations
}
pub fn governance(&self) -> &MootGovernance<B> {
&self.governance
}
pub fn membership_store(&self) -> &MootGroupStore<B> {
&self.membership
}
pub async fn membership(&self) -> Result<MootGroup, MootError> {
Ok(self.membership.group().await?)
}
async fn refresh_retention_authority(&self) -> Result<(), MootError> {
let authority = self.governance.checkpoint_authority().await?;
let history = self.governance.checkpoint_authority_history().await?;
self.objects
.set_retention_policy(Some(self.retention.resolve(authority, history)));
Ok(())
}
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
}
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 authorize<P: MootAuthorizationProvider>(
&self,
provider: &P,
request: &MootAuthorizationRequest,
) -> Result<GateDecision, MootError> {
let policy = self.governance.snapshot().await?.rules.admission;
let inputs = provider.inputs(request);
Ok(authorize(
&policy,
inputs.capability_covers,
&inputs.facts,
request.at_ms,
))
}
pub async fn authorize_constitution_grant<P: MootAuthorizationProvider>(
&self,
provider: &P,
request: &MootAuthorizationRequest,
) -> Result<GateDecision, MootError> {
let governance = self.governance.snapshot().await?;
let inputs = provider.inputs(request);
let grant_covers =
governance
.rules
.grant_covers(request.subject, &request.capability_path, request.at_ms);
Ok(authorize(
&governance.rules.admission,
grant_covers && inputs.capability_covers,
&inputs.facts,
request.at_ms,
))
}
pub async fn delegations(&self) -> Result<MootDelegations, MootError> {
let rules = self.governance.snapshot().await?.rules;
Ok(self.delegations.delegations(&rules).await?)
}
pub async fn delegation_projections(
&self,
at_ms: u64,
) -> Result<Vec<MootDelegationProjection>, MootError> {
let rules = self.governance.snapshot().await?.rules;
Ok(self
.delegations
.delegations(&rules)
.await?
.projections(self.moot_id.0, &rules, at_ms))
}
pub async fn delegation_scope_key_epochs(&self) -> Result<Vec<MootScopeKeyEpoch>, MootError> {
Ok(self.delegations().await?.scope_key_epochs())
}
pub async fn authorize_current_delegated<P: MootAuthorizationProvider>(
&self,
provider: &P,
request: &MootAuthorizationRequest,
) -> Result<GateDecision, MootError> {
let governance = self.governance.snapshot().await?;
let delegations = self.delegations.delegations(&governance.rules).await?;
self.authorize_delegated(&delegations, provider, request)
.await
}
pub async fn authorize_delegated<P: MootAuthorizationProvider>(
&self,
delegations: &super::MootDelegations,
provider: &P,
request: &MootAuthorizationRequest,
) -> Result<GateDecision, MootError> {
let governance = self.governance.snapshot().await?;
let inputs = provider.inputs(request);
let grant_covers = delegations.covers(
self.moot_id.0,
&governance.rules,
request.subject,
&request.capability_path,
request.at_ms,
);
Ok(authorize(
&governance.rules.admission,
grant_covers && inputs.capability_covers,
&inputs.facts,
request.at_ms,
))
}
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(),
lane: MootLane::Objects,
snapshot: self.snapshot().await?,
})
}
pub async fn update_membership(
&self,
actor_seed: [u8; 32],
action: MootMembershipAction,
) -> Result<MootCommandReceipt, MootError> {
self.governance.snapshot().await?;
let operation = self.membership.author_seed(actor_seed, action).await?;
Ok(MootCommandReceipt {
operation: *operation.hash.as_bytes(),
lane: MootLane::Membership,
snapshot: self.snapshot().await?,
})
}
pub async fn update_membership_for_identity<P: identity::IdentityProvider + ?Sized>(
&self,
identity: &P,
action: MootMembershipAction,
) -> Result<MootCommandReceipt, MootError> {
self.governance.snapshot().await?;
let operation = self
.membership
.author_for_identity(identity, action)
.await?;
Ok(MootCommandReceipt {
operation: *operation.hash.as_bytes(),
lane: MootLane::Membership,
snapshot: self.snapshot().await?,
})
}
pub async fn record_tessera(
&self,
actor_seed: [u8; 32],
event: TesseraEvent,
) -> Result<MootCommandReceipt, MootError> {
self.governance.snapshot().await?;
let operation = self
.tessera
.author_seed(actor_seed, self.moot_id.0, &event)
.await?;
Ok(MootCommandReceipt {
operation: *operation.hash.as_bytes(),
lane: MootLane::Tessera,
snapshot: self.snapshot().await?,
})
}
pub async fn outbound(
&self,
receipt: &MootCommandReceipt,
) -> Result<MootOutboundOperation, MootError> {
let hash = p2panda_core::Hash::from_bytes(receipt.operation);
match receipt.lane {
MootLane::Membership => self
.membership
.get(&hash)
.await?
.map(MootOutboundOperation::Membership)
.ok_or(MootError::OutboundMissing),
MootLane::Objects => self
.objects
.operation(&hash)
.await?
.map(MootOutboundOperation::Object)
.ok_or(MootError::OutboundMissing),
MootLane::Tessera => self
.tessera
.get(&hash)
.await?
.map(MootOutboundOperation::Tessera)
.ok_or(MootError::OutboundMissing),
}
}
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
}
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(),
lane: MootLane::Objects,
snapshot: self.snapshot().await?,
})
}
async fn aggregate_drop_records(
&self,
selector: &MootDropSelector,
budget: DropExportBudget,
) -> Result<Vec<DropRecord>, MootError> {
let evidence = ConstitutionEvidence {
version: CONSTITUTION_EVIDENCE_VERSION,
operations: self.governance.drop_records().await?,
};
let evidence_bytes =
encode_cbor(&evidence).map_err(|_| MootError::ConstitutionEvidenceMalformed)?;
let mut records = vec![DropRecord::Evidence {
kind: EvidenceKind::CheckpointAuthorization,
subject: self.moot_id.0,
bytes: evidence_bytes,
critical: true,
}];
let delegation = DelegationEvidence {
version: DELEGATION_EVIDENCE_VERSION,
operations: self.delegations.drop_records().await?,
};
let delegation_bytes =
encode_cbor(&delegation).map_err(|_| MootError::DelegationEvidenceMalformed)?;
records.push(DropRecord::Evidence {
kind: EvidenceKind::CapabilityChain,
subject: self.moot_id.0,
bytes: delegation_bytes,
critical: true,
});
let domains = DomainEvidence {
version: DOMAIN_EVIDENCE_VERSION,
membership_operations: self.membership.drop_records().await?,
tessera_operations: export_topic_operations::<B, TesseraExt, u64>(
&self.tessera.sync_store(),
&p2panda_core::Topic::from(self.moot_id.0),
DropExportProfile::default(),
)
.await
.map_err(|_| MootError::DomainEvidenceMalformed)?,
};
let domain_bytes = encode_cbor(&domains).map_err(|_| MootError::DomainEvidenceMalformed)?;
records.push(DropRecord::Evidence {
kind: EvidenceKind::DomainOperations,
subject: self.moot_id.0,
bytes: domain_bytes,
critical: true,
});
let (objects, selection) = self
.objects
.export_selected_drop_records(self.moot_id.0, selector, budget)
.await?;
if selection.budget_omitted != 0 || selection.policy_omitted != 0 {
return Err(MootError::IncompleteDropBudget(
selection.budget_omitted + selection.policy_omitted,
));
}
records.extend(objects);
Ok(records)
}
fn constitution_evidence(&self, records: &[DropRecord]) -> Result<Vec<DropRecord>, MootError> {
let mut found = None;
for record in records {
let DropRecord::Evidence {
kind: EvidenceKind::CheckpointAuthorization,
subject,
bytes,
critical: true,
} = record
else {
continue;
};
if *subject != self.moot_id.0 || found.is_some() {
return Err(MootError::ConstitutionEvidenceMalformed);
}
let evidence: ConstitutionEvidence =
decode_cbor(&bytes[..]).map_err(|_| MootError::ConstitutionEvidenceMalformed)?;
if evidence.version != CONSTITUTION_EVIDENCE_VERSION
|| encode_cbor(&evidence).ok().as_deref() != Some(bytes.as_slice())
{
return Err(MootError::ConstitutionEvidenceMalformed);
}
found = Some(evidence.operations);
}
found.ok_or(MootError::ConstitutionEvidenceMissing)
}
fn delegation_evidence(&self, records: &[DropRecord]) -> Result<Vec<DropRecord>, MootError> {
let mut found = None;
for record in records {
let DropRecord::Evidence {
kind: EvidenceKind::CapabilityChain,
subject,
bytes,
critical: true,
} = record
else {
continue;
};
if *subject != self.moot_id.0 || found.is_some() {
return Err(MootError::DelegationEvidenceMalformed);
}
let evidence: DelegationEvidence =
decode_cbor(&bytes[..]).map_err(|_| MootError::DelegationEvidenceMalformed)?;
if evidence.version != DELEGATION_EVIDENCE_VERSION
|| encode_cbor(&evidence).ok().as_deref() != Some(bytes.as_slice())
{
return Err(MootError::DelegationEvidenceMalformed);
}
found = Some(evidence.operations);
}
Ok(found.unwrap_or_default())
}
fn domain_evidence(&self, records: &[DropRecord]) -> Result<DomainEvidence, MootError> {
let mut found = None;
for record in records {
let DropRecord::Evidence {
kind: EvidenceKind::DomainOperations,
subject,
bytes,
critical: true,
} = record
else {
continue;
};
if *subject != self.moot_id.0 || found.is_some() {
return Err(MootError::DomainEvidenceMalformed);
}
let evidence: DomainEvidence =
decode_cbor(&bytes[..]).map_err(|_| MootError::DomainEvidenceMalformed)?;
if evidence.version != DOMAIN_EVIDENCE_VERSION
|| encode_cbor(&evidence).ok().as_deref() != Some(bytes.as_slice())
{
return Err(MootError::DomainEvidenceMalformed);
}
found = Some(evidence);
}
Ok(found.unwrap_or(DomainEvidence {
version: DOMAIN_EVIDENCE_VERSION,
membership_operations: Vec::new(),
tessera_operations: Vec::new(),
}))
}
async fn accept_tessera_drop_records(&self, records: &[DropRecord]) -> Result<u64, MootError> {
let mut accepted = 0;
for record in records {
let Some(operation) = decode_operation_record::<TesseraExt>(record)
.map_err(|_| MootError::DomainEvidenceMalformed)?
else {
continue;
};
if operation.body.is_none() {
return Err(MootError::DomainEvidenceMalformed);
}
accepted += u64::from(self.tessera.accept(self.moot_id.0, &operation).await?);
}
Ok(accepted)
}
async fn import_aggregate_records(
&self,
drop_id: DropId,
records: Vec<DropRecord>,
) -> Result<MootDropImportReceipt, MootError> {
let evidence = self.constitution_evidence(&records)?;
let constitution_operations = self.governance.accept_drop_records(&evidence).await?;
let delegation_evidence = self.delegation_evidence(&records)?;
let delegation_operations = self
.delegations
.accept_drop_records(&delegation_evidence)
.await?;
let domains = self.domain_evidence(&records)?;
let membership_operations = self
.membership
.accept_drop_records(&domains.membership_operations)
.await?;
let tessera_operations = self
.accept_tessera_drop_records(&domains.tessera_operations)
.await?;
self.refresh_retention_authority().await?;
let import = self
.objects
.import_drop_records(self.moot_id.0, drop_id, records)
.await?;
Ok(MootDropImportReceipt {
import,
constitution_operations,
delegation_operations,
membership_operations,
tessera_operations,
snapshot: self.snapshot().await?,
})
}
pub async fn export_plain_drop<W: Write>(
&self,
writer: &mut W,
profile: DropExportProfile,
limits: DropLimits,
) -> Result<DropWriteReceipt, MootError> {
if !profile.include_operation_bodies {
return Err(MootError::HeaderOnlyDrop);
}
let records = self
.aggregate_drop_records(&MootDropSelector::default(), DropExportBudget::default())
.await?;
Ok(write_plain_drop(writer, &records, limits)?)
}
pub async fn export_protected_drop<W: Write, D: DropProtector>(
&self,
writer: &mut W,
selector: &MootDropSelector,
budget: DropExportBudget,
limits: DropLimits,
protector: &D,
) -> Result<DropWriteReceipt, MootError> {
let records = self.aggregate_drop_records(selector, budget).await?;
Ok(write_protected_drop(writer, &records, limits, protector)?)
}
pub async fn import_plain_drop<R: Read>(
&self,
reader: R,
limits: DropLimits,
) -> Result<MootDropImportReceipt, MootError> {
let (read, records) = read_plain_drop(reader, limits)?;
self.import_aggregate_records(read.id, records).await
}
pub async fn import_protected_drop<R: Read, D: DropProtector>(
&self,
reader: R,
limits: DropLimits,
protector: &D,
) -> Result<MootDropImportReceipt, MootError> {
let (read, records) = read_protected_drop(reader, limits, protector)?;
self.import_aggregate_records(read.id, records).await
}
pub async fn authorized_fauna(&self, at_ms: u64) -> Result<Vec<FaunaEntry>, MootError> {
let rules = self.governance.snapshot().await?.rules;
let delegations = self.delegations.delegations(&rules).await?;
let roster = self.objects.roster(self.moot_id.0).await?;
let authority = MootAuthority {
delegations: &delegations,
rules: &rules,
moot_id: self.moot_id.0,
now_ms: at_ms,
};
Ok(roster
.authorized_fauna(&authority)
.into_iter()
.cloned()
.collect())
}
pub async fn snapshot(&self) -> Result<MootSnapshot, MootError> {
let governance = self.governance.snapshot().await?;
let membership = self.membership.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,
});
let delegated_certificates = self
.delegations
.delegations(&governance.rules)
.await?
.certificate_count();
let tessera_operations = self.tessera.len().await?;
Ok(MootSnapshot {
moot_id: self.moot_id,
governance,
membership,
roster,
checkpoint,
delegated_certificates,
tessera_operations,
})
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::moot::constitution::CapabilityGrant;
use crate::moot::delegation::{MOOT_ACT_ACTION, MOOT_DELEGATION_DOMAIN};
use crate::moot::tessera::{
ChainRoot, DenyReason, GateConfig, GateDecision, Policy, TesseraEvent, TesseraFacts,
};
use crate::moot::{
KeepBound, MootAccessLevel, MootMember, MootMembershipAction, MootStoreError,
};
use identity::delegation::{
CapabilityScope, DelegationCertificate, DelegationParent, DelegationRevocation,
SignedDelegationCertificate, SignedDelegationRevocation, delegation_signing_salt,
};
use identity::{IdentityProvider, InMemoryProvider};
use std::io::Cursor;
use stickleback::NativeDropError;
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,
},
}
}
struct Access {
capability_covers: bool,
facts: TesseraFacts,
}
impl MootAuthorizationProvider for Access {
fn inputs(&self, _: &MootAuthorizationRequest) -> MootAuthorizationInputs {
MootAuthorizationInputs {
capability_covers: self.capability_covers,
facts: self.facts.clone(),
}
}
}
struct TestProtector;
impl DropProtector for TestProtector {
fn suite_id(&self) -> u16 {
77
}
fn protect(&self, plaintext: &[u8], aad: &[u8]) -> Result<Vec<u8>, NativeDropError> {
Ok(plaintext
.iter()
.enumerate()
.map(|(index, byte)| byte ^ aad[index % aad.len()])
.collect())
}
fn unprotect(
&self,
protected: &[u8],
aad: &[u8],
max_plaintext_bytes: u64,
) -> Result<Vec<u8>, NativeDropError> {
if protected.len() as u64 > max_plaintext_bytes {
return Err(NativeDropError::Limit {
limit: "test plaintext bytes",
actual: protected.len() as u64,
maximum: max_plaintext_bytes,
});
}
self.protect(protected, aad)
}
}
#[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 signed_admission_rule_uses_the_injected_membership_and_capability_inputs() {
let founder = keypair(8);
let founder_id = founder.public_key().to_bytes();
let service = Moot::in_memory(ID, founder_id, retention());
let mut rules = ConstitutionRules::founder_only(founder_id);
rules.admission = Policy::MembersOnly {
rate_limit: 20,
rate_window_ms: 60_000,
};
service
.found(founder.to_seed(), None, None, rules, 1)
.await
.unwrap();
let request = MootAuthorizationRequest {
subject: [9; 32],
capability_path: "moot/fauna/write".into(),
at_ms: 10,
};
assert_eq!(
service
.authorize(
&Access {
capability_covers: false,
facts: TesseraFacts {
is_member: true,
..Default::default()
},
},
&request,
)
.await
.unwrap(),
GateDecision::Deny(DenyReason::NoCapability)
);
assert_eq!(
service
.authorize(
&Access {
capability_covers: true,
facts: TesseraFacts {
score: 1,
..Default::default()
},
},
&request,
)
.await
.unwrap(),
GateDecision::Deny(DenyReason::NotAMember)
);
assert_eq!(
service
.authorize(
&Access {
capability_covers: true,
facts: TesseraFacts {
is_member: true,
..Default::default()
},
},
&request,
)
.await
.unwrap(),
GateDecision::Allow
);
let mut amended = ConstitutionRules::founder_only(founder_id);
amended.admission = Policy::OpenWithFloor(GateConfig {
posting_threshold: 2,
rate_limit: 20,
rate_window_ms: 60_000,
});
service.amend(founder.to_seed(), amended, 11).await.unwrap();
assert_eq!(
service
.authorize(
&Access {
capability_covers: true,
facts: TesseraFacts {
score: 1,
is_member: true,
..Default::default()
},
},
&request,
)
.await
.unwrap(),
GateDecision::Deny(DenyReason::BelowThreshold)
);
}
#[tokio::test]
async fn constitutional_grants_narrow_live_capability_inputs_and_revoke_by_amendment() {
let founder = keypair(9);
let founder_id = founder.public_key().to_bytes();
let service = Moot::in_memory(ID, founder_id, retention());
let grant_id = [0xa9; 32];
let mut rules = ConstitutionRules::founder_only(founder_id);
rules.admission = Policy::MembersOnly {
rate_limit: 20,
rate_window_ms: 60_000,
};
rules.grant(CapabilityGrant {
id: grant_id,
subject: [9; 32],
path_prefix: "moot/fauna".into(),
not_before_ms: 5,
expires_at_ms: Some(20),
delegation_depth: 0,
});
service
.found(founder.to_seed(), None, None, rules.clone(), 1)
.await
.unwrap();
let member = Access {
capability_covers: true,
facts: TesseraFacts {
is_member: true,
..Default::default()
},
};
let request = MootAuthorizationRequest {
subject: [9; 32],
capability_path: "moot/fauna/write".into(),
at_ms: 10,
};
assert_eq!(
service
.authorize_constitution_grant(&member, &request)
.await
.unwrap(),
GateDecision::Allow
);
let sibling = MootAuthorizationRequest {
capability_path: "moot/faunarium/write".into(),
..request.clone()
};
assert_eq!(
service
.authorize_constitution_grant(&member, &sibling)
.await
.unwrap(),
GateDecision::Deny(DenyReason::NoCapability)
);
let expired = MootAuthorizationRequest {
at_ms: 21,
..request.clone()
};
assert_eq!(
service
.authorize_constitution_grant(&member, &expired)
.await
.unwrap(),
GateDecision::Deny(DenyReason::NoCapability)
);
rules.revoke_grant(&grant_id);
service.amend(founder.to_seed(), rules, 22).await.unwrap();
assert_eq!(
service
.authorize_constitution_grant(&member, &request)
.await
.unwrap(),
GateDecision::Deny(DenyReason::NoCapability)
);
}
#[tokio::test]
async fn delegated_grants_intersect_constitution_group_and_admission() {
let founder = keypair(10);
let founder_id = founder.public_key().to_bytes();
let root_holder = InMemoryProvider::from_seed([0x31; 32]);
let delegate = InMemoryProvider::from_seed([0x32; 32]);
let root_id = [0xb1; 32];
let service = Moot::in_memory(ID, founder_id, retention());
let mut rules = ConstitutionRules::founder_only(founder_id);
rules.admission = Policy::MembersOnly {
rate_limit: 20,
rate_window_ms: 60_000,
};
rules.grant(CapabilityGrant {
id: root_id,
subject: root_holder.master_public_key().to_bytes(),
path_prefix: "moot/fauna".into(),
not_before_ms: 5,
expires_at_ms: Some(100),
delegation_depth: 2,
});
service
.found(founder.to_seed(), None, None, rules.clone(), 1)
.await
.unwrap();
let scope = CapabilityScope {
domain: MOOT_DELEGATION_DOMAIN.into(),
resource: ID.0.to_vec(),
path_prefix: "moot/fauna/research".into(),
actions: [MOOT_ACT_ACTION.to_string()].into_iter().collect(),
};
let certificate = DelegationCertificate::new(
DelegationParent::Root(root_id),
root_holder.master_public_key().to_bytes(),
delegate.master_public_key().to_bytes(),
scope.clone(),
5,
10,
Some(90),
1,
[0x41; 32],
);
let delegation_key = root_holder
.derive_keypair(&delegation_signing_salt(&scope))
.unwrap();
service
.delegation_store()
.author_issue(
&delegation_key,
&rules,
SignedDelegationCertificate::issue(&root_holder, certificate).unwrap(),
)
.await
.unwrap();
assert_eq!(service.snapshot().await.unwrap().delegated_certificates, 1);
let request = MootAuthorizationRequest {
subject: delegate.master_public_key().to_bytes(),
capability_path: "moot/fauna/research/write".into(),
at_ms: 50,
};
let member = Access {
capability_covers: true,
facts: TesseraFacts {
is_member: true,
..Default::default()
},
};
assert_eq!(
service
.authorize_current_delegated(&member, &request)
.await
.unwrap(),
GateDecision::Allow
);
assert_eq!(
service
.authorize_current_delegated(
&Access {
capability_covers: false,
facts: member.facts.clone(),
},
&request,
)
.await
.unwrap(),
GateDecision::Deny(DenyReason::NoCapability)
);
rules.revoke_grant(&root_id);
service.amend(founder.to_seed(), rules, 101).await.unwrap();
assert_eq!(
service
.authorize_current_delegated(&member, &request)
.await
.unwrap(),
GateDecision::Deny(DenyReason::NoCapability)
);
}
#[tokio::test]
async fn native_drop_bootstraps_independent_delegation_authority() {
let founder = keypair(11);
let founder_id = founder.public_key().to_bytes();
let root_holder = InMemoryProvider::from_seed([0x51; 32]);
let delegate = InMemoryProvider::from_seed([0x52; 32]);
let root_id = [0xc1; 32];
let mut rules = ConstitutionRules::founder_only(founder_id);
rules.grant(CapabilityGrant {
id: root_id,
subject: root_holder.master_public_key().to_bytes(),
path_prefix: "moot/fauna".into(),
not_before_ms: 1,
expires_at_ms: Some(100),
delegation_depth: 1,
});
let source = Moot::in_memory(ID, founder_id, retention());
source
.found(founder.to_seed(), None, None, rules.clone(), 1)
.await
.unwrap();
let scope = CapabilityScope {
domain: MOOT_DELEGATION_DOMAIN.into(),
resource: ID.0.to_vec(),
path_prefix: "moot/fauna/notes".into(),
actions: [MOOT_ACT_ACTION.to_string()].into_iter().collect(),
};
let signed = SignedDelegationCertificate::issue(
&root_holder,
DelegationCertificate::new(
DelegationParent::Root(root_id),
root_holder.master_public_key().to_bytes(),
delegate.master_public_key().to_bytes(),
scope.clone(),
2,
3,
Some(90),
0,
[0x53; 32],
),
)
.unwrap();
let certificate_id = signed.certificate.id();
let delegation_key = root_holder
.derive_keypair(&delegation_signing_salt(&scope))
.unwrap();
source
.delegation_store()
.author_issue(&delegation_key, &rules, signed)
.await
.unwrap();
let mut bytes = Vec::new();
source
.export_plain_drop(
&mut bytes,
DropExportProfile::default(),
DropLimits::default(),
)
.await
.unwrap();
let target = Moot::in_memory(ID, founder_id, retention());
let receipt = target
.import_plain_drop(Cursor::new(bytes), DropLimits::default())
.await
.unwrap();
assert_eq!(receipt.delegation_operations, 1);
assert_eq!(receipt.snapshot.delegated_certificates, 1);
assert_eq!(
target
.authorize_current_delegated(
&Access {
capability_covers: true,
facts: TesseraFacts {
score: 1,
..Default::default()
},
},
&MootAuthorizationRequest {
subject: delegate.master_public_key().to_bytes(),
capability_path: "moot/fauna/notes/write".into(),
at_ms: 50,
},
)
.await
.unwrap(),
GateDecision::Allow
);
let revocation = SignedDelegationRevocation::issue(
&root_holder,
DelegationRevocation::new(
certificate_id,
root_holder.master_public_key().to_bytes(),
scope.clone(),
60,
[0x54; 32],
),
)
.unwrap();
source
.delegation_store()
.author_revoke(&delegation_key, &rules, revocation)
.await
.unwrap();
let mut revoked_bytes = Vec::new();
source
.export_plain_drop(
&mut revoked_bytes,
DropExportProfile::default(),
DropLimits::default(),
)
.await
.unwrap();
let revoked_receipt = target
.import_plain_drop(Cursor::new(revoked_bytes), DropLimits::default())
.await
.unwrap();
assert_eq!(revoked_receipt.delegation_operations, 1);
assert_eq!(
target.delegation_scope_key_epochs().await.unwrap()[0].epoch,
1
);
assert!(
target
.delegation_projections(60)
.await
.unwrap()
.iter()
.all(|projection| !projection.active)
);
assert_eq!(
target
.authorize_current_delegated(
&Access {
capability_covers: true,
facts: TesseraFacts {
score: 1,
..Default::default()
},
},
&MootAuthorizationRequest {
subject: delegate.master_public_key().to_bytes(),
capability_path: "moot/fauna/notes/write".into(),
at_ms: 60,
},
)
.await
.unwrap(),
GateDecision::Deny(DenyReason::NoCapability)
);
}
#[tokio::test]
async fn aggregate_drop_reconstructs_all_five_retained_domains_for_late_peer() {
let founder = keypair(12);
let founder_id = founder.public_key().to_bytes();
let member_identity = InMemoryProvider::from_seed([0x61; 32]);
let member_root = member_identity.master_public_key().to_bytes();
let root_holder = InMemoryProvider::from_seed([0x62; 32]);
let delegate = InMemoryProvider::from_seed([0x63; 32]);
let root_id = [0xd1; 32];
let mut rules = ConstitutionRules::founder_only(founder_id);
rules.grant(CapabilityGrant {
id: root_id,
subject: root_holder.master_public_key().to_bytes(),
path_prefix: "moot/fauna".into(),
not_before_ms: 1,
expires_at_ms: Some(100),
delegation_depth: 1,
});
let source = Moot::in_memory(ID, founder_id, retention());
source
.found(founder.to_seed(), None, None, rules.clone(), 1)
.await
.unwrap();
let membership_receipt = source
.update_membership_for_identity(
&member_identity,
MootMembershipAction::Create {
initial_members: vec![MootMember {
member: member_root,
access: MootAccessLevel::Manage,
}],
},
)
.await
.unwrap();
assert!(matches!(
source.outbound(&membership_receipt).await.unwrap(),
MootOutboundOperation::Membership(_)
));
let scope = CapabilityScope {
domain: MOOT_DELEGATION_DOMAIN.into(),
resource: ID.0.to_vec(),
path_prefix: "moot/fauna/notes".into(),
actions: [MOOT_ACT_ACTION.to_string()].into_iter().collect(),
};
let signed = SignedDelegationCertificate::issue(
&root_holder,
DelegationCertificate::new(
DelegationParent::Root(root_id),
root_holder.master_public_key().to_bytes(),
delegate.master_public_key().to_bytes(),
scope.clone(),
2,
3,
Some(90),
0,
[0x64; 32],
),
)
.unwrap();
let delegation_key = root_holder
.derive_keypair(&delegation_signing_salt(&scope))
.unwrap();
source
.delegation_store()
.author_issue(&delegation_key, &rules, signed)
.await
.unwrap();
source
.declare(
founder.to_seed(),
"peer press".into(),
"shared place".into(),
4,
)
.await
.unwrap();
source
.join(founder.to_seed(), "founder".into(), 5)
.await
.unwrap();
source
.share(
founder.to_seed(),
[0x65; 32],
"text/plain".into(),
"field note".into(),
6,
)
.await
.unwrap();
source
.record_tessera(
founder.to_seed(),
TesseraEvent::GovernanceParticipation {
by: ChainRoot(member_root),
at_ms: 7,
},
)
.await
.unwrap();
let expected = source.snapshot().await.unwrap();
let mut bytes = Vec::new();
source
.export_plain_drop(
&mut bytes,
DropExportProfile::default(),
DropLimits::default(),
)
.await
.unwrap();
let late_peer = Moot::in_memory(ID, founder_id, retention());
let receipt = late_peer
.import_plain_drop(Cursor::new(bytes), DropLimits::default())
.await
.unwrap();
assert_eq!(receipt.constitution_operations, 1);
assert_eq!(receipt.delegation_operations, 1);
assert_eq!(receipt.membership_operations, 1);
assert_eq!(receipt.tessera_operations, 1);
assert_eq!(receipt.snapshot, expected);
assert_eq!(receipt.snapshot.membership.members[0].member, member_root);
assert_eq!(receipt.snapshot.roster.members.len(), 1);
assert_eq!(receipt.snapshot.roster.fauna.len(), 1);
assert_eq!(receipt.snapshot.delegated_certificates, 1);
assert_eq!(receipt.snapshot.tessera_operations, 1);
}
#[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);
}
#[tokio::test]
async fn native_drop_bootstraps_checkpoint_and_roster_then_is_idempotent() {
let founder = keypair(4);
let founder_id = founder.public_key().to_bytes();
let source = Moot::in_memory(ID, founder_id, retention());
let destination = Moot::in_memory(ID, founder_id, retention());
for service in [&source, &destination] {
service
.found(
founder.to_seed(),
None,
None,
ConstitutionRules::founder_only(founder_id),
1,
)
.await
.unwrap();
}
source
.declare(
founder.to_seed(),
"drop circle".into(),
"travels by file".into(),
2,
)
.await
.unwrap();
source
.join(founder.to_seed(), "mark".into(), 3)
.await
.unwrap();
source.checkpoint(founder.to_seed(), 4).await.unwrap();
let mut bytes = Vec::new();
source
.export_plain_drop(
&mut bytes,
DropExportProfile::default(),
DropLimits::default(),
)
.await
.unwrap();
let first = destination
.import_plain_drop(Cursor::new(bytes.clone()), DropLimits::default())
.await
.unwrap();
assert_eq!(first.snapshot.roster.members.len(), 1);
assert_eq!(
first.snapshot.roster.declaration.unwrap().name,
"drop circle"
);
assert!(first.snapshot.checkpoint.is_some());
let repeated = destination
.import_plain_drop(Cursor::new(bytes), DropLimits::default())
.await
.unwrap();
assert!(repeated.import.receipt_hit);
}
#[tokio::test]
async fn aggregate_drop_bootstraps_rotated_checkpoint_authority() {
let founder = keypair(5);
let successor = keypair(6);
let founder_id = founder.public_key().to_bytes();
let source = Moot::in_memory(ID, founder_id, retention());
let destination = Moot::in_memory(ID, founder_id, retention());
source
.found(
founder.to_seed(),
None,
None,
ConstitutionRules::founder_only(founder_id),
1,
)
.await
.unwrap();
source
.join(founder.to_seed(), "mark".into(), 2)
.await
.unwrap();
source.checkpoint(founder.to_seed(), 3).await.unwrap();
let mut rules = ConstitutionRules::founder_only(founder_id);
rules.checkpoint_signers.clear();
rules
.checkpoint_signers
.insert(successor.public_key().to_bytes());
source.amend(founder.to_seed(), rules, 4).await.unwrap();
let rotated = source.checkpoint(successor.to_seed(), 5).await.unwrap();
let mut bytes = Vec::new();
source
.export_plain_drop(
&mut bytes,
DropExportProfile::default(),
DropLimits::default(),
)
.await
.unwrap();
let imported = destination
.import_plain_drop(Cursor::new(bytes), DropLimits::default())
.await
.unwrap();
assert_eq!(imported.constitution_operations, 2);
assert_eq!(
imported.snapshot.checkpoint.unwrap().operation,
rotated.operation
);
assert_eq!(imported.snapshot.roster.members.len(), 1);
}
#[tokio::test]
async fn protected_drop_and_tessera_command_expose_publishable_operations() {
let founder = keypair(7);
let founder_id = founder.public_key().to_bytes();
let source = Moot::in_memory(ID, founder_id, retention());
let destination = Moot::in_memory(ID, founder_id, retention());
source
.found(
founder.to_seed(),
None,
None,
ConstitutionRules::founder_only(founder_id),
1,
)
.await
.unwrap();
destination
.found(
founder.to_seed(),
None,
None,
ConstitutionRules::founder_only(founder_id),
1,
)
.await
.unwrap();
source
.declare(
founder.to_seed(),
"private circle".into(),
"sealed".into(),
2,
)
.await
.unwrap();
let mut bytes = Vec::new();
source
.export_protected_drop(
&mut bytes,
&MootDropSelector::default(),
DropExportBudget::default(),
DropLimits::default(),
&TestProtector,
)
.await
.unwrap();
let imported = destination
.import_protected_drop(Cursor::new(bytes), DropLimits::default(), &TestProtector)
.await
.unwrap();
assert_eq!(
imported.snapshot.roster.declaration.unwrap().name,
"private circle"
);
let receipt = source
.record_tessera(
founder.to_seed(),
TesseraEvent::GovernanceParticipation {
by: ChainRoot(founder_id),
at_ms: 3,
},
)
.await
.unwrap();
assert_eq!(receipt.lane, MootLane::Tessera);
assert!(matches!(
source.outbound(&receipt).await.unwrap(),
MootOutboundOperation::Tessera(_)
));
}
}