Skip to main content

cbcl_core/quorum/
engine.rs

1use super::types::{digest, text, Operation};
2use super::*;
3use crate::{
4    escrow::{DEPS, NONCE, PREV},
5    intend::{Instance, Reject},
6    message::Message,
7    role::AgentKey,
8    sexpr::{Atom, SExpr},
9    state::{Act, Value},
10};
11use alloc::{
12    collections::{BTreeMap, BTreeSet},
13    string::{String, ToString},
14    vec::Vec,
15};
16
17#[derive(Debug, Default)]
18struct State {
19    operations: BTreeMap<String, Operation>,
20    owned: BTreeMap<String, OwnedSealRequest>,
21    sealed: BTreeMap<String, String>,
22    certificates: BTreeMap<(VoteKind, String), Certificate>,
23    versions: BTreeMap<String, DagVersion>,
24    visited: BTreeSet<String>,
25    signed: BTreeSet<String>,
26    effects: BTreeSet<String>,
27    fences: BTreeSet<String>,
28    released: BTreeSet<String>,
29    active: BTreeMap<String, String>,
30    // Derived from immutable signed/released history; never loaded from a snapshot.
31    charges: BTreeMap<String, Resources>,
32}
33/// Owned, already-validated changes. No protocol checks may fail during application.
34/// This is transient preparation, never serialized or accepted as journal input.
35#[derive(Clone)]
36enum Update {
37    Candidate(String, Operation),
38    Owned(String, OwnedSealRequest, bool),
39    Certificate((VoteKind, String), Certificate),
40    Version(String, DagVersion),
41    Adopt {
42        account: String,
43        id: String,
44    },
45    Sign {
46        id: String,
47        epoch: String,
48        charge: Resources,
49    },
50    Effect(String),
51    Fence(String),
52    Release {
53        id: String,
54        epoch: String,
55        charge: Resources,
56    },
57}
58/// One validator's independent state machine. Each mutation is journaled before
59/// exposing a decision to the signer. There is no shared reservation authority.
60pub struct Replica {
61    context: Context,
62    validator: String,
63    limits: Limits,
64    sequence: u64,
65    state: State,
66}
67// Only touched entries are saved. No retained-history clone is needed.
68enum GroupUndo {
69    Candidate(String),
70    Certificate((VoteKind, String)),
71    Sign {
72        id: String,
73        epoch: String,
74        charge: Option<Resources>,
75    },
76    Effect(String),
77}
78struct GroupPreparation<'a> {
79    replica: &'a mut Replica,
80    sequence: u64,
81    undo: Vec<GroupUndo>,
82}
83impl Drop for GroupPreparation<'_> {
84    fn drop(&mut self) {
85        for undo in self.undo.drain(..).rev() {
86            match undo {
87                GroupUndo::Candidate(id) => {
88                    self.replica.state.operations.remove(&id);
89                }
90                GroupUndo::Certificate(key) => {
91                    self.replica.state.certificates.remove(&key);
92                }
93                GroupUndo::Sign { id, epoch, charge } => {
94                    self.replica.state.signed.remove(&id);
95                    match charge {
96                        Some(old) => {
97                            self.replica.state.charges.insert(epoch, old);
98                        }
99                        None => {
100                            self.replica.state.charges.remove(&epoch);
101                        }
102                    }
103                }
104                GroupUndo::Effect(id) => {
105                    self.replica.state.effects.remove(&id);
106                }
107            }
108        }
109        self.replica.sequence = self.sequence;
110    }
111}
112impl Replica {
113    /// Validate a bounded group using the ordinary guards, then persist it with
114    /// one durability barrier. No signing request escapes before that barrier.
115    /// On validation/CAS failure state is unchanged. Retries emit no log event.
116    /// Only candidate/certificate/sign/effect transitions are supported; DAG
117    /// adoption, cancellation fencing and release retain their serial API.
118    pub fn commit_group<J: BatchJournal, A: Authentication>(
119        &mut self,
120        events: &[Event],
121        journal: &mut J,
122        auth: &A,
123    ) -> Result<Vec<Option<SigningRequest>>> {
124        if events.len() > 256 {
125            return Err("group exceeds 256 events".into());
126        }
127        let mut durable = Vec::new();
128        let mut updates = Vec::new();
129        {
130            let sequence = self.sequence;
131            let plan = GroupPreparation {
132                replica: self,
133                sequence,
134                undo: Vec::new(),
135            };
136            let mut plan = plan;
137            for event in events {
138                if !matches!(
139                    event,
140                    Event::Candidate(_) | Event::Certificate(_) | Event::Sign(_) | Event::Effect(_)
141                ) {
142                    return Err("unsupported group transition".into());
143                }
144                let Some(update) = plan.replica.prepare(event, auth)? else {
145                    continue;
146                };
147                if plan.replica.sequence >= plan.replica.limits.events {
148                    return Err("journal limit reached; evidence retained".into());
149                }
150                let undo = match &update {
151                    Update::Candidate(id, _) => GroupUndo::Candidate(id.clone()),
152                    Update::Certificate(key, _) => GroupUndo::Certificate(key.clone()),
153                    Update::Sign { id, epoch, .. } => GroupUndo::Sign {
154                        id: id.clone(),
155                        epoch: epoch.clone(),
156                        charge: plan.replica.state.charges.get(epoch).copied(),
157                    },
158                    Update::Effect(id) => GroupUndo::Effect(id.clone()),
159                    _ => unreachable!("group transition checked"),
160                };
161                plan.undo.push(undo);
162                plan.replica.apply_update(update.clone());
163                plan.replica.sequence += 1;
164                durable.push(event.clone());
165                updates.push(update);
166            }
167        } // Roll back staging on success, rejection and unwinding alike.
168        if !durable.is_empty() {
169            journal.append_batch(&self.context.id, &self.validator, self.sequence, &durable)?;
170            for update in updates {
171                self.apply_update(update);
172                self.sequence += 1;
173            }
174        }
175        Ok(events
176            .iter()
177            .map(|event| match event {
178                Event::Sign(id) => Some(self.context.request(
179                    VoteKind::Operation,
180                    id,
181                    &self.validator,
182                )),
183                Event::Effect(id) => {
184                    Some(self.context.request(VoteKind::Effects, id, &self.validator))
185                }
186                _ => None,
187            })
188            .collect())
189    }
190    /// Creates a log exactly once. An existing identity must use `recover`.
191    pub fn initialize<J: Journal>(
192        context: Context,
193        validator: &str,
194        limits: Limits,
195        journal: &mut J,
196    ) -> Result<Self> {
197        if !context.committee.contains(validator) {
198            return Err("validator outside committee".into());
199        }
200        if journal.load(&context.id, validator)?.is_some() {
201            return Err("journal exists: recover it".into());
202        }
203        if limits.events == 0 {
204            return Err("event limit is zero".into());
205        }
206        journal.append(&context.id, validator, None, &Event::Initialize)?;
207        let mut state = State::default();
208        for a in context.initial.keys() {
209            let root = context.root_epoch(a)?;
210            state.visited.insert(root.clone());
211            state.active.insert(a.clone(), root);
212        }
213        Ok(Self {
214            context,
215            validator: validator.into(),
216            limits,
217            sequence: 1,
218            state,
219        })
220    }
221    pub fn recover<J: Journal, A: Authentication>(
222        context: Context,
223        validator: &str,
224        limits: Limits,
225        journal: &J,
226        auth: &A,
227    ) -> Result<Self> {
228        if !context.committee.contains(validator) {
229            return Err("validator outside committee".into());
230        }
231        let events = journal
232            .load(&context.id, validator)?
233            .ok_or("missing journal; initialize explicitly")?;
234        if events.first() != Some(&Event::Initialize) || events.len() as u64 > limits.events {
235            return Err("invalid or oversized journal".into());
236        }
237        let mut state = State::default();
238        for a in context.initial.keys() {
239            let root = context.root_epoch(a)?;
240            state.visited.insert(root.clone());
241            state.active.insert(a.clone(), root);
242        }
243        let mut r = Self {
244            context,
245            validator: validator.into(),
246            limits,
247            sequence: 1,
248            state,
249        };
250        for e in events.into_iter().skip(1) {
251            r.apply(&e, auth)?;
252            r.sequence += 1;
253        }
254        Ok(r)
255    }
256    /// Plan a finite forward path; validate coverage at every NEW node before IO.
257    /// The starting current node need not hold signatures made in its own slot.
258    fn owned_adoption_path(&self, target: &str) -> Result<Vec<String>> {
259        let manifest = self.epoch(target)?;
260        if manifest.phase != VersionPhase::Owned {
261            return Ok(Vec::new());
262        }
263        let root = self
264            .owned_root(&manifest.account)
265            .ok_or("catch-up awaits owned-root QC")?;
266        if !self.descends(target, root)? {
267            return Err("catch-up target outside owned root".into());
268        }
269        self.adoption_path(target, Some(root))
270    }
271    fn adoption_path(&self, target: &str, boundary: Option<&str>) -> Result<Vec<String>> {
272        let manifest = self.epoch(target)?;
273        let current = self.active_epoch(&manifest.account)?;
274        if current == target {
275            return Ok(Vec::new());
276        }
277        let mut todo = alloc::vec![target.to_string()];
278        let mut seen = BTreeSet::from([target.to_string()]);
279        let mut forward = BTreeMap::new();
280        let mut found = false;
281        while let Some(id) = todo.pop() {
282            if id == current {
283                found = true;
284                break;
285            }
286            let node = self.epoch(&id)?;
287            if let Some(root) = boundary {
288                if !self.descends(&id, root)? && !self.descends(root, &id)? {
289                    continue;
290                }
291            } else if node.phase == VersionPhase::Owned
292                && self.owned_root(&manifest.account).is_none()
293            {
294                continue;
295            }
296            // A multi-parent DAG can offer an incompatible first branch. Skip
297            // it and search another path; never let arrival/hash order strand
298            // a validator when a covering path exists.
299            if self.state.signed.iter().any(|signed| {
300                self.state.operations[signed].account == manifest.account
301                    && !node.held.contains(signed)
302            }) {
303                continue;
304            }
305            for parent in &node.parents {
306                if seen.insert(parent.clone()) {
307                    forward.insert(parent.clone(), id.clone());
308                    todo.push(parent.clone());
309                }
310            }
311        }
312        if !found {
313            return Err("catch-up target is not a descendant of current version".into());
314        }
315        let mut path = Vec::new();
316        let mut cursor = current.to_string();
317        while cursor != target {
318            let next = forward.get(&cursor).ok_or("broken catch-up path")?;
319            let node = self.epoch(next)?;
320            if let Some(root) = boundary {
321                if !self.descends(next, root)? && !self.descends(root, next)? {
322                    return Err("catch-up node is outside certified root ancestry".into());
323                }
324            } else if node.phase == VersionPhase::Owned
325                && self.owned_root(&manifest.account).is_none()
326            {
327                return Err("catch-up awaits owned-root QC".into());
328            }
329            for signed in &self.state.signed {
330                if self.op(signed)?.account == manifest.account && !node.held.contains(signed) {
331                    return Err("catch-up node omits historical signature".into());
332                }
333            }
334            path.push(next.clone());
335            cursor = next.clone();
336        }
337        Ok(path)
338    }
339    /// Apply ordinary adoption events, retaining durable prefix progress on IO
340    /// failure. This is a retryable multi-event service, not an atomic transaction.
341    pub fn catch_up_owned<J: Journal, A: Authentication>(
342        &mut self,
343        target: &str,
344        journal: &mut J,
345        auth: &A,
346    ) -> Result<()> {
347        let path = self.owned_adoption_path(target)?;
348        for id in path {
349            self.adopt_version(&id, journal, auth)?;
350        }
351        Ok(())
352    }
353
354    /// Export the transitive verified dependency closure, deduplicated by identity.
355    /// Host transport must attach each Act's actual authentication envelope.
356    pub fn publication(&self, act: &Act) -> Result<Publication> {
357        self.operation(act)?;
358        Ok(Publication {
359            act: act.clone(),
360            evidence: self.relay_evidence(
361                Some(act),
362                alloc::vec![act.address.clone()],
363                Vec::new(),
364            )?,
365        })
366    }
367    /// Old holds/credits and their transitive ancestry are also required at seal.
368    pub fn seal_evidence(&self, manifest: &VersionManifest) -> Result<Vec<RelayItem>> {
369        self.check_version_manifest(manifest)?;
370        self.relay_evidence(
371            None,
372            manifest.held.union(&manifest.credited).cloned().collect(),
373            manifest.parents.iter().cloned().collect(),
374        )
375    }
376    fn relay_evidence(
377        &self,
378        target: Option<&Act>,
379        mut operations: Vec<String>,
380        mut versions: Vec<String>,
381    ) -> Result<Vec<RelayItem>> {
382        let mut seen_ops = BTreeSet::new();
383        let mut seen_versions = BTreeSet::new();
384        let mut seen_roots = BTreeSet::new();
385        let mut evidence = Vec::new();
386        while !operations.is_empty() || !versions.is_empty() {
387            while let Some(id) = operations.pop() {
388                if !seen_ops.insert(id.clone()) {
389                    continue;
390                }
391                let candidate = match target.filter(|act| id == act.address) {
392                    Some(act) => act,
393                    None => self.operation_act(&id).ok_or("missing relay operation")?,
394                };
395                let op = self.operation(candidate)?;
396                versions.push(op.epoch);
397                evidence.push(RelayItem::Act(candidate.clone()));
398                for kind in [VoteKind::Operation, VoteKind::Effects, VoteKind::Cancel] {
399                    if let Some(cert) = self.certificate(kind, &id) {
400                        evidence.push(RelayItem::Certificate(cert.clone()));
401                    }
402                }
403            }
404            if let Some(id) = versions.pop() {
405                if !seen_versions.insert(id.clone()) {
406                    continue;
407                }
408                let manifest = self.epoch(&id)?;
409                let Some(version) = self.version(&id) else {
410                    continue;
411                }; // pinned genesis
412                evidence.push(RelayItem::Version(version.clone()));
413                versions.extend(manifest.parents.iter().cloned());
414                operations.extend(manifest.held.iter().cloned());
415                operations.extend(manifest.credited.iter().cloned());
416                operations.extend(manifest.refunded.iter().cloned());
417                if manifest.phase == VersionPhase::Owned {
418                    let root = self
419                        .owned_root(&manifest.account)
420                        .ok_or("missing relay owned-root QC")?;
421                    if !self.descends(&id, root)? {
422                        return Err("relay target is outside owned root".into());
423                    }
424                    if seen_roots.insert(root.to_string()) {
425                        evidence.push(RelayItem::Owned(self.state.owned[root].clone()));
426                        evidence.push(RelayItem::Certificate(
427                            self.certificate(VoteKind::OwnedSeal, root)
428                                .ok_or("missing seal QC")?
429                                .clone(),
430                        ));
431                        versions.push(root.to_string());
432                    }
433                }
434            }
435        }
436        Ok(evidence)
437    }
438    fn bound_relay_act(&self, act: &Act) -> Result<()> {
439        if act.signer.len() > self.limits.object_bytes
440            || act.address.len() > self.limits.object_bytes
441            || act.verb.len() > self.limits.object_bytes
442        {
443            return Err("relay act header limit exceeded".into());
444        }
445        bounded_message(&act.message, self.limits.object_bytes)?;
446        self.context.structural(act)
447    }
448    fn bound_relay_vote(&self, vote: &Vote) -> Result<()> {
449        if vote.signature.len() > self.limits.signature_bytes
450            || vote.context != self.context.id
451            || vote.payload.len() > crate::multihash::TEXT_LEN
452        {
453            return Err("relay vote domain or signature limit exceeded".into());
454        }
455        // Key names are bounded by the initialized roster, not by the unrelated
456        // Act byte limit. Crypto signature size has its own native limit.
457        if !self.context.actors.contains(&vote.signer)
458            && !self.context.committee.contains(&vote.signer)
459        {
460            return Err("unknown relay signing identity".into());
461        }
462        Ok(())
463    }
464    fn bound_relay_version(&self, version: &DagVersion) -> Result<()> {
465        let m = &version.manifest;
466        if !self.context.initial.contains_key(&m.account)
467            || m.parents.len() > self.limits.versions.saturating_add(1)
468            || m.held.len() > self.limits.operations
469            || m.refunded.len() > self.limits.operations
470            || m.credited.len() > self.limits.operations
471        {
472            return Err("relay manifest scope or count limit exceeded".into());
473        }
474        // Act/version identity functions emit canonical multihash IDs.
475        // Match ordinary collection bounds; do not impose a new aggregate-byte
476        // ceiling that could strand already admitted cumulative metadata.
477        for ids in [&m.parents, &m.held, &m.refunded, &m.credited] {
478            if ids.iter().any(|id| id.len() > crate::multihash::TEXT_LEN) {
479                return Err("relay identifier limit exceeded".into());
480            }
481        }
482        self.bound_relay_vote(&version.authorization)
483    }
484    fn bound_seal_request(&self, request: &OwnedSealRequest) -> Result<()> {
485        self.bound_relay_version(&request.version)?;
486        self.bound_relay_vote(&request.authorization)
487    }
488    fn bound_relay_item(&self, item: &RelayItem) -> Result<()> {
489        match item {
490            RelayItem::Act(act) => self.bound_relay_act(act),
491            RelayItem::Version(v) => self.bound_relay_version(v),
492            RelayItem::Owned(r) => self.bound_seal_request(r),
493            RelayItem::Certificate(c) => {
494                if c.votes.len() > self.context.committee.validators.len()
495                    || c.payload.len() > crate::multihash::TEXT_LEN
496                {
497                    return Err("relay certificate count or payload limit exceeded".into());
498                }
499                for v in &c.votes {
500                    self.bound_relay_vote(v)?;
501                }
502                Ok(())
503            }
504        }
505    }
506    fn relay_item_bound(&self) -> usize {
507        self.limits
508            .operations
509            .saturating_mul(4)
510            .saturating_add(self.limits.versions.saturating_mul(3))
511            .saturating_add(1)
512    }
513    /// Seal preparation uses the same retry closure; a lagging honest validator
514    /// must not need a Byzantine sender to supply the old effects certificates.
515    pub fn prepare_seal_publication<J: Journal, A: Authentication>(
516        &mut self,
517        publication: &SealPublication,
518        journal: &mut J,
519        auth: &A,
520    ) -> Result<PublicationResult> {
521        self.bound_seal_request(&publication.request)?;
522        if publication.evidence.len() > self.relay_item_bound() {
523            return Err("seal evidence limit exceeded".into());
524        }
525        let (pending, reasons) = self.import_relay_items(&publication.evidence, journal, auth)?;
526        let id = publication.request.version.manifest.id(&self.context.id);
527        if let Some(cert) = self.certificate(VoteKind::OwnedSeal, &id) {
528            self.check_owned(&publication.request, auth)?;
529            let mut evidence = self.seal_evidence(&publication.request.version.manifest)?;
530            evidence.push(RelayItem::Owned(publication.request.clone()));
531            evidence.push(RelayItem::Certificate(cert.clone()));
532            return Ok(PublicationResult::Finalized {
533                certificate: cert.clone(),
534                evidence,
535            });
536        }
537        if !pending.is_empty() {
538            return Ok(PublicationResult::Pending {
539                items: pending,
540                reasons,
541            });
542        }
543        self.check_owned(&publication.request, auth)?;
544        let manifest = &publication.request.version.manifest;
545        let current = self.active_epoch(&manifest.account)?.to_string();
546        if !manifest.parents.contains(&current)
547            && !self.state.sealed.contains_key(&manifest.account)
548        {
549            let path = manifest.parents.iter().find_map(|parent| {
550                self.adoption_path(parent, self.owned_root(&manifest.account))
551                    .ok()
552            });
553            let Some(path) = path else {
554                return Ok(PublicationResult::Pending {
555                    items: Vec::new(),
556                    reasons: alloc::vec!["seal parent catch-up needs compatible ancestry".into()],
557                });
558            };
559            for id in path {
560                self.adopt_version(&id, journal, auth)?;
561            }
562        }
563        match self.prepare(&Event::SealOwned(publication.request.clone()), auth) {
564            Err(reason) => Ok(PublicationResult::Pending {
565                items: Vec::new(),
566                reasons: alloc::vec![reason],
567            }),
568            Ok(_) => Ok(PublicationResult::Seal(self.prepare_owned_seal(
569                publication.request.clone(),
570                journal,
571                auth,
572            )?)),
573        }
574    }
575    fn import_relay_items<J: Journal, A: Authentication>(
576        &mut self,
577        items: &[RelayItem],
578        journal: &mut J,
579        auth: &A,
580    ) -> Result<(Vec<RelayItem>, Vec<String>)> {
581        let bound = self
582            .limits
583            .operations
584            .saturating_mul(4)
585            .saturating_add(self.limits.versions.saturating_mul(3))
586            .saturating_add(2);
587        if items.len() > bound {
588            return Err("publication evidence limit exceeded".into());
589        }
590        for item in items {
591            self.bound_relay_item(item)?;
592        }
593        let mut pending = items.to_vec();
594        let mut reasons;
595        loop {
596            let before = pending.len();
597            let mut deferred = Vec::new();
598            reasons = Vec::new();
599            for item in pending {
600                let event = match &item {
601                    RelayItem::Act(a) => Event::Candidate(a.clone()),
602                    RelayItem::Version(v) => Event::Version(v.clone()),
603                    RelayItem::Owned(r) => Event::OwnedProposal(r.clone()),
604                    RelayItem::Certificate(c) => Event::Certificate(c.clone()),
605                };
606                match self.prepare(&event, auth) {
607                    Err(reason) => {
608                        reasons.push(reason);
609                        deferred.push(item);
610                    }
611                    Ok(_) => self.commit(event, journal, auth)?,
612                }
613            }
614            pending = deferred;
615            if pending.is_empty() || pending.len() == before {
616                break;
617            }
618        }
619        Ok((pending, reasons))
620    }
621    /// Import peer-retained proofs without making any local voting decision.
622    /// This is also the owner-side path for feedback certificates. Individual
623    /// accepted journal events remain durable if a later append fails.
624    pub fn receive_evidence<J: Journal, A: Authentication>(
625        &mut self,
626        items: &[RelayItem],
627        journal: &mut J,
628        auth: &A,
629    ) -> Result<RelayReport> {
630        let (pending, reasons) = self.import_relay_items(items, journal, auth)?;
631        Ok(RelayReport { pending, reasons })
632    }
633    /// Retry public evidence to a finite fixed point, using ordinary guards and
634    /// individually atomic journal events. Accepted prefix progress survives errors.
635    /// No signing request escapes a failed journal append. Pending is not success.
636    pub fn prepare_publication<J: Journal, A: Authentication>(
637        &mut self,
638        publication: &Publication,
639        journal: &mut J,
640        auth: &A,
641    ) -> Result<PublicationResult> {
642        self.bound_relay_act(&publication.act)?;
643        if !auth.authenticate_act(&publication.act) {
644            return Err("publication target authentication failed".into());
645        }
646        if publication.evidence.len() > self.relay_item_bound() {
647            return Err("publication evidence limit exceeded".into());
648        }
649        for item in &publication.evidence {
650            self.bound_relay_item(item)?;
651        }
652        let mut items = publication.evidence.clone();
653        items.push(RelayItem::Act(publication.act.clone()));
654        let (pending, reasons) = self.import_relay_items(&items, journal, auth)?;
655        if let Some(cert) = self.certificate(VoteKind::Effects, &publication.act.address) {
656            return Ok(PublicationResult::Finalized {
657                certificate: cert.clone(),
658                evidence: self.publication(&publication.act)?.evidence,
659            });
660        }
661        if !pending.is_empty() {
662            return Ok(PublicationResult::Pending {
663                items: pending,
664                reasons,
665            });
666        }
667        if self.has(VoteKind::Operation, &publication.act.address) {
668            let operation = self
669                .certificate(VoteKind::Operation, &publication.act.address)
670                .ok_or("missing operation QC")?
671                .clone();
672            let request = self.prepare_effects(&publication.act.address, journal, auth)?;
673            return Ok(PublicationResult::Effects { operation, request });
674        }
675        let epoch = self.op(&publication.act.address)?.epoch.clone();
676        match self.owned_adoption_path(&epoch) {
677            Err(reason) => {
678                return Ok(PublicationResult::Pending {
679                    items: Vec::new(),
680                    reasons: alloc::vec![reason],
681                })
682            }
683            Ok(path) => {
684                for id in path {
685                    self.adopt_version(&id, journal, auth)?;
686                }
687            }
688        }
689        match self.prepare(&Event::Sign(publication.act.address.clone()), auth) {
690            Err(reason) => Ok(PublicationResult::Pending {
691                items: Vec::new(),
692                reasons: alloc::vec![reason],
693            }),
694            Ok(_) => Ok(PublicationResult::Operation(self.prepare_operation(
695                &publication.act.address,
696                journal,
697                auth,
698            )?)),
699        }
700    }
701
702    pub fn context(&self) -> &Context {
703        &self.context
704    }
705    pub fn validator(&self) -> &str {
706        &self.validator
707    }
708    /// Fetch retained evidence for relay. These getters never synthesize proofs.
709    pub fn operation_act(&self, id: &str) -> Option<&Act> {
710        self.state.operations.get(id).map(|op| &op.act)
711    }
712    pub fn certificate(&self, kind: VoteKind, id: &str) -> Option<&Certificate> {
713        self.state.certificates.get(&(kind, id.into()))
714    }
715
716    pub fn journal_sequence(&self) -> u64 {
717        self.sequence
718    }
719    fn commit<J: Journal, A: Authentication>(
720        &mut self,
721        event: Event,
722        journal: &mut J,
723        auth: &A,
724    ) -> Result<()> {
725        let Some(update) = self.prepare(&event, auth)? else {
726            return Ok(());
727        };
728        if self.sequence >= self.limits.events {
729            return Err("journal limit reached; evidence retained".into());
730        }
731        // All fallible protocol validation is complete. Failure/CAS rejection
732        // leaves state (including derived charges) untouched; no vote is exposed.
733        journal.append(
734            &self.context.id,
735            &self.validator,
736            Some(self.sequence),
737            &event,
738        )?;
739        self.apply_update(update);
740        self.sequence += 1;
741        Ok(())
742    }
743    fn op(&self, id: &str) -> Result<&Operation> {
744        self.state
745            .operations
746            .get(id)
747            .ok_or_else(|| alloc::format!("missing operation {id}"))
748    }
749    fn has(&self, kind: VoteKind, id: &str) -> bool {
750        self.state.certificates.contains_key(&(kind, id.into()))
751    }
752    fn epoch(&self, id: &str) -> Result<&VersionManifest> {
753        if let Some(v) = self.state.versions.get(id) {
754            return Ok(&v.manifest);
755        }
756        self.context
757            .root_manifest(id)
758            .ok_or_else(|| alloc::format!("missing certified epoch {id}"))
759    }
760    fn verify_vote<A: Authentication>(
761        &self,
762        v: &Vote,
763        kind: VoteKind,
764        payload: &str,
765        key: &str,
766        auth: &A,
767    ) -> Result<()> {
768        if v.context != self.context.id
769            || v.kind != kind
770            || v.payload != payload
771            || v.signer != key
772            || v.signature.len() > self.limits.signature_bytes
773            || v.signature.is_empty()
774            || !auth.verify(key, &v.preimage(), &v.signature)
775        {
776            return Err("invalid signature, domain, signer or payload".into());
777        }
778        Ok(())
779    }
780    fn verify_certificate<A: Authentication>(
781        &self,
782        c: &Certificate,
783        kind: VoteKind,
784        payload: &str,
785        auth: &A,
786    ) -> Result<()> {
787        let committee = &self.context.committee;
788        if c.kind != kind
789            || c.payload != payload
790            || c.votes.len() < committee.quorum
791            || c.votes.len() > committee.validators.len()
792        {
793            return Err("invalid certificate kind, payload or quorum".into());
794        }
795        let mut keys = BTreeSet::new();
796        for v in &c.votes {
797            if !committee.contains(&v.signer) || !keys.insert(v.signer.clone()) {
798                return Err("nonmember or duplicate validator".into());
799            }
800            self.verify_vote(v, kind, payload, &v.signer, auth)?;
801        }
802        Ok(())
803    }
804    fn operation(&self, a: &Act) -> Result<Operation> {
805        bounded_message(&a.message, self.limits.object_bytes)?;
806        self.context.structural(a)?;
807        if crate::canonical::canonical_encode(&SExpr::from(&a.message)).len()
808            > self.limits.object_bytes
809        {
810            return Err("operation too large".into());
811        }
812        let epoch = match a.fields.get(PREV) {
813            Some(SExpr::Atom(Atom::Symbol(s))) => s.clone(),
814            _ => return Err("missing source epoch".into()),
815        };
816        let m = self.epoch(&epoch)?;
817        let account = self.context.account(&a.signer)?.to_string();
818        if m.account != account {
819            return Err("epoch belongs to another account".into());
820        }
821        let dependencies = SExpr::List(
822            m.credited
823                .iter()
824                .map(|s| SExpr::Atom(Atom::Symbol(s.clone())))
825                .collect(),
826        );
827        if a.fields.get(DEPS) != Some(&dependencies) {
828            return Err("epoch finalized dependencies mismatch".into());
829        }
830        if !matches!(a.fields.get(NONCE),Some(SExpr::Atom(Atom::Str(s))) if !s.is_empty() && s.len()<=256)
831        {
832            return Err("missing or invalid transaction nonce".into());
833        }
834        let rule = &self.context.rule;
835        let (key, recipient, kind) = if a.verb == rule.increment.0 {
836            (&rule.increment.1, None, 0)
837        } else if a.verb == rule.decrement.0 {
838            (&rule.decrement.1, None, 1)
839        } else if let Some((_, r, k)) = rule.transfer.as_ref().filter(|(v, _, _)| a.verb == *v) {
840            (k, Some(r), 2)
841        } else if let Some((v, r, k)) = &rule.transfer_headroom {
842            if &a.verb == v {
843                (k, Some(r), 3)
844            } else {
845                return Err("not a counter operation".into());
846            }
847        } else {
848            return Err("not a counter operation".into());
849        };
850        let n = match a.fields.get(key) {
851            Some(SExpr::Atom(Atom::Num(n))) if *n > 0 => i128::from(*n),
852            _ => return Err("amount must be a positive integer".into()),
853        };
854        let to = match recipient {
855            None => account.clone(),
856            Some(k) => match a.fields.get(k) {
857                Some(SExpr::Atom(Atom::Symbol(s) | Atom::Str(s)))
858                    if self.context.initial.contains_key(s) =>
859                {
860                    s.clone()
861                }
862                _ => return Err("unknown recipient".into()),
863            },
864        };
865        if kind >= 2 && to == a.signer {
866            return Err("self transfer is not a resource operation".into());
867        }
868        if kind == 0 && !self.context.issuers.contains(&a.signer) {
869            return Err("mint requires issuer authority".into());
870        }
871        let bounded = rule.ceiling.is_some();
872        let (cost, credit) = match kind {
873            0 => (
874                Resources {
875                    rights: 0,
876                    headroom: if bounded { n } else { 0 },
877                },
878                Resources {
879                    rights: n,
880                    headroom: 0,
881                },
882            ),
883            1 => (
884                Resources {
885                    rights: n,
886                    headroom: 0,
887                },
888                Resources {
889                    rights: 0,
890                    headroom: if bounded { n } else { 0 },
891                },
892            ),
893            2 => (
894                Resources {
895                    rights: n,
896                    headroom: 0,
897                },
898                Resources {
899                    rights: n,
900                    headroom: 0,
901                },
902            ),
903            _ => {
904                if !bounded {
905                    return Err("headroom requires a ceiling".into());
906                }
907                (
908                    Resources {
909                        rights: 0,
910                        headroom: n,
911                    },
912                    Resources {
913                        rights: 0,
914                        headroom: n,
915                    },
916                )
917            }
918        };
919        Ok(Operation {
920            act: a.clone(),
921            account,
922            epoch,
923            cost,
924            credits: [(to, credit)].into_iter().collect(),
925        })
926    }
927    fn budget(&self, id: &str) -> Result<Resources> {
928        self.budget_op(id, self.op(id)?)
929    }
930    fn budget_op(&self, id: &str, op: &Operation) -> Result<Resources> {
931        let epoch = self.epoch(&op.epoch)?;
932        if self.state.active.get(&op.account) != Some(&op.epoch) || self.state.released.contains(id)
933        {
934            return Err("version inactive or operation released".into());
935        }
936        if let Some(root) = self.owned_root(&op.account) {
937            if self.state.fences.contains(id) || self.has(VoteKind::Cancel, id) {
938                return Err("owned operation has a preexisting cancellation fence".into());
939            }
940            if !self.descends(&op.epoch, root)? {
941                return Err("operation outside certified owned continuation".into());
942            }
943            if self
944                .state
945                .signed
946                .iter()
947                .any(|other| self.state.operations[other].epoch == op.epoch)
948            {
949                return Err("owned version slot already consumed".into());
950            }
951            if op.cost.rights > epoch.allocation.rights
952                || op.cost.headroom > epoch.allocation.headroom
953            {
954                return Err("owned allocation exceeded".into());
955            }
956            return self
957                .state
958                .charges
959                .get(&op.epoch)
960                .copied()
961                .unwrap_or_default()
962                .add(op.cost);
963        }
964        if epoch.phase == VersionPhase::Owned {
965            return Err("owned metadata awaits certified root".into());
966        }
967        if self.state.sealed.contains_key(&op.account) {
968            return Err("account sealed; awaiting certificate".into());
969        }
970        let used = self
971            .state
972            .charges
973            .get(&op.epoch)
974            .copied()
975            .unwrap_or_default()
976            .add(op.cost)?;
977        let q = self.context.committee.quorum as i128;
978        let k = i128::from(self.context.committee.faults) + 1;
979        if used.rights.checked_mul(q).ok_or("budget overflow")?
980            > epoch
981                .allocation
982                .rights
983                .checked_mul(k)
984                .ok_or("budget overflow")?
985            || used.headroom.checked_mul(q).ok_or("budget overflow")?
986                > epoch
987                    .allocation
988                    .headroom
989                    .checked_mul(k)
990                    .ok_or("budget overflow")?
991        {
992            return Err("local validator budget exceeded".into());
993        }
994        Ok(used)
995    }
996
997    pub(crate) fn owner_pristine(&self, owner: &str) -> bool {
998        !self.state.operations.values().any(|op| op.account == owner)
999            && self.state.active.get(owner) == self.context.root_epoch(owner).ok().as_ref()
1000    }
1001    pub(crate) fn owner_epoch_is_owned(&self, owner: &str, epoch: &str) -> Result<bool> {
1002        match self.owned_root(owner) {
1003            Some(root) => self.descends(epoch, root),
1004            None => Ok(false),
1005        }
1006    }
1007    pub(crate) fn owner_cost(&self, act: &Act) -> Result<Resources> {
1008        Ok(self.operation(act)?.cost)
1009    }
1010    pub(crate) fn owner_can_issue(&self, act: &Act, issued: &[Act]) -> Result<()> {
1011        let op = self.operation(act)?;
1012        self.budget_op(&act.address, &op)?;
1013        self.owner_batch_fits(act, issued)
1014    }
1015    pub(crate) fn owner_batch_fits(&self, act: &Act, issued: &[Act]) -> Result<()> {
1016        let op = self.operation(act)?;
1017        let epoch = self.epoch(&op.epoch)?;
1018        let owned = epoch.phase == VersionPhase::Owned;
1019        if op.cost.rights > epoch.allocation.rights || op.cost.headroom > epoch.allocation.headroom
1020        {
1021            return Err("owner cost exceeds version allocation".into());
1022        }
1023        let mut used = op.cost;
1024        for previous in issued {
1025            let previous = self.operation(previous)?;
1026            if previous.epoch == op.epoch {
1027                if owned {
1028                    return Err("owner already issued this owned slot".into());
1029                }
1030                used = used.add(previous.cost)?;
1031            }
1032        }
1033        if !owned {
1034            let allocation = epoch.allocation;
1035            let q = self.context.committee.quorum as i128;
1036            let k = i128::from(self.context.committee.faults) + 1;
1037            if used.rights.checked_mul(q).ok_or("owner budget overflow")?
1038                > allocation
1039                    .rights
1040                    .checked_mul(k)
1041                    .ok_or("owner budget overflow")?
1042                || used
1043                    .headroom
1044                    .checked_mul(q)
1045                    .ok_or("owner budget overflow")?
1046                    > allocation
1047                        .headroom
1048                        .checked_mul(k)
1049                        .ok_or("owner budget overflow")?
1050            {
1051                return Err("issued owner batch exceeds concurrent envelope".into());
1052            }
1053        }
1054        Ok(())
1055    }
1056    /// Rebuild bookkeeping only. Business content, owner and nonce remain exact.
1057    pub(crate) fn owner_rebase(&self, draft: &Act, epoch: &str) -> Result<Act> {
1058        self.operation(draft)?;
1059        let m = self.epoch(epoch)?;
1060        let mut message = draft.message.clone();
1061        fn replace(msg: &mut Message, epoch: &str, credits: &BTreeSet<String>) {
1062            match msg {
1063                Message::Wrapped { content, .. } => replace(content, epoch, credits),
1064                Message::Dialect { inner, .. } => replace(inner, epoch, credits),
1065                Message::Simple { params, .. } => {
1066                    for pair in params.chunks_exact_mut(2) {
1067                        match &pair[0] {
1068                            SExpr::Atom(Atom::Keyword(k)) if k == PREV => {
1069                                pair[1] = SExpr::Atom(Atom::Symbol(epoch.into()))
1070                            }
1071                            SExpr::Atom(Atom::Keyword(k)) if k == DEPS => {
1072                                pair[1] = SExpr::List(
1073                                    credits
1074                                        .iter()
1075                                        .map(|id| SExpr::Atom(Atom::Symbol(id.clone())))
1076                                        .collect(),
1077                                )
1078                            }
1079                            _ => (),
1080                        }
1081                    }
1082                }
1083                _ => (),
1084            }
1085        }
1086        replace(&mut message, epoch, &m.credited);
1087        let act = Act::from_message(message, &draft.signer)?;
1088        self.operation(&act)?;
1089        Ok(act)
1090    }
1091    pub(crate) fn owner_manifest(
1092        &self,
1093        account: &str,
1094        issued: &BTreeSet<String>,
1095    ) -> Result<VersionManifest> {
1096        let mut held = issued.clone();
1097        for id in &self.state.signed {
1098            if self.op(id)?.account == account {
1099                held.insert(id.clone());
1100            }
1101        }
1102        for id in &held {
1103            if !self.has(VoteKind::Effects, id) && !self.has(VoteKind::Cancel, id) {
1104                return Err("owner batch still draining".into());
1105            }
1106        }
1107        let credits = self
1108            .state
1109            .operations
1110            .iter()
1111            .filter_map(|(id, op)| {
1112                (op.credits.contains_key(account) && self.has(VoteKind::Effects, id))
1113                    .then_some(id.clone())
1114            })
1115            .collect();
1116        let mut manifest = self.draft_version(
1117            &BTreeSet::from([self.active_epoch(account)?.into()]),
1118            &held,
1119            &BTreeSet::new(),
1120            &credits,
1121        )?;
1122        manifest.phase = VersionPhase::Owned;
1123        Ok(manifest)
1124    }
1125    /// Certificate-derived mode; an untrusted manifest cannot activate ownership.
1126    pub fn owned_root(&self, account: &str) -> Option<&str> {
1127        self.state.owned.iter().find_map(|(id, request)| {
1128            (request.version.manifest.account == account && self.has(VoteKind::OwnedSeal, id))
1129                .then_some(id.as_str())
1130        })
1131    }
1132    fn descends(&self, version: &str, root: &str) -> Result<bool> {
1133        let mut todo = alloc::vec![version.to_string()];
1134        let mut seen = BTreeSet::new();
1135        while let Some(id) = todo.pop() {
1136            if id == root {
1137                return Ok(true);
1138            }
1139            if seen.insert(id.clone()) {
1140                todo.extend(self.epoch(&id)?.parents.iter().cloned());
1141            }
1142        }
1143        Ok(false)
1144    }
1145    fn check_owned<A: Authentication>(&self, request: &OwnedSealRequest, auth: &A) -> Result<()> {
1146        let m = &request.version.manifest;
1147        if m.phase != VersionPhase::Owned
1148            || self.context.ownership() != crate::escrow::Ownership::Account
1149        {
1150            return Err("collective pools cannot become owned accounts".into());
1151        }
1152        self.check_version(&request.version, auth)?;
1153        self.verify_vote(
1154            &request.authorization,
1155            VoteKind::OwnedSealRequest,
1156            &m.id(&self.context.id),
1157            &m.account,
1158            auth,
1159        )?;
1160        for id in &m.held {
1161            if !self.has(VoteKind::Effects, id) && !self.has(VoteKind::Cancel, id) {
1162                return Err("seal requires completely drained history".into());
1163            }
1164        }
1165        Ok(())
1166    }
1167    fn allocation(&self, m: &VersionManifest) -> Result<Resources> {
1168        let mut b = *self
1169            .context
1170            .initial
1171            .get(&m.account)
1172            .ok_or("unknown resource scope")?;
1173        for id in &m.credited {
1174            if !self.has(VoteKind::Effects, id) {
1175                return Err("missing final credit certificate".into());
1176            }
1177            b = b.add(
1178                *self
1179                    .op(id)?
1180                    .credits
1181                    .get(&m.account)
1182                    .ok_or("credit belongs to another account")?,
1183            )?;
1184        }
1185        for id in &m.held {
1186            let op = self.op(id)?;
1187            if op.account != m.account {
1188                return Err("held operation belongs to another account".into());
1189            }
1190            b = b.sub(op.cost)?;
1191        }
1192        for id in &m.refunded {
1193            if !m.held.contains(id) || !self.has(VoteKind::Cancel, id) {
1194                return Err("refund needs held operation and cancellation quorum".into());
1195            }
1196            b = b.add(self.op(id)?.cost)?;
1197        }
1198        if !b.nonnegative() {
1199            return Err("negative version allocation".into());
1200        }
1201        Ok(b)
1202    }
1203    fn check_version_manifest(&self, m: &VersionManifest) -> Result<()> {
1204        if (m.phase == VersionPhase::Owned
1205            && self.context.ownership() == crate::escrow::Ownership::Collective)
1206            || !self.context.initial.contains_key(&m.account)
1207            || m.parents.is_empty()
1208            || m.parents.len() > self.limits.versions.saturating_add(1)
1209            || m.held.len() > self.limits.operations
1210            || m.refunded.len() > self.limits.operations
1211            || m.credited.len() > self.limits.operations
1212        {
1213            return Err("invalid DAG pool, parent set or size limit".into());
1214        }
1215        for id in &m.parents {
1216            let parent = self.epoch(id)?;
1217            if (parent.phase == VersionPhase::Owned && m.phase != VersionPhase::Owned)
1218                || parent.account != m.account
1219                || parent.rank >= m.rank
1220                || !parent.held.is_subset(&m.held)
1221                || !parent.refunded.is_subset(&m.refunded)
1222                || !parent.credited.is_subset(&m.credited)
1223            {
1224                return Err("DAG parent rank or inherited sets mismatch".into());
1225            }
1226        }
1227        for id in &m.held {
1228            if self.epoch(&self.op(id)?.epoch)?.rank >= m.rank {
1229                return Err("held transaction must precede DAG version rank".into());
1230            }
1231        }
1232        if self.allocation(m)? != m.allocation {
1233            return Err("DAG version allocation mismatch".into());
1234        }
1235        Ok(())
1236    }
1237    fn check_version<A: Authentication>(&self, v: &DagVersion, auth: &A) -> Result<()> {
1238        self.check_version_manifest(&v.manifest)?;
1239        if !self
1240            .context
1241            .version_actor(&v.manifest.account, &v.authorization.signer)
1242        {
1243            return Err("unauthorized DAG version actor".into());
1244        }
1245        self.verify_vote(
1246            &v.authorization,
1247            VoteKind::VersionRequest,
1248            &v.manifest.id(&self.context.id),
1249            &v.authorization.signer,
1250            auth,
1251        )
1252    }
1253    /// Validated metadata for relay; no synthetic certificates or winner selection.
1254    pub fn version(&self, id: &str) -> Option<&DagVersion> {
1255        self.state.versions.get(id)
1256    }
1257    /// Complete immutable local history, including released and zero-cost IDs.
1258    pub fn version_snapshot(&self, account: &str) -> Result<VersionSnapshot> {
1259        let account = self.context.account(account)?;
1260        let root = self.context.root_epoch(account)?;
1261        let mut known: BTreeSet<_> = self
1262            .state
1263            .versions
1264            .iter()
1265            .filter(|(_, v)| v.manifest.account == account)
1266            .map(|(id, _)| id.clone())
1267            .collect();
1268        known.insert(root);
1269        let project = |ids: &BTreeSet<String>| {
1270            ids.iter()
1271                .filter(|id| {
1272                    self.state
1273                        .operations
1274                        .get(*id)
1275                        .is_some_and(|op| op.account == account)
1276                })
1277                .cloned()
1278                .collect()
1279        };
1280        let visited = self
1281            .state
1282            .visited
1283            .iter()
1284            .filter(|id| self.epoch(id).is_ok_and(|m| m.account == account))
1285            .cloned()
1286            .collect();
1287        Ok(VersionSnapshot {
1288            permanent_seal: self.state.sealed.get(account).cloned(),
1289            owned_root: self.owned_root(account).map(String::from),
1290            active: self.active_epoch(account)?.into(),
1291            known,
1292            visited,
1293            signed: project(&self.state.signed),
1294            released: project(&self.state.released),
1295            effects: project(&self.state.effects),
1296            fences: project(&self.state.fences),
1297        })
1298    }
1299    /// Compute unique cumulative books. The caller externally authorizes the
1300    /// result; receipt verifies all prerequisites independently.
1301    pub fn draft_version(
1302        &self,
1303        parents: &BTreeSet<String>,
1304        held: &BTreeSet<String>,
1305        refunds: &BTreeSet<String>,
1306        credits: &BTreeSet<String>,
1307    ) -> Result<VersionManifest> {
1308        if parents.is_empty()
1309            || parents.len() > self.limits.versions.saturating_add(1)
1310            || held.len() > self.limits.operations
1311            || refunds.len() > self.limits.operations
1312            || credits.len() > self.limits.operations
1313        {
1314            return Err("invalid DAG draft context or limits".into());
1315        }
1316        let mut m = VersionManifest {
1317            phase: VersionPhase::Concurrent,
1318            account: self
1319                .epoch(parents.first().ok_or("empty parent set")?)?
1320                .account
1321                .clone(),
1322            parents: parents.clone(),
1323            rank: 0,
1324            held: held.clone(),
1325            refunded: refunds.clone(),
1326            credited: credits.clone(),
1327            allocation: Resources::default(),
1328        };
1329        for id in parents {
1330            let p = self.epoch(id)?;
1331            if p.phase == VersionPhase::Owned {
1332                m.phase = VersionPhase::Owned;
1333            }
1334            m.rank = m.rank.max(p.rank);
1335            m.held.extend(p.held.iter().cloned());
1336            m.refunded.extend(p.refunded.iter().cloned());
1337            m.credited.extend(p.credited.iter().cloned());
1338        }
1339        if m.held.len() > self.limits.operations
1340            || m.refunded.len() > self.limits.operations
1341            || m.credited.len() > self.limits.operations
1342        {
1343            return Err("cumulative DAG sets exceed limits".into());
1344        }
1345        for id in &m.held {
1346            m.rank = m.rank.max(self.epoch(&self.op(id)?.epoch)?.rank);
1347        }
1348        m.rank = m.rank.checked_add(1).ok_or("DAG rank overflow")?;
1349        m.allocation = self.allocation(&m)?;
1350        self.check_version_manifest(&m)?;
1351        Ok(m)
1352    }
1353    pub fn receive_version<J: Journal, A: Authentication>(
1354        &mut self,
1355        version: DagVersion,
1356        journal: &mut J,
1357        auth: &A,
1358    ) -> Result<()> {
1359        self.commit(Event::Version(version), journal, auth)
1360    }
1361    pub fn adopt_version<J: Journal, A: Authentication>(
1362        &mut self,
1363        id: &str,
1364        journal: &mut J,
1365        auth: &A,
1366    ) -> Result<()> {
1367        self.commit(Event::AdoptVersion(id.into()), journal, auth)
1368    }
1369    // Replay shares exactly the same validation/update functions as live commit.
1370    fn apply<A: Authentication>(&mut self, event: &Event, auth: &A) -> Result<()> {
1371        if let Some(update) = self.prepare(event, auth)? {
1372            self.apply_update(update);
1373        }
1374        Ok(())
1375    }
1376    fn prepare<A: Authentication>(&self, event: &Event, auth: &A) -> Result<Option<Update>> {
1377        let update = match event {
1378            Event::Initialize => return Err("duplicate initialization".into()),
1379            Event::OwnedProposal(request) | Event::SealOwned(request) => {
1380                self.check_owned(request, auth)?;
1381                let m = &request.version.manifest;
1382                let id = m.id(&self.context.id);
1383                let seal = matches!(event, Event::SealOwned(_));
1384                if let Some(root) = self.owned_root(&m.account) {
1385                    if root != id {
1386                        return Err("conflicting certified owned root".into());
1387                    }
1388                }
1389                if seal {
1390                    if let Some(old) = self.state.sealed.get(&m.account) {
1391                        if old != &id {
1392                            return Err("account permanently sealed to another root".into());
1393                        }
1394                        return Ok(None);
1395                    }
1396                    let current = self.state.active.get(&m.account).ok_or("unknown account")?;
1397                    if !m.parents.contains(current) {
1398                        return Err("seal must follow active parent".into());
1399                    }
1400                    for signed in &self.state.signed {
1401                        if self.op(signed)?.account == m.account && !m.held.contains(signed) {
1402                            return Err("seal omits historical signature".into());
1403                        }
1404                    }
1405                } else if self.state.owned.contains_key(&id) {
1406                    return Ok(None);
1407                }
1408                if !self.state.owned.contains_key(&id)
1409                    && self.state.owned.len() >= self.limits.versions
1410                {
1411                    return Err("owned proposal limit reached".into());
1412                }
1413                if !self.state.versions.contains_key(&id)
1414                    && self.state.versions.len() >= self.limits.versions
1415                {
1416                    return Err("version limit reached; evidence retained".into());
1417                }
1418                Update::Owned(id, request.clone(), seal)
1419            }
1420            Event::Version(v) => {
1421                self.check_version(v, auth)?;
1422                let id = v.manifest.id(&self.context.id);
1423                if self.state.versions.contains_key(&id) {
1424                    return Ok(None);
1425                }
1426                if self.state.versions.len() >= self.limits.versions {
1427                    return Err("version limit reached; evidence retained".into());
1428                }
1429                Update::Version(id, v.clone())
1430            }
1431            Event::AdoptVersion(id) => {
1432                let v = self.state.versions.get(id).ok_or("unknown DAG version")?;
1433                let m = &v.manifest;
1434                let current = self.state.active.get(&m.account).ok_or("unknown pool")?;
1435                if current == id {
1436                    return Ok(None);
1437                }
1438                if let Some(root) = self.owned_root(&m.account) {
1439                    if !self.descends(id, root)? && !self.descends(root, id)? {
1440                        return Err("adoption outside certified owned ancestry".into());
1441                    }
1442                    // Pre-root ancestors may be traversed to catch up. budget_op
1443                    // still forbids EVERY new signature outside the owned root.
1444                } else if m.phase == VersionPhase::Owned
1445                    || self.state.sealed.contains_key(&m.account)
1446                {
1447                    return Err("owned account awaits seal certificate".into());
1448                }
1449                if !m.parents.contains(current) {
1450                    return Err("adoption must follow a direct active parent".into());
1451                }
1452                // Includes every old version, released reservation and zero-cost ID.
1453                for signed in &self.state.signed {
1454                    if self.op(signed)?.account == m.account && !m.held.contains(signed) {
1455                        return Err("DAG version omits historical signature".into());
1456                    }
1457                }
1458                Update::Adopt {
1459                    account: m.account.clone(),
1460                    id: id.clone(),
1461                }
1462            }
1463            Event::Candidate(a) => {
1464                let op = self.operation(a)?;
1465                if !auth.authenticate_act(a) {
1466                    return Err("owner signature or protocol admission failed".into());
1467                }
1468                if let Some(old) = self.state.operations.get(&a.address) {
1469                    if *old != op {
1470                        return Err("conflicting act identity".into());
1471                    }
1472                    return Ok(None);
1473                }
1474                if self.state.operations.len() >= self.limits.operations {
1475                    return Err("operation limit reached; evidence retained".into());
1476                }
1477                Update::Candidate(a.address.clone(), op)
1478            }
1479            Event::Certificate(c) => {
1480                if !matches!(
1481                    c.kind,
1482                    VoteKind::Operation
1483                        | VoteKind::Effects
1484                        | VoteKind::Cancel
1485                        | VoteKind::OwnedSeal
1486                ) {
1487                    return Err("unexpected certificate type".into());
1488                }
1489                if c.kind == VoteKind::OwnedSeal {
1490                    let request = self
1491                        .state
1492                        .owned
1493                        .get(&c.payload)
1494                        .ok_or("unknown owned proposal")?;
1495                    if let Some(root) = self.owned_root(&request.version.manifest.account) {
1496                        if root != c.payload {
1497                            return Err("conflicting certified owned root".into());
1498                        }
1499                    }
1500                    if let Some(root) = self.state.sealed.get(&request.version.manifest.account) {
1501                        if root != &c.payload {
1502                            return Err("certificate conflicts with permanent local seal".into());
1503                        }
1504                    }
1505                } else {
1506                    self.op(&c.payload)?;
1507                }
1508                self.verify_certificate(c, c.kind, &c.payload, auth)?;
1509                if c.kind == VoteKind::Effects {
1510                    if !self.has(VoteKind::Operation, &c.payload) {
1511                        return Err("effects require operation certificate".into());
1512                    }
1513                    if self.has(VoteKind::Cancel, &c.payload) {
1514                        return Err(
1515                            "conflicting genuine effects and cancellation certificates".into()
1516                        );
1517                    }
1518                }
1519                if c.kind == VoteKind::Cancel && self.has(VoteKind::Effects, &c.payload) {
1520                    return Err("conflicting genuine cancellation and effects certificates".into());
1521                }
1522                if self.has(c.kind, &c.payload) {
1523                    return Ok(None);
1524                }
1525                Update::Certificate((c.kind, c.payload.clone()), c.clone())
1526            }
1527            Event::Sign(id) => {
1528                if self.state.signed.contains(id) {
1529                    return Ok(None);
1530                }
1531                let charge = self.budget(id)?;
1532                Update::Sign {
1533                    id: id.clone(),
1534                    epoch: self.op(id)?.epoch.clone(),
1535                    charge,
1536                }
1537            }
1538            Event::Effect(id) => {
1539                if self.state.effects.contains(id) {
1540                    return Ok(None);
1541                }
1542                self.op(id)?;
1543                if self.state.fences.contains(id) || !self.has(VoteKind::Operation, id) {
1544                    return Err("effects fenced or missing operation certificate".into());
1545                }
1546                Update::Effect(id.clone())
1547            }
1548            Event::Fence(v) => {
1549                let op = self.op(&v.payload)?;
1550                if let Some(root) = self.owned_root(&op.account) {
1551                    if self.descends(&op.epoch, root)? {
1552                        return Err("owned operations cannot be cancelled".into());
1553                    }
1554                }
1555                self.verify_vote(v, VoteKind::CancelRequest, &v.payload, &op.act.signer, auth)?;
1556                if self.state.effects.contains(&v.payload) {
1557                    return Err("validator already signed effects".into());
1558                }
1559                if self.state.fences.contains(&v.payload) {
1560                    return Ok(None);
1561                }
1562                Update::Fence(v.payload.clone())
1563            }
1564            Event::Release(id) => {
1565                if !self.state.signed.contains(id) || !self.has(VoteKind::Cancel, id) {
1566                    return Err("release requires own charge and cancellation quorum".into());
1567                }
1568                if self.state.released.contains(id) {
1569                    return Ok(None);
1570                }
1571                let op = self.op(id)?;
1572                if self.owner_epoch_is_owned(&op.account, &op.epoch)? {
1573                    return Err("owned operations cannot release slots".into());
1574                }
1575                let charge = self
1576                    .state
1577                    .charges
1578                    .get(&op.epoch)
1579                    .copied()
1580                    .unwrap_or_default()
1581                    .sub(op.cost)?;
1582                if !charge.nonnegative() {
1583                    return Err("inconsistent derived charge".into());
1584                }
1585                Update::Release {
1586                    id: id.clone(),
1587                    epoch: op.epoch.clone(),
1588                    charge,
1589                }
1590            }
1591        };
1592        Ok(Some(update))
1593    }
1594    fn apply_update(&mut self, update: Update) {
1595        match update {
1596            Update::Owned(id, request, seal) => {
1597                if seal {
1598                    self.state
1599                        .sealed
1600                        .insert(request.version.manifest.account.clone(), id.clone());
1601                }
1602                self.state
1603                    .versions
1604                    .insert(id.clone(), request.version.clone());
1605                self.state.owned.insert(id, request);
1606            }
1607            Update::Candidate(id, op) => {
1608                self.state.operations.insert(id, op);
1609            }
1610            Update::Certificate(key, certificate) => {
1611                self.state.certificates.insert(key, certificate);
1612            }
1613            Update::Version(id, version) => {
1614                self.state.versions.insert(id, version);
1615            }
1616            Update::Adopt { account, id } => {
1617                self.state.active.insert(account, id.clone());
1618                self.state.visited.insert(id);
1619            }
1620            Update::Sign { id, epoch, charge } => {
1621                self.state.signed.insert(id);
1622                self.state.charges.insert(epoch, charge);
1623            }
1624            Update::Effect(id) => {
1625                self.state.effects.insert(id);
1626            }
1627            Update::Fence(id) => {
1628                self.state.fences.insert(id);
1629            }
1630            Update::Release { id, epoch, charge } => {
1631                self.state.released.insert(id);
1632                self.state.charges.insert(epoch, charge);
1633            }
1634        }
1635        #[cfg(debug_assertions)]
1636        self.assert_charge_cache();
1637    }
1638    /// Independent reference expression: the original history-based budget sum.
1639    /// Kept out of optimized builds; exercised at every debug execution/replay step.
1640    #[cfg(debug_assertions)]
1641    fn assert_charge_cache(&self) {
1642        let mut expected: BTreeMap<String, Resources> = BTreeMap::new();
1643        for id in &self.state.signed {
1644            let op = self
1645                .state
1646                .operations
1647                .get(id)
1648                .expect("signed candidate retained");
1649            let total = expected.entry(op.epoch.clone()).or_default();
1650            if !self.state.released.contains(id) {
1651                *total = total
1652                    .add(op.cost)
1653                    .expect("reachable historical charge fits");
1654            }
1655        }
1656        debug_assert_eq!(
1657            self.state.charges, expected,
1658            "derived charge differs from signed history"
1659        );
1660    }
1661    pub fn record_owned_proposal<J: Journal, A: Authentication>(
1662        &mut self,
1663        request: OwnedSealRequest,
1664        journal: &mut J,
1665        auth: &A,
1666    ) -> Result<()> {
1667        self.commit(Event::OwnedProposal(request), journal, auth)
1668    }
1669    /// Journal the unique permanent seal before exposing a validator vote.
1670    pub fn prepare_owned_seal<J: Journal, A: Authentication>(
1671        &mut self,
1672        request: OwnedSealRequest,
1673        journal: &mut J,
1674        auth: &A,
1675    ) -> Result<SigningRequest> {
1676        let id = request.version.manifest.id(&self.context.id);
1677        self.commit(Event::SealOwned(request), journal, auth)?;
1678        Ok(self
1679            .context
1680            .request(VoteKind::OwnedSeal, &id, &self.validator))
1681    }
1682    pub fn register<J: Journal, A: Authentication>(
1683        &mut self,
1684        act: Act,
1685        j: &mut J,
1686        a: &A,
1687    ) -> Result<()> {
1688        self.commit(Event::Candidate(act), j, a)
1689    }
1690    pub fn receive<J: Journal, A: Authentication>(
1691        &mut self,
1692        c: Certificate,
1693        j: &mut J,
1694        a: &A,
1695    ) -> Result<()> {
1696        self.commit(Event::Certificate(c), j, a)
1697    }
1698    pub fn prepare_operation<J: Journal, A: Authentication>(
1699        &mut self,
1700        id: &str,
1701        j: &mut J,
1702        a: &A,
1703    ) -> Result<SigningRequest> {
1704        self.commit(Event::Sign(id.into()), j, a)?;
1705        Ok(self
1706            .context
1707            .request(VoteKind::Operation, id, &self.validator))
1708    }
1709    pub fn prepare_effects<J: Journal, A: Authentication>(
1710        &mut self,
1711        id: &str,
1712        j: &mut J,
1713        a: &A,
1714    ) -> Result<SigningRequest> {
1715        self.commit(Event::Effect(id.into()), j, a)?;
1716        Ok(self.context.request(VoteKind::Effects, id, &self.validator))
1717    }
1718    pub fn prepare_cancel<J: Journal, A: Authentication>(
1719        &mut self,
1720        request: Vote,
1721        j: &mut J,
1722        a: &A,
1723    ) -> Result<SigningRequest> {
1724        let id = request.payload.clone();
1725        self.commit(Event::Fence(request), j, a)?;
1726        Ok(self.context.request(VoteKind::Cancel, &id, &self.validator))
1727    }
1728    pub fn release<J: Journal, A: Authentication>(
1729        &mut self,
1730        id: &str,
1731        j: &mut J,
1732        a: &A,
1733    ) -> Result<()> {
1734        self.commit(Event::Release(id.into()), j, a)
1735    }
1736
1737    pub fn active_epoch(&self, account: &str) -> Result<&str> {
1738        let account = self.context.account(account)?;
1739        self.state
1740            .active
1741            .get(account)
1742            .map(String::as_str)
1743            .ok_or_else(|| "unknown account".into())
1744    }
1745    pub fn finalized_view(&self) -> Result<FinalizedView> {
1746        let mut balances = self.context.initial.clone();
1747        let mut finalized = BTreeSet::new();
1748        let mut pending = BTreeSet::new();
1749        for (kind, id) in self.state.certificates.keys() {
1750            if *kind == VoteKind::Effects {
1751                finalized.insert(id.clone());
1752            } else if *kind == VoteKind::Operation
1753                && !self.has(VoteKind::Cancel, id)
1754                && !self.has(VoteKind::Effects, id)
1755            {
1756                pending.insert(id.clone());
1757            }
1758        }
1759        for id in &finalized {
1760            let op = self.op(id)?;
1761            let owner = balances.get_mut(&op.account).ok_or("unknown owner")?;
1762            *owner = owner.sub(op.cost)?;
1763            for (a, credit) in &op.credits {
1764                let b = balances.get_mut(a).ok_or("unknown recipient")?;
1765                *b = b.add(*credit)?;
1766            }
1767        }
1768        if balances.values().any(|b| !b.nonnegative()) {
1769            return Err("inconsistent final evidence violates resource bounds".into());
1770        }
1771        let rights: BTreeMap<_, _> = balances
1772            .iter()
1773            .map(|(a, b)| (a.clone(), b.rights))
1774            .collect();
1775        let value = rights
1776            .values()
1777            .try_fold(i128::from(self.context.rule.floor), |s, n| {
1778                s.checked_add(*n).ok_or("balance overflow")
1779            })?;
1780        if self
1781            .context
1782            .rule
1783            .ceiling
1784            .is_some_and(|cap| value > i128::from(cap))
1785        {
1786            return Err("final evidence exceeds ceiling".into());
1787        }
1788        Ok(FinalizedView {
1789            ownership: self.context.rule.ownership,
1790            context: self.context.id.clone(),
1791            evidence_digest: digest(alloc::vec![
1792                text("cbcl/final-view/v1"),
1793                text(&self.context.id),
1794                super::types::strings(&finalized)
1795            ]),
1796            rights,
1797            headroom: self.context.rule.ceiling.map(|_| {
1798                balances
1799                    .iter()
1800                    .map(|(a, b)| (a.clone(), b.headroom))
1801                    .collect()
1802            }),
1803            value,
1804            finalized,
1805            pending,
1806        })
1807    }
1808    pub fn intend(
1809        &self,
1810        inst: &Instance,
1811        owner: &AgentKey,
1812        verb: &str,
1813        fields: BTreeMap<String, SExpr>,
1814        nonce: &str,
1815    ) -> core::result::Result<Message, Reject> {
1816        let bound = Instance::new(inst.dialect, inst.thread.clone(), inst.acts)
1817            .map_err(Reject::Resource)?;
1818        crate::intend::intend_certified(&bound, owner, verb, fields, self, nonce)
1819    }
1820    pub(crate) fn bind_authoring<'a, 'd>(
1821        &'a self,
1822        instance: &'a Instance<'d>,
1823    ) -> Result<BoundAuthoring<'a, 'd>> {
1824        if !self.context.matches(instance) {
1825            return Err("runtime does not match instance or counter verb".into());
1826        }
1827        Ok(BoundAuthoring {
1828            replica: self,
1829            instance,
1830        })
1831    }
1832
1833    pub fn fold_instance(&self, inst: &Instance) -> Result<Vec<(String, Value)>> {
1834        if !self.context.matches(inst) {
1835            return Err("runtime instance mismatch".into());
1836        }
1837        let mut folded = crate::escrow::fold_instance(inst.dialect, &inst.thread.0, inst.acts);
1838        let field = folded
1839            .iter_mut()
1840            .find(|(name, _)| *name == self.context.field)
1841            .ok_or("missing resource field")?;
1842        field.1 = self.finalized_view()?.value();
1843        Ok(folded)
1844    }
1845}
1846
1847/// Bound the typed tree before recursive cloning/canonicalization/authentication.
1848/// Wire decoders must ALSO enforce their own allocation limits before constructing
1849/// these values. Depth 64 is the runtime ceiling, independent of host limits.
1850fn bounded_message(message: &Message, limit: usize) -> Result<()> {
1851    use crate::message::{CausedBy, Recipients};
1852    let mut total = 0usize;
1853    let mut charge = |n: usize| -> Result<()> {
1854        total = total.checked_add(n).ok_or("object size overflow")?;
1855        if total > limit {
1856            return Err("operation object limit exceeded".into());
1857        }
1858        Ok(())
1859    };
1860    let mut msg = message;
1861    let mut expressions = Vec::new();
1862    for depth in 0..=64 {
1863        charge(16)?;
1864        match msg {
1865            Message::Dialect {
1866                dialect_name,
1867                inner,
1868            } => {
1869                charge(dialect_name.len())?;
1870                msg = inner;
1871            }
1872            Message::Wrapped {
1873                params, content, ..
1874            } => {
1875                if params.len() > limit {
1876                    return Err("wrapper size limit exceeded".into());
1877                }
1878                expressions.extend(params.iter().map(|s| (s, depth + 1)));
1879                msg = content;
1880            }
1881            Message::Simple {
1882                performative,
1883                recipient,
1884                content,
1885                params,
1886                thread,
1887                sender,
1888                caused_by,
1889            } => {
1890                charge(performative.name().len())?;
1891                if let Some(r) = recipient {
1892                    match r {
1893                        Recipients::One(k) => charge(k.len())?,
1894                        Recipients::Set(ks) => {
1895                            if ks.len() > limit {
1896                                return Err("recipient limit exceeded".into());
1897                            }
1898                            for k in ks {
1899                                charge(k.len() + 1)?;
1900                            }
1901                        }
1902                    }
1903                }
1904                if let Some(t) = thread {
1905                    charge(t.len())?;
1906                }
1907                if let Some(s) = sender {
1908                    charge(s.len())?;
1909                }
1910                match caused_by {
1911                    Some(CausedBy::Single(s)) => charge(s.len())?,
1912                    Some(CausedBy::Multiple(xs)) => {
1913                        if xs.len() > limit {
1914                            return Err("cause limit exceeded".into());
1915                        }
1916                        for x in xs {
1917                            charge(x.len() + 1)?;
1918                        }
1919                    }
1920                    _ => {}
1921                }
1922                if params.len() > limit {
1923                    return Err("parameter limit exceeded".into());
1924                }
1925                expressions.push((content, depth + 1));
1926                expressions.extend(params.iter().map(|s| (s, depth + 1)));
1927                break;
1928            }
1929            Message::Meta { .. } => {
1930                return Err("resource candidate cannot be a meta message".into())
1931            }
1932        }
1933        if depth == 64 {
1934            return Err("message nesting limit exceeded".into());
1935        }
1936    }
1937    while let Some((s, depth)) = expressions.pop() {
1938        if depth > 64 {
1939            return Err("S-expression nesting limit exceeded".into());
1940        }
1941        charge(16)?;
1942        match s {
1943            SExpr::Atom(Atom::Symbol(s) | Atom::Keyword(s) | Atom::Str(s)) => charge(s.len())?,
1944            SExpr::Atom(_) => {}
1945            SExpr::List(xs) => {
1946                if xs.len() > limit {
1947                    return Err("list limit exceeded".into());
1948                }
1949                expressions.extend(xs.iter().map(|s| (s, depth + 1)));
1950            }
1951        }
1952    }
1953    Ok(())
1954}
1955
1956/// Immutable authoring inputs whose instance identity was checked together.
1957/// Only this module can construct the binding; it cannot be retargeted to a
1958/// different instance. Bookkeeping and candidate checks share that validation.
1959pub(crate) struct BoundAuthoring<'a, 'd> {
1960    replica: &'a Replica,
1961    instance: &'a Instance<'d>,
1962}
1963impl<'d> BoundAuthoring<'_, 'd> {
1964    pub(crate) fn instance(&self) -> &Instance<'d> {
1965        self.instance
1966    }
1967    pub(crate) fn bookkeeping(
1968        &self,
1969        owner: &str,
1970        verb: &str,
1971        nonce: &str,
1972    ) -> Result<Vec<(String, SExpr)>> {
1973        if !self.replica.context.rule.operation_verbs().contains(&verb) {
1974            return Err("runtime does not match instance or counter verb".into());
1975        }
1976        if nonce.is_empty() || nonce.len() > 256 {
1977            return Err("nonce must contain 1..256 bytes".into());
1978        }
1979        let epoch = self.replica.active_epoch(owner)?;
1980        let m = self.replica.epoch(epoch)?;
1981        Ok(alloc::vec![
1982            (PREV.into(), SExpr::Atom(Atom::Symbol(epoch.into()))),
1983            (
1984                DEPS.into(),
1985                SExpr::List(
1986                    m.credited
1987                        .iter()
1988                        .map(|s| SExpr::Atom(Atom::Symbol(s.clone())))
1989                        .collect()
1990                )
1991            ),
1992            (NONCE.into(), SExpr::Atom(Atom::Str(nonce.into())))
1993        ])
1994    }
1995    pub(crate) fn check_candidate(&self, candidate: &Act) -> Result<()> {
1996        self.replica.operation(candidate)?;
1997        Ok(())
1998    }
1999}