use super::types::{digest, text, Operation};
use super::*;
use crate::{
escrow::{DEPS, NONCE, PREV},
intend::{Instance, Reject},
message::Message,
role::AgentKey,
sexpr::{Atom, SExpr},
state::{Act, Value},
};
use alloc::{
collections::{BTreeMap, BTreeSet},
string::{String, ToString},
vec::Vec,
};
#[derive(Debug, Default)]
struct State {
operations: BTreeMap<String, Operation>,
owned: BTreeMap<String, OwnedSealRequest>,
sealed: BTreeMap<String, String>,
certificates: BTreeMap<(VoteKind, String), Certificate>,
versions: BTreeMap<String, DagVersion>,
visited: BTreeSet<String>,
signed: BTreeSet<String>,
effects: BTreeSet<String>,
fences: BTreeSet<String>,
released: BTreeSet<String>,
active: BTreeMap<String, String>,
charges: BTreeMap<String, Resources>,
}
#[derive(Clone)]
enum Update {
Candidate(String, Operation),
Owned(String, OwnedSealRequest, bool),
Certificate((VoteKind, String), Certificate),
Version(String, DagVersion),
Adopt {
account: String,
id: String,
},
Sign {
id: String,
epoch: String,
charge: Resources,
},
Effect(String),
Fence(String),
Release {
id: String,
epoch: String,
charge: Resources,
},
}
pub struct Replica {
context: Context,
validator: String,
limits: Limits,
sequence: u64,
state: State,
}
enum GroupUndo {
Candidate(String),
Certificate((VoteKind, String)),
Sign {
id: String,
epoch: String,
charge: Option<Resources>,
},
Effect(String),
}
struct GroupPreparation<'a> {
replica: &'a mut Replica,
sequence: u64,
undo: Vec<GroupUndo>,
}
impl Drop for GroupPreparation<'_> {
fn drop(&mut self) {
for undo in self.undo.drain(..).rev() {
match undo {
GroupUndo::Candidate(id) => {
self.replica.state.operations.remove(&id);
}
GroupUndo::Certificate(key) => {
self.replica.state.certificates.remove(&key);
}
GroupUndo::Sign { id, epoch, charge } => {
self.replica.state.signed.remove(&id);
match charge {
Some(old) => {
self.replica.state.charges.insert(epoch, old);
}
None => {
self.replica.state.charges.remove(&epoch);
}
}
}
GroupUndo::Effect(id) => {
self.replica.state.effects.remove(&id);
}
}
}
self.replica.sequence = self.sequence;
}
}
impl Replica {
pub fn commit_group<J: BatchJournal, A: Authentication>(
&mut self,
events: &[Event],
journal: &mut J,
auth: &A,
) -> Result<Vec<Option<SigningRequest>>> {
if events.len() > 256 {
return Err("group exceeds 256 events".into());
}
let mut durable = Vec::new();
let mut updates = Vec::new();
{
let sequence = self.sequence;
let plan = GroupPreparation {
replica: self,
sequence,
undo: Vec::new(),
};
let mut plan = plan;
for event in events {
if !matches!(
event,
Event::Candidate(_) | Event::Certificate(_) | Event::Sign(_) | Event::Effect(_)
) {
return Err("unsupported group transition".into());
}
let Some(update) = plan.replica.prepare(event, auth)? else {
continue;
};
if plan.replica.sequence >= plan.replica.limits.events {
return Err("journal limit reached; evidence retained".into());
}
let undo = match &update {
Update::Candidate(id, _) => GroupUndo::Candidate(id.clone()),
Update::Certificate(key, _) => GroupUndo::Certificate(key.clone()),
Update::Sign { id, epoch, .. } => GroupUndo::Sign {
id: id.clone(),
epoch: epoch.clone(),
charge: plan.replica.state.charges.get(epoch).copied(),
},
Update::Effect(id) => GroupUndo::Effect(id.clone()),
_ => unreachable!("group transition checked"),
};
plan.undo.push(undo);
plan.replica.apply_update(update.clone());
plan.replica.sequence += 1;
durable.push(event.clone());
updates.push(update);
}
} if !durable.is_empty() {
journal.append_batch(&self.context.id, &self.validator, self.sequence, &durable)?;
for update in updates {
self.apply_update(update);
self.sequence += 1;
}
}
Ok(events
.iter()
.map(|event| match event {
Event::Sign(id) => Some(self.context.request(
VoteKind::Operation,
id,
&self.validator,
)),
Event::Effect(id) => {
Some(self.context.request(VoteKind::Effects, id, &self.validator))
}
_ => None,
})
.collect())
}
pub fn initialize<J: Journal>(
context: Context,
validator: &str,
limits: Limits,
journal: &mut J,
) -> Result<Self> {
if !context.committee.contains(validator) {
return Err("validator outside committee".into());
}
if journal.load(&context.id, validator)?.is_some() {
return Err("journal exists: recover it".into());
}
if limits.events == 0 {
return Err("event limit is zero".into());
}
journal.append(&context.id, validator, None, &Event::Initialize)?;
let mut state = State::default();
for a in context.initial.keys() {
let root = context.root_epoch(a)?;
state.visited.insert(root.clone());
state.active.insert(a.clone(), root);
}
Ok(Self {
context,
validator: validator.into(),
limits,
sequence: 1,
state,
})
}
pub fn recover<J: Journal, A: Authentication>(
context: Context,
validator: &str,
limits: Limits,
journal: &J,
auth: &A,
) -> Result<Self> {
if !context.committee.contains(validator) {
return Err("validator outside committee".into());
}
let events = journal
.load(&context.id, validator)?
.ok_or("missing journal; initialize explicitly")?;
if events.first() != Some(&Event::Initialize) || events.len() as u64 > limits.events {
return Err("invalid or oversized journal".into());
}
let mut state = State::default();
for a in context.initial.keys() {
let root = context.root_epoch(a)?;
state.visited.insert(root.clone());
state.active.insert(a.clone(), root);
}
let mut r = Self {
context,
validator: validator.into(),
limits,
sequence: 1,
state,
};
for e in events.into_iter().skip(1) {
r.apply(&e, auth)?;
r.sequence += 1;
}
Ok(r)
}
fn owned_adoption_path(&self, target: &str) -> Result<Vec<String>> {
let manifest = self.epoch(target)?;
if manifest.phase != VersionPhase::Owned {
return Ok(Vec::new());
}
let root = self
.owned_root(&manifest.account)
.ok_or("catch-up awaits owned-root QC")?;
if !self.descends(target, root)? {
return Err("catch-up target outside owned root".into());
}
self.adoption_path(target, Some(root))
}
fn adoption_path(&self, target: &str, boundary: Option<&str>) -> Result<Vec<String>> {
let manifest = self.epoch(target)?;
let current = self.active_epoch(&manifest.account)?;
if current == target {
return Ok(Vec::new());
}
let mut todo = alloc::vec![target.to_string()];
let mut seen = BTreeSet::from([target.to_string()]);
let mut forward = BTreeMap::new();
let mut found = false;
while let Some(id) = todo.pop() {
if id == current {
found = true;
break;
}
let node = self.epoch(&id)?;
if let Some(root) = boundary {
if !self.descends(&id, root)? && !self.descends(root, &id)? {
continue;
}
} else if node.phase == VersionPhase::Owned
&& self.owned_root(&manifest.account).is_none()
{
continue;
}
if self.state.signed.iter().any(|signed| {
self.state.operations[signed].account == manifest.account
&& !node.held.contains(signed)
}) {
continue;
}
for parent in &node.parents {
if seen.insert(parent.clone()) {
forward.insert(parent.clone(), id.clone());
todo.push(parent.clone());
}
}
}
if !found {
return Err("catch-up target is not a descendant of current version".into());
}
let mut path = Vec::new();
let mut cursor = current.to_string();
while cursor != target {
let next = forward.get(&cursor).ok_or("broken catch-up path")?;
let node = self.epoch(next)?;
if let Some(root) = boundary {
if !self.descends(next, root)? && !self.descends(root, next)? {
return Err("catch-up node is outside certified root ancestry".into());
}
} else if node.phase == VersionPhase::Owned
&& self.owned_root(&manifest.account).is_none()
{
return Err("catch-up awaits owned-root QC".into());
}
for signed in &self.state.signed {
if self.op(signed)?.account == manifest.account && !node.held.contains(signed) {
return Err("catch-up node omits historical signature".into());
}
}
path.push(next.clone());
cursor = next.clone();
}
Ok(path)
}
pub fn catch_up_owned<J: Journal, A: Authentication>(
&mut self,
target: &str,
journal: &mut J,
auth: &A,
) -> Result<()> {
let path = self.owned_adoption_path(target)?;
for id in path {
self.adopt_version(&id, journal, auth)?;
}
Ok(())
}
pub fn publication(&self, act: &Act) -> Result<Publication> {
self.operation(act)?;
Ok(Publication {
act: act.clone(),
evidence: self.relay_evidence(
Some(act),
alloc::vec![act.address.clone()],
Vec::new(),
)?,
})
}
pub fn seal_evidence(&self, manifest: &VersionManifest) -> Result<Vec<RelayItem>> {
self.check_version_manifest(manifest)?;
self.relay_evidence(
None,
manifest.held.union(&manifest.credited).cloned().collect(),
manifest.parents.iter().cloned().collect(),
)
}
fn relay_evidence(
&self,
target: Option<&Act>,
mut operations: Vec<String>,
mut versions: Vec<String>,
) -> Result<Vec<RelayItem>> {
let mut seen_ops = BTreeSet::new();
let mut seen_versions = BTreeSet::new();
let mut seen_roots = BTreeSet::new();
let mut evidence = Vec::new();
while !operations.is_empty() || !versions.is_empty() {
while let Some(id) = operations.pop() {
if !seen_ops.insert(id.clone()) {
continue;
}
let candidate = match target.filter(|act| id == act.address) {
Some(act) => act,
None => self.operation_act(&id).ok_or("missing relay operation")?,
};
let op = self.operation(candidate)?;
versions.push(op.epoch);
evidence.push(RelayItem::Act(candidate.clone()));
for kind in [VoteKind::Operation, VoteKind::Effects, VoteKind::Cancel] {
if let Some(cert) = self.certificate(kind, &id) {
evidence.push(RelayItem::Certificate(cert.clone()));
}
}
}
if let Some(id) = versions.pop() {
if !seen_versions.insert(id.clone()) {
continue;
}
let manifest = self.epoch(&id)?;
let Some(version) = self.version(&id) else {
continue;
}; evidence.push(RelayItem::Version(version.clone()));
versions.extend(manifest.parents.iter().cloned());
operations.extend(manifest.held.iter().cloned());
operations.extend(manifest.credited.iter().cloned());
operations.extend(manifest.refunded.iter().cloned());
if manifest.phase == VersionPhase::Owned {
let root = self
.owned_root(&manifest.account)
.ok_or("missing relay owned-root QC")?;
if !self.descends(&id, root)? {
return Err("relay target is outside owned root".into());
}
if seen_roots.insert(root.to_string()) {
evidence.push(RelayItem::Owned(self.state.owned[root].clone()));
evidence.push(RelayItem::Certificate(
self.certificate(VoteKind::OwnedSeal, root)
.ok_or("missing seal QC")?
.clone(),
));
versions.push(root.to_string());
}
}
}
}
Ok(evidence)
}
fn bound_relay_act(&self, act: &Act) -> Result<()> {
if act.signer.len() > self.limits.object_bytes
|| act.address.len() > self.limits.object_bytes
|| act.verb.len() > self.limits.object_bytes
{
return Err("relay act header limit exceeded".into());
}
bounded_message(&act.message, self.limits.object_bytes)?;
self.context.structural(act)
}
fn bound_relay_vote(&self, vote: &Vote) -> Result<()> {
if vote.signature.len() > self.limits.signature_bytes
|| vote.context != self.context.id
|| vote.payload.len() > crate::multihash::TEXT_LEN
{
return Err("relay vote domain or signature limit exceeded".into());
}
if !self.context.actors.contains(&vote.signer)
&& !self.context.committee.contains(&vote.signer)
{
return Err("unknown relay signing identity".into());
}
Ok(())
}
fn bound_relay_version(&self, version: &DagVersion) -> Result<()> {
let m = &version.manifest;
if !self.context.initial.contains_key(&m.account)
|| m.parents.len() > self.limits.versions.saturating_add(1)
|| m.held.len() > self.limits.operations
|| m.refunded.len() > self.limits.operations
|| m.credited.len() > self.limits.operations
{
return Err("relay manifest scope or count limit exceeded".into());
}
for ids in [&m.parents, &m.held, &m.refunded, &m.credited] {
if ids.iter().any(|id| id.len() > crate::multihash::TEXT_LEN) {
return Err("relay identifier limit exceeded".into());
}
}
self.bound_relay_vote(&version.authorization)
}
fn bound_seal_request(&self, request: &OwnedSealRequest) -> Result<()> {
self.bound_relay_version(&request.version)?;
self.bound_relay_vote(&request.authorization)
}
fn bound_relay_item(&self, item: &RelayItem) -> Result<()> {
match item {
RelayItem::Act(act) => self.bound_relay_act(act),
RelayItem::Version(v) => self.bound_relay_version(v),
RelayItem::Owned(r) => self.bound_seal_request(r),
RelayItem::Certificate(c) => {
if c.votes.len() > self.context.committee.validators.len()
|| c.payload.len() > crate::multihash::TEXT_LEN
{
return Err("relay certificate count or payload limit exceeded".into());
}
for v in &c.votes {
self.bound_relay_vote(v)?;
}
Ok(())
}
}
}
fn relay_item_bound(&self) -> usize {
self.limits
.operations
.saturating_mul(4)
.saturating_add(self.limits.versions.saturating_mul(3))
.saturating_add(1)
}
pub fn prepare_seal_publication<J: Journal, A: Authentication>(
&mut self,
publication: &SealPublication,
journal: &mut J,
auth: &A,
) -> Result<PublicationResult> {
self.bound_seal_request(&publication.request)?;
if publication.evidence.len() > self.relay_item_bound() {
return Err("seal evidence limit exceeded".into());
}
let (pending, reasons) = self.import_relay_items(&publication.evidence, journal, auth)?;
let id = publication.request.version.manifest.id(&self.context.id);
if let Some(cert) = self.certificate(VoteKind::OwnedSeal, &id) {
self.check_owned(&publication.request, auth)?;
let mut evidence = self.seal_evidence(&publication.request.version.manifest)?;
evidence.push(RelayItem::Owned(publication.request.clone()));
evidence.push(RelayItem::Certificate(cert.clone()));
return Ok(PublicationResult::Finalized {
certificate: cert.clone(),
evidence,
});
}
if !pending.is_empty() {
return Ok(PublicationResult::Pending {
items: pending,
reasons,
});
}
self.check_owned(&publication.request, auth)?;
let manifest = &publication.request.version.manifest;
let current = self.active_epoch(&manifest.account)?.to_string();
if !manifest.parents.contains(¤t)
&& !self.state.sealed.contains_key(&manifest.account)
{
let path = manifest.parents.iter().find_map(|parent| {
self.adoption_path(parent, self.owned_root(&manifest.account))
.ok()
});
let Some(path) = path else {
return Ok(PublicationResult::Pending {
items: Vec::new(),
reasons: alloc::vec!["seal parent catch-up needs compatible ancestry".into()],
});
};
for id in path {
self.adopt_version(&id, journal, auth)?;
}
}
match self.prepare(&Event::SealOwned(publication.request.clone()), auth) {
Err(reason) => Ok(PublicationResult::Pending {
items: Vec::new(),
reasons: alloc::vec![reason],
}),
Ok(_) => Ok(PublicationResult::Seal(self.prepare_owned_seal(
publication.request.clone(),
journal,
auth,
)?)),
}
}
fn import_relay_items<J: Journal, A: Authentication>(
&mut self,
items: &[RelayItem],
journal: &mut J,
auth: &A,
) -> Result<(Vec<RelayItem>, Vec<String>)> {
let bound = self
.limits
.operations
.saturating_mul(4)
.saturating_add(self.limits.versions.saturating_mul(3))
.saturating_add(2);
if items.len() > bound {
return Err("publication evidence limit exceeded".into());
}
for item in items {
self.bound_relay_item(item)?;
}
let mut pending = items.to_vec();
let mut reasons;
loop {
let before = pending.len();
let mut deferred = Vec::new();
reasons = Vec::new();
for item in pending {
let event = match &item {
RelayItem::Act(a) => Event::Candidate(a.clone()),
RelayItem::Version(v) => Event::Version(v.clone()),
RelayItem::Owned(r) => Event::OwnedProposal(r.clone()),
RelayItem::Certificate(c) => Event::Certificate(c.clone()),
};
match self.prepare(&event, auth) {
Err(reason) => {
reasons.push(reason);
deferred.push(item);
}
Ok(_) => self.commit(event, journal, auth)?,
}
}
pending = deferred;
if pending.is_empty() || pending.len() == before {
break;
}
}
Ok((pending, reasons))
}
pub fn receive_evidence<J: Journal, A: Authentication>(
&mut self,
items: &[RelayItem],
journal: &mut J,
auth: &A,
) -> Result<RelayReport> {
let (pending, reasons) = self.import_relay_items(items, journal, auth)?;
Ok(RelayReport { pending, reasons })
}
pub fn prepare_publication<J: Journal, A: Authentication>(
&mut self,
publication: &Publication,
journal: &mut J,
auth: &A,
) -> Result<PublicationResult> {
self.bound_relay_act(&publication.act)?;
if !auth.authenticate_act(&publication.act) {
return Err("publication target authentication failed".into());
}
if publication.evidence.len() > self.relay_item_bound() {
return Err("publication evidence limit exceeded".into());
}
for item in &publication.evidence {
self.bound_relay_item(item)?;
}
let mut items = publication.evidence.clone();
items.push(RelayItem::Act(publication.act.clone()));
let (pending, reasons) = self.import_relay_items(&items, journal, auth)?;
if let Some(cert) = self.certificate(VoteKind::Effects, &publication.act.address) {
return Ok(PublicationResult::Finalized {
certificate: cert.clone(),
evidence: self.publication(&publication.act)?.evidence,
});
}
if !pending.is_empty() {
return Ok(PublicationResult::Pending {
items: pending,
reasons,
});
}
if self.has(VoteKind::Operation, &publication.act.address) {
let operation = self
.certificate(VoteKind::Operation, &publication.act.address)
.ok_or("missing operation QC")?
.clone();
let request = self.prepare_effects(&publication.act.address, journal, auth)?;
return Ok(PublicationResult::Effects { operation, request });
}
let epoch = self.op(&publication.act.address)?.epoch.clone();
match self.owned_adoption_path(&epoch) {
Err(reason) => {
return Ok(PublicationResult::Pending {
items: Vec::new(),
reasons: alloc::vec![reason],
})
}
Ok(path) => {
for id in path {
self.adopt_version(&id, journal, auth)?;
}
}
}
match self.prepare(&Event::Sign(publication.act.address.clone()), auth) {
Err(reason) => Ok(PublicationResult::Pending {
items: Vec::new(),
reasons: alloc::vec![reason],
}),
Ok(_) => Ok(PublicationResult::Operation(self.prepare_operation(
&publication.act.address,
journal,
auth,
)?)),
}
}
pub fn context(&self) -> &Context {
&self.context
}
pub fn validator(&self) -> &str {
&self.validator
}
pub fn operation_act(&self, id: &str) -> Option<&Act> {
self.state.operations.get(id).map(|op| &op.act)
}
pub fn certificate(&self, kind: VoteKind, id: &str) -> Option<&Certificate> {
self.state.certificates.get(&(kind, id.into()))
}
pub fn journal_sequence(&self) -> u64 {
self.sequence
}
fn commit<J: Journal, A: Authentication>(
&mut self,
event: Event,
journal: &mut J,
auth: &A,
) -> Result<()> {
let Some(update) = self.prepare(&event, auth)? else {
return Ok(());
};
if self.sequence >= self.limits.events {
return Err("journal limit reached; evidence retained".into());
}
journal.append(
&self.context.id,
&self.validator,
Some(self.sequence),
&event,
)?;
self.apply_update(update);
self.sequence += 1;
Ok(())
}
fn op(&self, id: &str) -> Result<&Operation> {
self.state
.operations
.get(id)
.ok_or_else(|| alloc::format!("missing operation {id}"))
}
fn has(&self, kind: VoteKind, id: &str) -> bool {
self.state.certificates.contains_key(&(kind, id.into()))
}
fn epoch(&self, id: &str) -> Result<&VersionManifest> {
if let Some(v) = self.state.versions.get(id) {
return Ok(&v.manifest);
}
self.context
.root_manifest(id)
.ok_or_else(|| alloc::format!("missing certified epoch {id}"))
}
fn verify_vote<A: Authentication>(
&self,
v: &Vote,
kind: VoteKind,
payload: &str,
key: &str,
auth: &A,
) -> Result<()> {
if v.context != self.context.id
|| v.kind != kind
|| v.payload != payload
|| v.signer != key
|| v.signature.len() > self.limits.signature_bytes
|| v.signature.is_empty()
|| !auth.verify(key, &v.preimage(), &v.signature)
{
return Err("invalid signature, domain, signer or payload".into());
}
Ok(())
}
fn verify_certificate<A: Authentication>(
&self,
c: &Certificate,
kind: VoteKind,
payload: &str,
auth: &A,
) -> Result<()> {
let committee = &self.context.committee;
if c.kind != kind
|| c.payload != payload
|| c.votes.len() < committee.quorum
|| c.votes.len() > committee.validators.len()
{
return Err("invalid certificate kind, payload or quorum".into());
}
let mut keys = BTreeSet::new();
for v in &c.votes {
if !committee.contains(&v.signer) || !keys.insert(v.signer.clone()) {
return Err("nonmember or duplicate validator".into());
}
self.verify_vote(v, kind, payload, &v.signer, auth)?;
}
Ok(())
}
fn operation(&self, a: &Act) -> Result<Operation> {
bounded_message(&a.message, self.limits.object_bytes)?;
self.context.structural(a)?;
if crate::canonical::canonical_encode(&SExpr::from(&a.message)).len()
> self.limits.object_bytes
{
return Err("operation too large".into());
}
let epoch = match a.fields.get(PREV) {
Some(SExpr::Atom(Atom::Symbol(s))) => s.clone(),
_ => return Err("missing source epoch".into()),
};
let m = self.epoch(&epoch)?;
let account = self.context.account(&a.signer)?.to_string();
if m.account != account {
return Err("epoch belongs to another account".into());
}
let dependencies = SExpr::List(
m.credited
.iter()
.map(|s| SExpr::Atom(Atom::Symbol(s.clone())))
.collect(),
);
if a.fields.get(DEPS) != Some(&dependencies) {
return Err("epoch finalized dependencies mismatch".into());
}
if !matches!(a.fields.get(NONCE),Some(SExpr::Atom(Atom::Str(s))) if !s.is_empty() && s.len()<=256)
{
return Err("missing or invalid transaction nonce".into());
}
let rule = &self.context.rule;
let (key, recipient, kind) = if a.verb == rule.increment.0 {
(&rule.increment.1, None, 0)
} else if a.verb == rule.decrement.0 {
(&rule.decrement.1, None, 1)
} else if let Some((_, r, k)) = rule.transfer.as_ref().filter(|(v, _, _)| a.verb == *v) {
(k, Some(r), 2)
} else if let Some((v, r, k)) = &rule.transfer_headroom {
if &a.verb == v {
(k, Some(r), 3)
} else {
return Err("not a counter operation".into());
}
} else {
return Err("not a counter operation".into());
};
let n = match a.fields.get(key) {
Some(SExpr::Atom(Atom::Num(n))) if *n > 0 => i128::from(*n),
_ => return Err("amount must be a positive integer".into()),
};
let to = match recipient {
None => account.clone(),
Some(k) => match a.fields.get(k) {
Some(SExpr::Atom(Atom::Symbol(s) | Atom::Str(s)))
if self.context.initial.contains_key(s) =>
{
s.clone()
}
_ => return Err("unknown recipient".into()),
},
};
if kind >= 2 && to == a.signer {
return Err("self transfer is not a resource operation".into());
}
if kind == 0 && !self.context.issuers.contains(&a.signer) {
return Err("mint requires issuer authority".into());
}
let bounded = rule.ceiling.is_some();
let (cost, credit) = match kind {
0 => (
Resources {
rights: 0,
headroom: if bounded { n } else { 0 },
},
Resources {
rights: n,
headroom: 0,
},
),
1 => (
Resources {
rights: n,
headroom: 0,
},
Resources {
rights: 0,
headroom: if bounded { n } else { 0 },
},
),
2 => (
Resources {
rights: n,
headroom: 0,
},
Resources {
rights: n,
headroom: 0,
},
),
_ => {
if !bounded {
return Err("headroom requires a ceiling".into());
}
(
Resources {
rights: 0,
headroom: n,
},
Resources {
rights: 0,
headroom: n,
},
)
}
};
Ok(Operation {
act: a.clone(),
account,
epoch,
cost,
credits: [(to, credit)].into_iter().collect(),
})
}
fn budget(&self, id: &str) -> Result<Resources> {
self.budget_op(id, self.op(id)?)
}
fn budget_op(&self, id: &str, op: &Operation) -> Result<Resources> {
let epoch = self.epoch(&op.epoch)?;
if self.state.active.get(&op.account) != Some(&op.epoch) || self.state.released.contains(id)
{
return Err("version inactive or operation released".into());
}
if let Some(root) = self.owned_root(&op.account) {
if self.state.fences.contains(id) || self.has(VoteKind::Cancel, id) {
return Err("owned operation has a preexisting cancellation fence".into());
}
if !self.descends(&op.epoch, root)? {
return Err("operation outside certified owned continuation".into());
}
if self
.state
.signed
.iter()
.any(|other| self.state.operations[other].epoch == op.epoch)
{
return Err("owned version slot already consumed".into());
}
if op.cost.rights > epoch.allocation.rights
|| op.cost.headroom > epoch.allocation.headroom
{
return Err("owned allocation exceeded".into());
}
return self
.state
.charges
.get(&op.epoch)
.copied()
.unwrap_or_default()
.add(op.cost);
}
if epoch.phase == VersionPhase::Owned {
return Err("owned metadata awaits certified root".into());
}
if self.state.sealed.contains_key(&op.account) {
return Err("account sealed; awaiting certificate".into());
}
let used = self
.state
.charges
.get(&op.epoch)
.copied()
.unwrap_or_default()
.add(op.cost)?;
let q = self.context.committee.quorum as i128;
let k = i128::from(self.context.committee.faults) + 1;
if used.rights.checked_mul(q).ok_or("budget overflow")?
> epoch
.allocation
.rights
.checked_mul(k)
.ok_or("budget overflow")?
|| used.headroom.checked_mul(q).ok_or("budget overflow")?
> epoch
.allocation
.headroom
.checked_mul(k)
.ok_or("budget overflow")?
{
return Err("local validator budget exceeded".into());
}
Ok(used)
}
pub(crate) fn owner_pristine(&self, owner: &str) -> bool {
!self.state.operations.values().any(|op| op.account == owner)
&& self.state.active.get(owner) == self.context.root_epoch(owner).ok().as_ref()
}
pub(crate) fn owner_epoch_is_owned(&self, owner: &str, epoch: &str) -> Result<bool> {
match self.owned_root(owner) {
Some(root) => self.descends(epoch, root),
None => Ok(false),
}
}
pub(crate) fn owner_cost(&self, act: &Act) -> Result<Resources> {
Ok(self.operation(act)?.cost)
}
pub(crate) fn owner_can_issue(&self, act: &Act, issued: &[Act]) -> Result<()> {
let op = self.operation(act)?;
self.budget_op(&act.address, &op)?;
self.owner_batch_fits(act, issued)
}
pub(crate) fn owner_batch_fits(&self, act: &Act, issued: &[Act]) -> Result<()> {
let op = self.operation(act)?;
let epoch = self.epoch(&op.epoch)?;
let owned = epoch.phase == VersionPhase::Owned;
if op.cost.rights > epoch.allocation.rights || op.cost.headroom > epoch.allocation.headroom
{
return Err("owner cost exceeds version allocation".into());
}
let mut used = op.cost;
for previous in issued {
let previous = self.operation(previous)?;
if previous.epoch == op.epoch {
if owned {
return Err("owner already issued this owned slot".into());
}
used = used.add(previous.cost)?;
}
}
if !owned {
let allocation = epoch.allocation;
let q = self.context.committee.quorum as i128;
let k = i128::from(self.context.committee.faults) + 1;
if used.rights.checked_mul(q).ok_or("owner budget overflow")?
> allocation
.rights
.checked_mul(k)
.ok_or("owner budget overflow")?
|| used
.headroom
.checked_mul(q)
.ok_or("owner budget overflow")?
> allocation
.headroom
.checked_mul(k)
.ok_or("owner budget overflow")?
{
return Err("issued owner batch exceeds concurrent envelope".into());
}
}
Ok(())
}
pub(crate) fn owner_rebase(&self, draft: &Act, epoch: &str) -> Result<Act> {
self.operation(draft)?;
let m = self.epoch(epoch)?;
let mut message = draft.message.clone();
fn replace(msg: &mut Message, epoch: &str, credits: &BTreeSet<String>) {
match msg {
Message::Wrapped { content, .. } => replace(content, epoch, credits),
Message::Dialect { inner, .. } => replace(inner, epoch, credits),
Message::Simple { params, .. } => {
for pair in params.chunks_exact_mut(2) {
match &pair[0] {
SExpr::Atom(Atom::Keyword(k)) if k == PREV => {
pair[1] = SExpr::Atom(Atom::Symbol(epoch.into()))
}
SExpr::Atom(Atom::Keyword(k)) if k == DEPS => {
pair[1] = SExpr::List(
credits
.iter()
.map(|id| SExpr::Atom(Atom::Symbol(id.clone())))
.collect(),
)
}
_ => (),
}
}
}
_ => (),
}
}
replace(&mut message, epoch, &m.credited);
let act = Act::from_message(message, &draft.signer)?;
self.operation(&act)?;
Ok(act)
}
pub(crate) fn owner_manifest(
&self,
account: &str,
issued: &BTreeSet<String>,
) -> Result<VersionManifest> {
let mut held = issued.clone();
for id in &self.state.signed {
if self.op(id)?.account == account {
held.insert(id.clone());
}
}
for id in &held {
if !self.has(VoteKind::Effects, id) && !self.has(VoteKind::Cancel, id) {
return Err("owner batch still draining".into());
}
}
let credits = self
.state
.operations
.iter()
.filter_map(|(id, op)| {
(op.credits.contains_key(account) && self.has(VoteKind::Effects, id))
.then_some(id.clone())
})
.collect();
let mut manifest = self.draft_version(
&BTreeSet::from([self.active_epoch(account)?.into()]),
&held,
&BTreeSet::new(),
&credits,
)?;
manifest.phase = VersionPhase::Owned;
Ok(manifest)
}
pub fn owned_root(&self, account: &str) -> Option<&str> {
self.state.owned.iter().find_map(|(id, request)| {
(request.version.manifest.account == account && self.has(VoteKind::OwnedSeal, id))
.then_some(id.as_str())
})
}
fn descends(&self, version: &str, root: &str) -> Result<bool> {
let mut todo = alloc::vec![version.to_string()];
let mut seen = BTreeSet::new();
while let Some(id) = todo.pop() {
if id == root {
return Ok(true);
}
if seen.insert(id.clone()) {
todo.extend(self.epoch(&id)?.parents.iter().cloned());
}
}
Ok(false)
}
fn check_owned<A: Authentication>(&self, request: &OwnedSealRequest, auth: &A) -> Result<()> {
let m = &request.version.manifest;
if m.phase != VersionPhase::Owned
|| self.context.ownership() != crate::escrow::Ownership::Account
{
return Err("collective pools cannot become owned accounts".into());
}
self.check_version(&request.version, auth)?;
self.verify_vote(
&request.authorization,
VoteKind::OwnedSealRequest,
&m.id(&self.context.id),
&m.account,
auth,
)?;
for id in &m.held {
if !self.has(VoteKind::Effects, id) && !self.has(VoteKind::Cancel, id) {
return Err("seal requires completely drained history".into());
}
}
Ok(())
}
fn allocation(&self, m: &VersionManifest) -> Result<Resources> {
let mut b = *self
.context
.initial
.get(&m.account)
.ok_or("unknown resource scope")?;
for id in &m.credited {
if !self.has(VoteKind::Effects, id) {
return Err("missing final credit certificate".into());
}
b = b.add(
*self
.op(id)?
.credits
.get(&m.account)
.ok_or("credit belongs to another account")?,
)?;
}
for id in &m.held {
let op = self.op(id)?;
if op.account != m.account {
return Err("held operation belongs to another account".into());
}
b = b.sub(op.cost)?;
}
for id in &m.refunded {
if !m.held.contains(id) || !self.has(VoteKind::Cancel, id) {
return Err("refund needs held operation and cancellation quorum".into());
}
b = b.add(self.op(id)?.cost)?;
}
if !b.nonnegative() {
return Err("negative version allocation".into());
}
Ok(b)
}
fn check_version_manifest(&self, m: &VersionManifest) -> Result<()> {
if (m.phase == VersionPhase::Owned
&& self.context.ownership() == crate::escrow::Ownership::Collective)
|| !self.context.initial.contains_key(&m.account)
|| m.parents.is_empty()
|| m.parents.len() > self.limits.versions.saturating_add(1)
|| m.held.len() > self.limits.operations
|| m.refunded.len() > self.limits.operations
|| m.credited.len() > self.limits.operations
{
return Err("invalid DAG pool, parent set or size limit".into());
}
for id in &m.parents {
let parent = self.epoch(id)?;
if (parent.phase == VersionPhase::Owned && m.phase != VersionPhase::Owned)
|| parent.account != m.account
|| parent.rank >= m.rank
|| !parent.held.is_subset(&m.held)
|| !parent.refunded.is_subset(&m.refunded)
|| !parent.credited.is_subset(&m.credited)
{
return Err("DAG parent rank or inherited sets mismatch".into());
}
}
for id in &m.held {
if self.epoch(&self.op(id)?.epoch)?.rank >= m.rank {
return Err("held transaction must precede DAG version rank".into());
}
}
if self.allocation(m)? != m.allocation {
return Err("DAG version allocation mismatch".into());
}
Ok(())
}
fn check_version<A: Authentication>(&self, v: &DagVersion, auth: &A) -> Result<()> {
self.check_version_manifest(&v.manifest)?;
if !self
.context
.version_actor(&v.manifest.account, &v.authorization.signer)
{
return Err("unauthorized DAG version actor".into());
}
self.verify_vote(
&v.authorization,
VoteKind::VersionRequest,
&v.manifest.id(&self.context.id),
&v.authorization.signer,
auth,
)
}
pub fn version(&self, id: &str) -> Option<&DagVersion> {
self.state.versions.get(id)
}
pub fn version_snapshot(&self, account: &str) -> Result<VersionSnapshot> {
let account = self.context.account(account)?;
let root = self.context.root_epoch(account)?;
let mut known: BTreeSet<_> = self
.state
.versions
.iter()
.filter(|(_, v)| v.manifest.account == account)
.map(|(id, _)| id.clone())
.collect();
known.insert(root);
let project = |ids: &BTreeSet<String>| {
ids.iter()
.filter(|id| {
self.state
.operations
.get(*id)
.is_some_and(|op| op.account == account)
})
.cloned()
.collect()
};
let visited = self
.state
.visited
.iter()
.filter(|id| self.epoch(id).is_ok_and(|m| m.account == account))
.cloned()
.collect();
Ok(VersionSnapshot {
permanent_seal: self.state.sealed.get(account).cloned(),
owned_root: self.owned_root(account).map(String::from),
active: self.active_epoch(account)?.into(),
known,
visited,
signed: project(&self.state.signed),
released: project(&self.state.released),
effects: project(&self.state.effects),
fences: project(&self.state.fences),
})
}
pub fn draft_version(
&self,
parents: &BTreeSet<String>,
held: &BTreeSet<String>,
refunds: &BTreeSet<String>,
credits: &BTreeSet<String>,
) -> Result<VersionManifest> {
if parents.is_empty()
|| parents.len() > self.limits.versions.saturating_add(1)
|| held.len() > self.limits.operations
|| refunds.len() > self.limits.operations
|| credits.len() > self.limits.operations
{
return Err("invalid DAG draft context or limits".into());
}
let mut m = VersionManifest {
phase: VersionPhase::Concurrent,
account: self
.epoch(parents.first().ok_or("empty parent set")?)?
.account
.clone(),
parents: parents.clone(),
rank: 0,
held: held.clone(),
refunded: refunds.clone(),
credited: credits.clone(),
allocation: Resources::default(),
};
for id in parents {
let p = self.epoch(id)?;
if p.phase == VersionPhase::Owned {
m.phase = VersionPhase::Owned;
}
m.rank = m.rank.max(p.rank);
m.held.extend(p.held.iter().cloned());
m.refunded.extend(p.refunded.iter().cloned());
m.credited.extend(p.credited.iter().cloned());
}
if m.held.len() > self.limits.operations
|| m.refunded.len() > self.limits.operations
|| m.credited.len() > self.limits.operations
{
return Err("cumulative DAG sets exceed limits".into());
}
for id in &m.held {
m.rank = m.rank.max(self.epoch(&self.op(id)?.epoch)?.rank);
}
m.rank = m.rank.checked_add(1).ok_or("DAG rank overflow")?;
m.allocation = self.allocation(&m)?;
self.check_version_manifest(&m)?;
Ok(m)
}
pub fn receive_version<J: Journal, A: Authentication>(
&mut self,
version: DagVersion,
journal: &mut J,
auth: &A,
) -> Result<()> {
self.commit(Event::Version(version), journal, auth)
}
pub fn adopt_version<J: Journal, A: Authentication>(
&mut self,
id: &str,
journal: &mut J,
auth: &A,
) -> Result<()> {
self.commit(Event::AdoptVersion(id.into()), journal, auth)
}
fn apply<A: Authentication>(&mut self, event: &Event, auth: &A) -> Result<()> {
if let Some(update) = self.prepare(event, auth)? {
self.apply_update(update);
}
Ok(())
}
fn prepare<A: Authentication>(&self, event: &Event, auth: &A) -> Result<Option<Update>> {
let update = match event {
Event::Initialize => return Err("duplicate initialization".into()),
Event::OwnedProposal(request) | Event::SealOwned(request) => {
self.check_owned(request, auth)?;
let m = &request.version.manifest;
let id = m.id(&self.context.id);
let seal = matches!(event, Event::SealOwned(_));
if let Some(root) = self.owned_root(&m.account) {
if root != id {
return Err("conflicting certified owned root".into());
}
}
if seal {
if let Some(old) = self.state.sealed.get(&m.account) {
if old != &id {
return Err("account permanently sealed to another root".into());
}
return Ok(None);
}
let current = self.state.active.get(&m.account).ok_or("unknown account")?;
if !m.parents.contains(current) {
return Err("seal must follow active parent".into());
}
for signed in &self.state.signed {
if self.op(signed)?.account == m.account && !m.held.contains(signed) {
return Err("seal omits historical signature".into());
}
}
} else if self.state.owned.contains_key(&id) {
return Ok(None);
}
if !self.state.owned.contains_key(&id)
&& self.state.owned.len() >= self.limits.versions
{
return Err("owned proposal limit reached".into());
}
if !self.state.versions.contains_key(&id)
&& self.state.versions.len() >= self.limits.versions
{
return Err("version limit reached; evidence retained".into());
}
Update::Owned(id, request.clone(), seal)
}
Event::Version(v) => {
self.check_version(v, auth)?;
let id = v.manifest.id(&self.context.id);
if self.state.versions.contains_key(&id) {
return Ok(None);
}
if self.state.versions.len() >= self.limits.versions {
return Err("version limit reached; evidence retained".into());
}
Update::Version(id, v.clone())
}
Event::AdoptVersion(id) => {
let v = self.state.versions.get(id).ok_or("unknown DAG version")?;
let m = &v.manifest;
let current = self.state.active.get(&m.account).ok_or("unknown pool")?;
if current == id {
return Ok(None);
}
if let Some(root) = self.owned_root(&m.account) {
if !self.descends(id, root)? && !self.descends(root, id)? {
return Err("adoption outside certified owned ancestry".into());
}
} else if m.phase == VersionPhase::Owned
|| self.state.sealed.contains_key(&m.account)
{
return Err("owned account awaits seal certificate".into());
}
if !m.parents.contains(current) {
return Err("adoption must follow a direct active parent".into());
}
for signed in &self.state.signed {
if self.op(signed)?.account == m.account && !m.held.contains(signed) {
return Err("DAG version omits historical signature".into());
}
}
Update::Adopt {
account: m.account.clone(),
id: id.clone(),
}
}
Event::Candidate(a) => {
let op = self.operation(a)?;
if !auth.authenticate_act(a) {
return Err("owner signature or protocol admission failed".into());
}
if let Some(old) = self.state.operations.get(&a.address) {
if *old != op {
return Err("conflicting act identity".into());
}
return Ok(None);
}
if self.state.operations.len() >= self.limits.operations {
return Err("operation limit reached; evidence retained".into());
}
Update::Candidate(a.address.clone(), op)
}
Event::Certificate(c) => {
if !matches!(
c.kind,
VoteKind::Operation
| VoteKind::Effects
| VoteKind::Cancel
| VoteKind::OwnedSeal
) {
return Err("unexpected certificate type".into());
}
if c.kind == VoteKind::OwnedSeal {
let request = self
.state
.owned
.get(&c.payload)
.ok_or("unknown owned proposal")?;
if let Some(root) = self.owned_root(&request.version.manifest.account) {
if root != c.payload {
return Err("conflicting certified owned root".into());
}
}
if let Some(root) = self.state.sealed.get(&request.version.manifest.account) {
if root != &c.payload {
return Err("certificate conflicts with permanent local seal".into());
}
}
} else {
self.op(&c.payload)?;
}
self.verify_certificate(c, c.kind, &c.payload, auth)?;
if c.kind == VoteKind::Effects {
if !self.has(VoteKind::Operation, &c.payload) {
return Err("effects require operation certificate".into());
}
if self.has(VoteKind::Cancel, &c.payload) {
return Err(
"conflicting genuine effects and cancellation certificates".into()
);
}
}
if c.kind == VoteKind::Cancel && self.has(VoteKind::Effects, &c.payload) {
return Err("conflicting genuine cancellation and effects certificates".into());
}
if self.has(c.kind, &c.payload) {
return Ok(None);
}
Update::Certificate((c.kind, c.payload.clone()), c.clone())
}
Event::Sign(id) => {
if self.state.signed.contains(id) {
return Ok(None);
}
let charge = self.budget(id)?;
Update::Sign {
id: id.clone(),
epoch: self.op(id)?.epoch.clone(),
charge,
}
}
Event::Effect(id) => {
if self.state.effects.contains(id) {
return Ok(None);
}
self.op(id)?;
if self.state.fences.contains(id) || !self.has(VoteKind::Operation, id) {
return Err("effects fenced or missing operation certificate".into());
}
Update::Effect(id.clone())
}
Event::Fence(v) => {
let op = self.op(&v.payload)?;
if let Some(root) = self.owned_root(&op.account) {
if self.descends(&op.epoch, root)? {
return Err("owned operations cannot be cancelled".into());
}
}
self.verify_vote(v, VoteKind::CancelRequest, &v.payload, &op.act.signer, auth)?;
if self.state.effects.contains(&v.payload) {
return Err("validator already signed effects".into());
}
if self.state.fences.contains(&v.payload) {
return Ok(None);
}
Update::Fence(v.payload.clone())
}
Event::Release(id) => {
if !self.state.signed.contains(id) || !self.has(VoteKind::Cancel, id) {
return Err("release requires own charge and cancellation quorum".into());
}
if self.state.released.contains(id) {
return Ok(None);
}
let op = self.op(id)?;
if self.owner_epoch_is_owned(&op.account, &op.epoch)? {
return Err("owned operations cannot release slots".into());
}
let charge = self
.state
.charges
.get(&op.epoch)
.copied()
.unwrap_or_default()
.sub(op.cost)?;
if !charge.nonnegative() {
return Err("inconsistent derived charge".into());
}
Update::Release {
id: id.clone(),
epoch: op.epoch.clone(),
charge,
}
}
};
Ok(Some(update))
}
fn apply_update(&mut self, update: Update) {
match update {
Update::Owned(id, request, seal) => {
if seal {
self.state
.sealed
.insert(request.version.manifest.account.clone(), id.clone());
}
self.state
.versions
.insert(id.clone(), request.version.clone());
self.state.owned.insert(id, request);
}
Update::Candidate(id, op) => {
self.state.operations.insert(id, op);
}
Update::Certificate(key, certificate) => {
self.state.certificates.insert(key, certificate);
}
Update::Version(id, version) => {
self.state.versions.insert(id, version);
}
Update::Adopt { account, id } => {
self.state.active.insert(account, id.clone());
self.state.visited.insert(id);
}
Update::Sign { id, epoch, charge } => {
self.state.signed.insert(id);
self.state.charges.insert(epoch, charge);
}
Update::Effect(id) => {
self.state.effects.insert(id);
}
Update::Fence(id) => {
self.state.fences.insert(id);
}
Update::Release { id, epoch, charge } => {
self.state.released.insert(id);
self.state.charges.insert(epoch, charge);
}
}
#[cfg(debug_assertions)]
self.assert_charge_cache();
}
#[cfg(debug_assertions)]
fn assert_charge_cache(&self) {
let mut expected: BTreeMap<String, Resources> = BTreeMap::new();
for id in &self.state.signed {
let op = self
.state
.operations
.get(id)
.expect("signed candidate retained");
let total = expected.entry(op.epoch.clone()).or_default();
if !self.state.released.contains(id) {
*total = total
.add(op.cost)
.expect("reachable historical charge fits");
}
}
debug_assert_eq!(
self.state.charges, expected,
"derived charge differs from signed history"
);
}
pub fn record_owned_proposal<J: Journal, A: Authentication>(
&mut self,
request: OwnedSealRequest,
journal: &mut J,
auth: &A,
) -> Result<()> {
self.commit(Event::OwnedProposal(request), journal, auth)
}
pub fn prepare_owned_seal<J: Journal, A: Authentication>(
&mut self,
request: OwnedSealRequest,
journal: &mut J,
auth: &A,
) -> Result<SigningRequest> {
let id = request.version.manifest.id(&self.context.id);
self.commit(Event::SealOwned(request), journal, auth)?;
Ok(self
.context
.request(VoteKind::OwnedSeal, &id, &self.validator))
}
pub fn register<J: Journal, A: Authentication>(
&mut self,
act: Act,
j: &mut J,
a: &A,
) -> Result<()> {
self.commit(Event::Candidate(act), j, a)
}
pub fn receive<J: Journal, A: Authentication>(
&mut self,
c: Certificate,
j: &mut J,
a: &A,
) -> Result<()> {
self.commit(Event::Certificate(c), j, a)
}
pub fn prepare_operation<J: Journal, A: Authentication>(
&mut self,
id: &str,
j: &mut J,
a: &A,
) -> Result<SigningRequest> {
self.commit(Event::Sign(id.into()), j, a)?;
Ok(self
.context
.request(VoteKind::Operation, id, &self.validator))
}
pub fn prepare_effects<J: Journal, A: Authentication>(
&mut self,
id: &str,
j: &mut J,
a: &A,
) -> Result<SigningRequest> {
self.commit(Event::Effect(id.into()), j, a)?;
Ok(self.context.request(VoteKind::Effects, id, &self.validator))
}
pub fn prepare_cancel<J: Journal, A: Authentication>(
&mut self,
request: Vote,
j: &mut J,
a: &A,
) -> Result<SigningRequest> {
let id = request.payload.clone();
self.commit(Event::Fence(request), j, a)?;
Ok(self.context.request(VoteKind::Cancel, &id, &self.validator))
}
pub fn release<J: Journal, A: Authentication>(
&mut self,
id: &str,
j: &mut J,
a: &A,
) -> Result<()> {
self.commit(Event::Release(id.into()), j, a)
}
pub fn active_epoch(&self, account: &str) -> Result<&str> {
let account = self.context.account(account)?;
self.state
.active
.get(account)
.map(String::as_str)
.ok_or_else(|| "unknown account".into())
}
pub fn finalized_view(&self) -> Result<FinalizedView> {
let mut balances = self.context.initial.clone();
let mut finalized = BTreeSet::new();
let mut pending = BTreeSet::new();
for (kind, id) in self.state.certificates.keys() {
if *kind == VoteKind::Effects {
finalized.insert(id.clone());
} else if *kind == VoteKind::Operation
&& !self.has(VoteKind::Cancel, id)
&& !self.has(VoteKind::Effects, id)
{
pending.insert(id.clone());
}
}
for id in &finalized {
let op = self.op(id)?;
let owner = balances.get_mut(&op.account).ok_or("unknown owner")?;
*owner = owner.sub(op.cost)?;
for (a, credit) in &op.credits {
let b = balances.get_mut(a).ok_or("unknown recipient")?;
*b = b.add(*credit)?;
}
}
if balances.values().any(|b| !b.nonnegative()) {
return Err("inconsistent final evidence violates resource bounds".into());
}
let rights: BTreeMap<_, _> = balances
.iter()
.map(|(a, b)| (a.clone(), b.rights))
.collect();
let value = rights
.values()
.try_fold(i128::from(self.context.rule.floor), |s, n| {
s.checked_add(*n).ok_or("balance overflow")
})?;
if self
.context
.rule
.ceiling
.is_some_and(|cap| value > i128::from(cap))
{
return Err("final evidence exceeds ceiling".into());
}
Ok(FinalizedView {
ownership: self.context.rule.ownership,
context: self.context.id.clone(),
evidence_digest: digest(alloc::vec![
text("cbcl/final-view/v1"),
text(&self.context.id),
super::types::strings(&finalized)
]),
rights,
headroom: self.context.rule.ceiling.map(|_| {
balances
.iter()
.map(|(a, b)| (a.clone(), b.headroom))
.collect()
}),
value,
finalized,
pending,
})
}
pub fn intend(
&self,
inst: &Instance,
owner: &AgentKey,
verb: &str,
fields: BTreeMap<String, SExpr>,
nonce: &str,
) -> core::result::Result<Message, Reject> {
let bound = Instance::new(inst.dialect, inst.thread.clone(), inst.acts)
.map_err(Reject::Resource)?;
crate::intend::intend_certified(&bound, owner, verb, fields, self, nonce)
}
pub(crate) fn bind_authoring<'a, 'd>(
&'a self,
instance: &'a Instance<'d>,
) -> Result<BoundAuthoring<'a, 'd>> {
if !self.context.matches(instance) {
return Err("runtime does not match instance or counter verb".into());
}
Ok(BoundAuthoring {
replica: self,
instance,
})
}
pub fn fold_instance(&self, inst: &Instance) -> Result<Vec<(String, Value)>> {
if !self.context.matches(inst) {
return Err("runtime instance mismatch".into());
}
let mut folded = crate::escrow::fold_instance(inst.dialect, &inst.thread.0, inst.acts);
let field = folded
.iter_mut()
.find(|(name, _)| *name == self.context.field)
.ok_or("missing resource field")?;
field.1 = self.finalized_view()?.value();
Ok(folded)
}
}
fn bounded_message(message: &Message, limit: usize) -> Result<()> {
use crate::message::{CausedBy, Recipients};
let mut total = 0usize;
let mut charge = |n: usize| -> Result<()> {
total = total.checked_add(n).ok_or("object size overflow")?;
if total > limit {
return Err("operation object limit exceeded".into());
}
Ok(())
};
let mut msg = message;
let mut expressions = Vec::new();
for depth in 0..=64 {
charge(16)?;
match msg {
Message::Dialect {
dialect_name,
inner,
} => {
charge(dialect_name.len())?;
msg = inner;
}
Message::Wrapped {
params, content, ..
} => {
if params.len() > limit {
return Err("wrapper size limit exceeded".into());
}
expressions.extend(params.iter().map(|s| (s, depth + 1)));
msg = content;
}
Message::Simple {
performative,
recipient,
content,
params,
thread,
sender,
caused_by,
} => {
charge(performative.name().len())?;
if let Some(r) = recipient {
match r {
Recipients::One(k) => charge(k.len())?,
Recipients::Set(ks) => {
if ks.len() > limit {
return Err("recipient limit exceeded".into());
}
for k in ks {
charge(k.len() + 1)?;
}
}
}
}
if let Some(t) = thread {
charge(t.len())?;
}
if let Some(s) = sender {
charge(s.len())?;
}
match caused_by {
Some(CausedBy::Single(s)) => charge(s.len())?,
Some(CausedBy::Multiple(xs)) => {
if xs.len() > limit {
return Err("cause limit exceeded".into());
}
for x in xs {
charge(x.len() + 1)?;
}
}
_ => {}
}
if params.len() > limit {
return Err("parameter limit exceeded".into());
}
expressions.push((content, depth + 1));
expressions.extend(params.iter().map(|s| (s, depth + 1)));
break;
}
Message::Meta { .. } => {
return Err("resource candidate cannot be a meta message".into())
}
}
if depth == 64 {
return Err("message nesting limit exceeded".into());
}
}
while let Some((s, depth)) = expressions.pop() {
if depth > 64 {
return Err("S-expression nesting limit exceeded".into());
}
charge(16)?;
match s {
SExpr::Atom(Atom::Symbol(s) | Atom::Keyword(s) | Atom::Str(s)) => charge(s.len())?,
SExpr::Atom(_) => {}
SExpr::List(xs) => {
if xs.len() > limit {
return Err("list limit exceeded".into());
}
expressions.extend(xs.iter().map(|s| (s, depth + 1)));
}
}
}
Ok(())
}
pub(crate) struct BoundAuthoring<'a, 'd> {
replica: &'a Replica,
instance: &'a Instance<'d>,
}
impl<'d> BoundAuthoring<'_, 'd> {
pub(crate) fn instance(&self) -> &Instance<'d> {
self.instance
}
pub(crate) fn bookkeeping(
&self,
owner: &str,
verb: &str,
nonce: &str,
) -> Result<Vec<(String, SExpr)>> {
if !self.replica.context.rule.operation_verbs().contains(&verb) {
return Err("runtime does not match instance or counter verb".into());
}
if nonce.is_empty() || nonce.len() > 256 {
return Err("nonce must contain 1..256 bytes".into());
}
let epoch = self.replica.active_epoch(owner)?;
let m = self.replica.epoch(epoch)?;
Ok(alloc::vec![
(PREV.into(), SExpr::Atom(Atom::Symbol(epoch.into()))),
(
DEPS.into(),
SExpr::List(
m.credited
.iter()
.map(|s| SExpr::Atom(Atom::Symbol(s.clone())))
.collect()
)
),
(NONCE.into(), SExpr::Atom(Atom::Str(nonce.into())))
])
}
pub(crate) fn check_candidate(&self, candidate: &Act) -> Result<()> {
self.replica.operation(candidate)?;
Ok(())
}
}