Skip to main content

cbcl_core/
intend.rs

1//! The intent binder (SPEC-019 R.5): `intend` completes a caller's verb and
2//! data fields into a canonical act, or rejects. Pure: it never signs,
3//! sends, stores, or reads a clock. Every host must bind identically, which
4//! is why it lives beside the fold.
5
6#![forbid(unsafe_code)]
7
8use crate::dialect::Dialect;
9use crate::message::{CausedBy, Message, Performative, Recipients, WrapperType};
10use crate::projection::verify_causal_for_role;
11use crate::protocol::{verify_causal, NodeRef, VerificationResult, BEGIN_KEYWORD};
12use crate::r7::{bounds_of, declared_keywords, verify_state_shape};
13use crate::role::{parse_wrapper_cast, AgentKey, Cast, Endpoint};
14use crate::sexpr::{Atom, SExpr};
15use crate::shape::ShapeViolation;
16use crate::state::{
17    opener, root, wire_address, Act, Rule, StateClause, Value, RESERVED_REPLACES, ROUTING_KEYWORDS,
18};
19use crate::store::{ContentHash, MessageStore, ThreadId, ThreadedMessageStore};
20use alloc::collections::{BTreeMap, BTreeSet};
21use alloc::format;
22use alloc::string::String;
23use alloc::vec::Vec;
24use core::fmt;
25
26/// The instance context (SPEC-019 CON-1903): everything a state function
27/// may read. The cast is parsed from the accepted root wrapper, never
28/// supplied by a caller.
29#[derive(Debug, Clone)]
30pub struct Instance<'a> {
31    pub dialect: &'a Dialect,
32    pub thread: ThreadId,
33    pub acts: &'a [Act],
34    /// The act of the opener verb.
35    pub opener: Option<&'a Act>,
36    /// Under R6, the cast-bearing root (SPEC-014 REQ-611/623), which the
37    /// opener follows; `None` for a role-free dialect.
38    pub root: Option<&'a Act>,
39    pub cast: Option<Cast>,
40}
41
42impl<'a> Instance<'a> {
43    /// Build the context from accepted acts. For a role-declaring dialect
44    /// the cast is read from the `with-roles` root among the acts.
45    pub fn new(
46        dialect: &'a Dialect,
47        thread: ThreadId,
48        acts: &'a [Act],
49    ) -> Result<Instance<'a>, String> {
50        let op = dialect
51            .causal_protocol
52            .as_ref()
53            .and_then(|p| opener(p, acts));
54        let (rt, cast) = if dialect.roles.is_empty() {
55            (None, None)
56        } else {
57            match root(acts) {
58                Some(r) => (Some(r), Some(cast_of(&r.message, dialect)?)),
59                None => (None, None),
60            }
61        };
62        Ok(Instance {
63            dialect,
64            thread,
65            acts,
66            opener: op,
67            root: rt,
68            cast,
69        })
70    }
71
72    /// The accepted acts as a store keyed by content address.
73    pub fn store(&self) -> ThreadedMessageStore {
74        let mut store = ThreadedMessageStore::new();
75        for a in self.acts {
76            store.append(
77                ContentHash(a.address.clone()),
78                self.thread.clone(),
79                a.message.clone(),
80            );
81        }
82        store
83    }
84
85    /// The address of the accepted opener.
86    pub fn instance_id(&self) -> Option<&str> {
87        self.opener.map(|a| a.address.as_str())
88    }
89}
90
91/// Read the cast from a root message's `with-roles` wrapper.
92pub fn cast_of(root: &Message, dialect: &Dialect) -> Result<Cast, String> {
93    let mut cur = root;
94    loop {
95        match cur {
96            Message::Wrapped {
97                wrapper: WrapperType::WithRoles,
98                params,
99                ..
100            } => {
101                return parse_wrapper_cast(params, &dialect.roles).map_err(|e| format!("{e}"));
102            }
103            Message::Wrapped { content, .. } => cur = content,
104            Message::Dialect { inner, .. } => cur = inner,
105            _ => {
106                return Err(String::from(
107                    "the root of a role-declaring dialect must carry a with-roles wrapper",
108                ))
109            }
110        }
111    }
112}
113
114/// The roles a signer occupies under a cast, sorted.
115pub fn roles_of(cast: &Cast, signer: &AgentKey) -> Vec<String> {
116    let mut out: Vec<String> = cast
117        .singleton
118        .iter()
119        .filter(|(_, k)| *k == signer)
120        .map(|(r, _)| r.clone())
121        .chain(
122            cast.indexed
123                .iter()
124                .filter(|(_, ks)| ks.contains(signer))
125                .map(|(r, _)| r.clone()),
126        )
127        .collect();
128    out.sort();
129    out.dedup();
130    out
131}
132
133/// Why an intent was rejected (SPEC-019 R.5).
134#[derive(Debug, Clone, PartialEq, Eq)]
135pub enum Reject {
136    UnknownVerb,
137    Opener,
138    Forge(String),
139    Role(String),
140    Domain(String),
141    NothingToDelete,
142    NoPredecessor,
143    Shape(ShapeViolation),
144    NotValid(VerificationResult),
145    /// The instance has no accepted opener, so no recipient set is known.
146    NoOpener,
147    Resource(String),
148}
149
150impl fmt::Display for Reject {
151    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
152        match self {
153            Reject::Resource(reason) => write!(f, "resource authorization: {reason}"),
154            Reject::UnknownVerb => write!(f, "unknown verb"),
155            Reject::Opener => write!(f, "the opener cannot be emitted on an existing instance"),
156            Reject::Forge(field) => {
157                write!(f, "the caller supplied :{field}, which the binder owns")
158            }
159            Reject::Role(required) => write!(f, "the signer occupies no role '{required}'"),
160            Reject::Domain(field) => write!(f, ":{field} is not among the opener's options"),
161            Reject::NothingToDelete => write!(f, "nothing to delete"),
162            Reject::NoPredecessor => write!(f, "no admissible predecessor"),
163            Reject::Shape(v) => write!(f, "{v}"),
164            Reject::NotValid(v) => write!(f, "constructed act is not Valid: {v:?}"),
165            Reject::NoOpener => write!(f, "the instance has no accepted opener"),
166        }
167    }
168}
169
170/// The JSON rendering of a rejection, for exports.
171pub fn render_reject(r: &Reject) -> String {
172    let kind = match r {
173        Reject::Resource(_) => "resource",
174        Reject::UnknownVerb => "unknown-verb",
175        Reject::Opener => "opener",
176        Reject::Forge(_) => "forge",
177        Reject::Role(_) => "role",
178        Reject::Domain(_) => "domain",
179        Reject::NothingToDelete => "nothing-to-delete",
180        Reject::NoPredecessor => "no-predecessor",
181        Reject::Shape(v) if v.rule == "resource-limit" => "resource-limit",
182        Reject::Shape(_) => "shape",
183        Reject::NotValid(_) => "not-valid",
184        Reject::NoOpener => "no-opener",
185    };
186    let detail = format!("{r}");
187    let mut out = String::from("{\"reject\":");
188    out.push_str(&Value::Str(String::from(kind)).render());
189    out.push_str(",\"reason\":");
190    out.push_str(&Value::Str(detail).render());
191    out.push('}');
192    out
193}
194
195/// The predecessor performatives a verb's step admits (each alternative).
196fn allowed_predecessors(d: &Dialect, verb: &str) -> Vec<NodeRef> {
197    d.causal_protocol
198        .as_ref()
199        .and_then(|p| p.steps.get(verb))
200        .map(|s| s.predecessors.clone())
201        .unwrap_or_default()
202}
203
204/// The keys the cast expects as recipients for a `:to` role set.
205fn recipient_keys(to: &BTreeSet<String>, cast: &Cast) -> BTreeSet<String> {
206    let mut keys = BTreeSet::new();
207    for role in to {
208        if let Some(k) = cast.singleton.get(role) {
209            keys.insert(k.0.clone());
210        }
211        if let Some(ks) = cast.indexed.get(role) {
212            keys.extend(ks.iter().map(|k| k.0.clone()));
213        }
214    }
215    keys
216}
217
218/// Step 1 of R.5 without an intent: the verbs a signer may emit here.
219pub fn may_send(inst: &Instance, signer: &AgentKey) -> Vec<String> {
220    let Some(protocol) = inst.dialect.causal_protocol.as_ref() else {
221        return Vec::new();
222    };
223    let opener_name = crate::state::opener_verb(protocol).map(String::from);
224    let mut out = Vec::new();
225    for p in &inst.dialect.performatives {
226        if Some(&p.name) == opener_name.as_ref()
227            && !protocol.steps.keys().any(|n| {
228                n.contains(crate::protocol::REPEAT_SEPARATOR)
229                    && crate::protocol::repeat_base_name(n) == p.name
230            })
231        {
232            continue;
233        }
234        if role_gate(inst, signer, &p.name).is_err() {
235            continue;
236        }
237        out.push(p.name.clone());
238    }
239    out.sort();
240    out
241}
242
243fn role_gate(inst: &Instance, signer: &AgentKey, verb: &str) -> Result<(), Reject> {
244    let Some(cast) = inst.cast.as_ref() else {
245        return Ok(());
246    };
247    let Some(ann) = inst
248        .dialect
249        .find_performative(verb)
250        .and_then(|p| p.role.as_ref())
251    else {
252        return Ok(());
253    };
254    if cast.admits(&ann.from, signer) {
255        Ok(())
256    } else {
257        Err(Reject::Role(ann.from.clone()))
258    }
259}
260
261/// Choose the predecessor for one required type set (step 5): the signer's
262/// own tip among candidates, else the greatest address.
263fn choose_predecessor(inst: &Instance, signer: &str, allowed: &BTreeSet<&str>) -> Option<String> {
264    choose_typed_predecessor(inst, signer, allowed, None)
265}
266fn choose_typed_predecessor(
267    inst: &Instance,
268    signer: &str,
269    allowed: &BTreeSet<&str>,
270    resolution: Option<&crate::repeat::Resolution<'_, ThreadedMessageStore>>,
271) -> Option<String> {
272    let candidates: Vec<&Act> = inst
273        .acts
274        .iter()
275        .filter(|a| match resolution {
276            Some(r) => allowed
277                .iter()
278                .any(|name| matches!(r.at(&a.address, name), VerificationResult::Valid)),
279            None => allowed.contains(a.verb.as_str()),
280        })
281        .collect();
282    if candidates.is_empty() {
283        return None;
284    }
285    let own: Vec<&Act> = candidates
286        .iter()
287        .copied()
288        .filter(|a| a.signer == signer)
289        .collect();
290    if !own.is_empty() {
291        let named: BTreeSet<&str> = own
292            .iter()
293            .flat_map(|a| a.predecessors.iter().map(|p| p.as_str()))
294            .collect();
295        let tips: Vec<&Act> = own
296            .iter()
297            .copied()
298            .filter(|a| !named.contains(a.address.as_str()))
299            .collect();
300        let pool = if tips.is_empty() { own } else { tips };
301        return pool
302            .iter()
303            .max_by(|a, b| a.address.as_bytes().cmp(b.address.as_bytes()))
304            .map(|a| a.address.clone());
305    }
306    candidates
307        .iter()
308        .max_by(|a, b| a.address.as_bytes().cmp(b.address.as_bytes()))
309        .map(|a| a.address.clone())
310}
311
312// Resolve expanded predecessor types from accepted causal evidence. For a
313// repeated verb, skip already occupied copies and prefer the furthest ready
314// position. This authoring policy does not reject concurrent peer branches.
315fn repeat_cause(inst: &Instance, signer: &str, verb: &str) -> Result<CausedBy, Reject> {
316    let protocol = inst
317        .dialect
318        .causal_protocol
319        .as_ref()
320        .ok_or(Reject::NoPredecessor)?;
321    let store = inst.store();
322    let root = inst.root.map(|a| ContentHash(a.address.clone()));
323    let resolution = crate::repeat::Resolution::new(
324        &store,
325        protocol,
326        &inst.thread,
327        root.as_ref(),
328        inst.acts.iter().map(|a| a.address.clone()),
329    );
330    for name in resolution.order.iter().rev() {
331        if crate::protocol::repeat_base_name(name) != verb {
332            continue;
333        }
334        if protocol.steps.keys().any(|n| {
335            n.contains(crate::protocol::REPEAT_SEPARATOR)
336                && crate::protocol::repeat_base_name(n) == verb
337        }) && inst
338            .acts
339            .iter()
340            .any(|a| matches!(resolution.at(&a.address, name), VerificationResult::Valid))
341        {
342            continue;
343        }
344        for node in &protocol.steps[*name].predecessors {
345            let names: BTreeSet<&str> = node.performatives().collect();
346            if names.contains(BEGIN_KEYWORD) {
347                continue;
348            }
349            if matches!(node, NodeRef::All(_)) {
350                let chosen: Option<Vec<String>> = names
351                    .iter()
352                    .map(|n| {
353                        let occupants = inst
354                            .dialect
355                            .find_performative(crate::protocol::repeat_base_name(n))
356                            .and_then(|p| p.role.as_ref())
357                            .and_then(|ann| inst.cast.as_ref()?.indexed.get(&ann.from));
358                        if let Some(occupants) = occupants {
359                            occupants
360                                .iter()
361                                .map(|who| {
362                                    inst.acts
363                                        .iter()
364                                        .filter(|a| {
365                                            a.signer == who.0
366                                                && matches!(
367                                                    resolution.at(&a.address, n),
368                                                    VerificationResult::Valid
369                                                )
370                                        })
371                                        .max_by(|a, b| a.address.cmp(&b.address))
372                                        .map(|a| a.address.clone())
373                                })
374                                .collect::<Option<Vec<_>>>()
375                        } else {
376                            choose_typed_predecessor(
377                                inst,
378                                signer,
379                                &[*n].into_iter().collect(),
380                                Some(&resolution),
381                            )
382                            .map(|h| alloc::vec![h])
383                        }
384                    })
385                    .collect::<Option<Vec<_>>>()
386                    .map(|groups| groups.into_iter().flatten().collect());
387                if let Some(mut hs) = chosen.filter(|hs| !hs.is_empty()) {
388                    hs.sort();
389                    hs.dedup();
390                    return Ok(CausedBy::Multiple(hs));
391                }
392            } else if let Some(hash) =
393                choose_typed_predecessor(inst, signer, &names, Some(&resolution))
394            {
395                return Ok(CausedBy::Single(hash));
396            }
397        }
398    }
399    Err(Reject::NoPredecessor)
400}
401
402/// Complete a verb and its data fields into a canonical act for the host to sign.
403pub fn intend(
404    inst: &Instance,
405    signer: &AgentKey,
406    verb: &str,
407    fields: BTreeMap<String, SExpr>,
408) -> Result<Message, Reject> {
409    intend_impl(inst, signer, verb, fields, None)
410}
411
412pub(crate) fn intend_certified(
413    inst: &Instance,
414    signer: &AgentKey,
415    verb: &str,
416    fields: BTreeMap<String, SExpr>,
417    runtime: &crate::quorum::Replica,
418    nonce: &str,
419) -> Result<Message, Reject> {
420    intend_impl(inst, signer, verb, fields, Some((runtime, nonce)))
421}
422
423fn intend_impl(
424    inst: &Instance,
425    signer: &AgentKey,
426    verb: &str,
427    fields: BTreeMap<String, SExpr>,
428    runtime: Option<(&crate::quorum::Replica, &str)>,
429) -> Result<Message, Reject> {
430    let d = inst.dialect;
431    let clause: &StateClause = match d.state.as_ref() {
432        Some(c) => c,
433        None => return Err(Reject::UnknownVerb),
434    };
435    let Some(protocol) = d.causal_protocol.as_ref() else {
436        return Err(Reject::UnknownVerb);
437    };
438
439    // 1 admit
440    if d.find_performative(verb).is_none() {
441        return Err(Reject::UnknownVerb);
442    }
443    if crate::state::opener_verb(protocol) == Some(verb)
444        && !protocol.steps.keys().any(|n| {
445            n.contains(crate::protocol::REPEAT_SEPARATOR)
446                && crate::protocol::repeat_base_name(n) == verb
447        })
448    {
449        return Err(Reject::Opener);
450    }
451    for k in fields.keys() {
452        if ROUTING_KEYWORDS.contains(&k.as_str())
453            || k == RESERVED_REPLACES
454            || k == crate::escrow::PREV
455            || k == crate::escrow::DEPS
456            || k == crate::escrow::NONCE
457        {
458            return Err(Reject::Forge(k.clone()));
459        }
460    }
461    role_gate(inst, signer, verb)?;
462
463    // 2 domain
464    let state = crate::state::fold(clause, Some(protocol), inst.acts);
465    for (dv, key, field) in clause.domains() {
466        if dv != verb {
467            continue;
468        }
469        let allowed = match state.iter().find(|(n, _)| n == field) {
470            Some((_, Value::List(items))) | Some((_, Value::Set(items))) => items.clone(),
471            _ => Vec::new(),
472        };
473        let supplied = fields.get(key).map(Value::from_sexpr);
474        let ok = supplied.as_ref().is_some_and(|v| {
475            let r = v.render();
476            allowed.iter().any(|x| x.render() == r)
477        });
478        if !ok {
479            return Err(Reject::Domain(String::from(key)));
480        }
481    }
482
483    // 3 to
484    let recipients: BTreeSet<String> = match (
485        &inst.cast,
486        d.find_performative(verb).and_then(|p| p.role.as_ref()),
487    ) {
488        (Some(cast), Some(ann)) => recipient_keys(&ann.to, cast),
489        _ => match inst.opener {
490            Some(op) => op.recipients.clone(),
491            None => return Err(Reject::NoOpener),
492        },
493    };
494
495    // 4 replaces
496    let bounds = bounds_of(d);
497    let mut replaces: Option<Vec<String>> = None;
498    for (_, rule) in clause.fields() {
499        if let Rule::LwwPerSigner { verb: writer, .. } = rule {
500            if writer == verb {
501                let mut addrs: Vec<String> =
502                    crate::state::current_by_signer(clause, inst.acts, writer)
503                        .into_iter()
504                        .filter(|a| a.signer == signer.0)
505                        .map(|a| a.address.clone())
506                        .collect();
507                addrs.sort();
508                addrs.dedup();
509                let existing = replaces.get_or_insert_with(Vec::new);
510                existing.extend(addrs);
511                existing.sort();
512                existing.dedup();
513                existing.truncate(bounds.max_list as usize);
514            }
515            continue;
516        }
517        let binding = match rule {
518            Rule::Values { verb: w, .. } if w == verb => Some((w.as_str(), None, None, false)),
519            Rule::ValuesPerKey {
520                verb: w,
521                key,
522                delete,
523                ..
524            }
525            | Rule::LwwMap {
526                verb: w,
527                key,
528                delete,
529                ..
530            } => {
531                if w == verb {
532                    Some((w.as_str(), Some(key.as_str()), delete.as_deref(), false))
533                } else if delete.as_deref() == Some(verb) {
534                    Some((w.as_str(), Some(key.as_str()), delete.as_deref(), true))
535                } else {
536                    None
537                }
538            }
539            Rule::ObservedSet { add, remove, key } if remove == verb => Some((
540                add.as_str(),
541                Some(key.as_str()),
542                Some(remove.as_str()),
543                true,
544            )),
545            _ => None,
546        };
547        let Some((writer, key, delete, is_delete)) = binding else {
548            continue;
549        };
550        let mine = |a: &Act| -> bool {
551            match key {
552                None => true,
553                Some(k) => match (a.fields.get(k), fields.get(k)) {
554                    (Some(x), Some(y)) => {
555                        Value::from_sexpr(x).render() == Value::from_sexpr(y).render()
556                    }
557                    _ => false,
558                },
559            }
560        };
561        let current = crate::state::current_writes(clause, inst.acts, writer, key, delete);
562        let mut addrs: Vec<String> = current
563            .iter()
564            .filter(|a| mine(a))
565            .map(|a| a.address.clone())
566            .collect();
567        if is_delete && addrs.is_empty() {
568            return Err(Reject::NothingToDelete);
569        }
570        if !is_delete {
571            if let Some(dv) = delete {
572                // Current deletions for the key: deletions no later write names.
573                let deletions =
574                    crate::state::current_writes(clause, inst.acts, dv, key, Some(writer));
575                addrs.extend(
576                    deletions
577                        .iter()
578                        .filter(|a| mine(a))
579                        .map(|a| a.address.clone()),
580                );
581            }
582        }
583        addrs.sort();
584        addrs.dedup();
585        addrs.truncate(bounds.max_list as usize);
586        match replaces.as_mut() {
587            None => replaces = Some(addrs),
588            Some(existing) => {
589                existing.extend(addrs);
590                existing.sort();
591                existing.dedup();
592                existing.truncate(bounds.max_list as usize);
593            }
594        }
595    }
596
597    // 5 caused-by
598    let steps = allowed_predecessors(d, verb);
599    let caused_by = if crate::repeat::has_repeat(protocol) {
600        repeat_cause(inst, &signer.0, verb)?
601    } else if steps.is_empty() {
602        return Err(Reject::NoPredecessor);
603    } else {
604        let mut chosen: Vec<String> = Vec::new();
605        let mut fan_in = false;
606        for node in &steps {
607            match node {
608                NodeRef::Single(s) => {
609                    let allowed: BTreeSet<&str> = [s.as_str()].into_iter().collect();
610                    if let Some(p) = choose_predecessor(inst, &signer.0, &allowed) {
611                        chosen = alloc::vec![p];
612                        break;
613                    }
614                    if s == BEGIN_KEYWORD {
615                        return Err(Reject::Opener);
616                    }
617                }
618                NodeRef::Any(set) => {
619                    let allowed: BTreeSet<&str> = set.iter().map(|s| s.as_str()).collect();
620                    if let Some(p) = choose_predecessor(inst, &signer.0, &allowed) {
621                        chosen = alloc::vec![p];
622                        break;
623                    }
624                }
625                NodeRef::All(set) => {
626                    fan_in = true;
627                    let mut all = Vec::new();
628                    for s in set {
629                        let allowed: BTreeSet<&str> = [s.as_str()].into_iter().collect();
630                        match choose_predecessor(inst, &signer.0, &allowed) {
631                            Some(p) => all.push(p),
632                            None => {
633                                all.clear();
634                                break;
635                            }
636                        }
637                    }
638                    if !all.is_empty() {
639                        chosen = all;
640                        break;
641                    }
642                }
643            }
644        }
645        if chosen.is_empty() {
646            return Err(Reject::NoPredecessor);
647        }
648        if fan_in && chosen.len() > 1 {
649            chosen.sort();
650            CausedBy::Multiple(chosen)
651        } else {
652            CausedBy::Single(chosen.remove(0))
653        }
654    };
655
656    // 6 build
657    let mut params: Vec<SExpr> = Vec::new();
658    let declared = declared_keywords(&d.shapes, verb);
659    for (k, v) in &fields {
660        if !declared.contains(k) {
661            return Err(Reject::Shape(ShapeViolation {
662                rule: String::from("closed"),
663                field: Some(format!(":{k}")),
664                expected: None,
665                found: None,
666                detail: format!("undeclared field :{k} on '{verb}'"),
667            }));
668        }
669        params.push(SExpr::Atom(Atom::Keyword(k.clone())));
670        params.push(v.clone());
671    }
672    // Keep identity rejection at its original point after ordinary admission.
673    // The binding holds the exact immutable inputs for both authoring stages.
674    let authoring = runtime
675        .map(|(engine, nonce)| engine.bind_authoring(inst).map(|bound| (bound, nonce)))
676        .transpose()
677        .map_err(Reject::Resource)?;
678    let inst = authoring
679        .as_ref()
680        .map_or(inst, |(bound, _)| bound.instance());
681    let bookkeeping = match &authoring {
682        Some((engine, nonce)) => engine.bookkeeping(&signer.0, verb, nonce),
683        None => crate::escrow::bookkeeping(d, inst.acts, &inst.thread.0, &signer.0, verb),
684    }
685    .map_err(Reject::Resource)?;
686    for (key, value) in bookkeeping {
687        params.push(SExpr::Atom(Atom::Keyword(key)));
688        params.push(value);
689    }
690    if let Some(addrs) = replaces {
691        params.push(SExpr::Atom(Atom::Keyword(String::from(RESERVED_REPLACES))));
692        params.push(SExpr::List(
693            addrs
694                .into_iter()
695                .map(|a| SExpr::Atom(Atom::Symbol(a)))
696                .collect(),
697        ));
698    }
699    params.push(SExpr::Atom(Atom::Keyword(String::from("from"))));
700    params.push(SExpr::Atom(Atom::Symbol(signer.0.clone())));
701    let recipient = match recipients.len() {
702        0 => None,
703        1 => Some(Recipients::One(recipients.into_iter().next().unwrap())),
704        _ => Some(Recipients::Set(recipients)),
705    };
706    let inner = Message::Simple {
707        performative: Performative::Custom(String::from(verb)),
708        recipient,
709        content: SExpr::List(Vec::new()),
710        params: crate::canonical::canonical_params(&params),
711        thread: Some(inst.thread.0.clone()),
712        sender: None,
713        caused_by: Some(caused_by),
714    };
715    let message = Message::Dialect {
716        dialect_name: d.name.clone(),
717        inner: alloc::boxed::Box::new(inner),
718    };
719
720    // 7 verify
721    let simple = message.innermost_simple().expect("built a simple message");
722    verify_state_shape(d, &message).map_err(Reject::Shape)?;
723    for shape in d.shapes.iter().filter(|s| s.performative == verb) {
724        shape.check(&SExpr::from(simple)).map_err(Reject::Shape)?;
725    }
726    let mut store = inst.store();
727    let address = ContentHash(wire_address(simple));
728    // The host signs the returned act; for verification the constructed
729    // act is viewed under the signed wrapper it will carry, so that role
730    // conformance can read the signer key (SPEC-014 REQ-612).
731    let signed = Message::Wrapped {
732        wrapper: WrapperType::Signed,
733        params: alloc::vec![SExpr::Atom(Atom::Symbol(signer.0.clone()))],
734        content: alloc::boxed::Box::new(message.clone()),
735    };
736    store.append(address.clone(), inst.thread.clone(), signed.clone());
737    let verdict = match (&inst.cast, inst.root) {
738        (Some(cast), Some(rt)) => {
739            let endpoint = Endpoint {
740                role: String::new(),
741                occupant: Some(signer.clone()),
742            };
743            verify_causal_for_role(
744                &signed,
745                &endpoint,
746                d,
747                cast,
748                &store,
749                &inst.thread,
750                &ContentHash(rt.address.clone()),
751            )
752        }
753        _ => verify_causal(verb, simple.caused_by(), &store, protocol, &inst.thread),
754    };
755    match verdict {
756        VerificationResult::Valid => {
757            if let Some((_, c)) = crate::escrow::rule_for(d, verb) {
758                let candidate =
759                    Act::from_message(message.clone(), &signer.0).map_err(Reject::Resource)?;
760                if c.certification.is_quorum() {
761                    let (engine, _) = authoring.as_ref().ok_or_else(|| {
762                        Reject::Resource("quorum-budget requires certificate runtime".into())
763                    })?;
764                    engine
765                        .check_candidate(&candidate)
766                        .map_err(Reject::Resource)?;
767                    return Ok(message);
768                }
769                match crate::escrow::observe_in(d, &inst.thread.0, c, inst.acts) {
770                    crate::escrow::Outcome::Ready(_) => {}
771                    other => return Err(Reject::Resource(other.value().render())),
772                }
773                match crate::escrow::check(c, inst.acts, &candidate) {
774                    crate::escrow::Outcome::Ready(_) => {}
775                    other => return Err(Reject::Resource(other.value().render())),
776                }
777            }
778            Ok(message)
779        }
780        other => Err(Reject::NotValid(other)),
781    }
782}
783
784/// The canonical text of an act, as the host signs it.
785pub fn canonical_text(message: &Message) -> String {
786    crate::serializer::serialize(&SExpr::from(message))
787}
788
789/// The content address of an act built by `intend`, wire spelling.
790pub fn address_of(message: &Message) -> Option<String> {
791    message.innermost_simple().map(wire_address)
792}
793
794impl Reject {
795    pub fn kind(&self) -> &'static str {
796        match self {
797            Reject::Resource(_) => "resource",
798            Reject::UnknownVerb => "unknown-verb",
799            Reject::Opener => "opener",
800            Reject::Forge(_) => "forge",
801            Reject::Role(_) => "role",
802            Reject::Domain(_) => "domain",
803            Reject::NothingToDelete => "nothing-to-delete",
804            Reject::NoPredecessor => "no-predecessor",
805            Reject::Shape(v) if v.rule == "resource-limit" => "resource-limit",
806            Reject::Shape(_) => "shape",
807            Reject::NotValid(_) => "not-valid",
808            Reject::NoOpener => "no-opener",
809        }
810    }
811}