1use super::types::{digest, text};
2use super::*;
3use crate::{
4 certification::{Certification, Committee},
5 dialect::Dialect,
6 escrow::{CounterRule, Outcome, Ownership},
7 intend::Instance,
8 role::AgentKey,
9 sexpr::{Atom, SExpr},
10 state::{Act, Rule},
11 store::ThreadId,
12};
13use alloc::{
14 collections::{BTreeMap, BTreeSet},
15 string::{String, ToString},
16 vec::Vec,
17};
18#[derive(Debug, Clone)]
19pub struct Context {
20 pub(crate) id: String,
21 pub(crate) field: String,
22 dialect: Dialect,
24 dialect_hash: String,
25 pub(crate) thread: ThreadId,
26 pub(crate) genesis: Vec<Act>,
27 pub(crate) opener: String,
28 pub(crate) rule: CounterRule,
29 pub(crate) committee: Committee,
30 pub(crate) initial: BTreeMap<String, Resources>,
31 root_ids: BTreeMap<String, String>,
34 root_manifests: BTreeMap<String, VersionManifest>,
35 pub(crate) issuers: BTreeSet<String>,
36 pub(crate) actors: BTreeSet<String>,
37}
38impl Context {
39 pub fn from_instance<A: Authentication>(
40 inst: &Instance,
41 field: &str,
42 validators: Option<&[String]>,
43 auth: &A,
44 ) -> Result<Self> {
45 let accepted = Instance::new(inst.dialect, inst.thread.clone(), inst.acts)?;
47 let inst = &accepted;
48 if !crate::r7::r7_violations(inst.dialect).is_empty() {
49 return Err("invalid bounded-counter dialect".into());
50 }
51 let Some(Rule::BoundedCounter(rule)) =
52 inst.dialect.state.as_ref().and_then(|s| s.rule_of(field))
53 else {
54 return Err("unknown bounded-counter field".into());
55 };
56 let committee = rule.certification.resolve(validators)?;
57 let opener = inst.opener.ok_or("missing opener")?;
58 let root = inst.root.ok_or("missing root")?;
59 if inst
60 .acts
61 .iter()
62 .any(|a| a.verb == rule.initial_verb && a.address != opener.address)
63 {
64 return Err("multiple resource openers in accepted history".into());
65 }
66
67 let genesis = alloc::vec![root.clone(), opener.clone()];
70 for act in &genesis {
71 if Act::from_message(act.message.clone(), &act.signer)? != *act
72 || !auth.authenticate_act(act)
73 {
74 return Err("unauthenticated genesis".into());
75 }
76 }
77 let bound = Instance::new(inst.dialect, inst.thread.clone(), &genesis)?;
78 let cast = bound.cast.as_ref().ok_or("missing cast")?;
79 let cast_keys: BTreeSet<String> = cast
80 .singleton
81 .values()
82 .chain(cast.indexed.values().flatten())
83 .map(|k| k.0.clone())
84 .collect();
85 let (initial, actors) = if rule.ownership == Ownership::Collective {
86 if cast_keys.contains(COLLECTIVE_POOL) {
87 return Err(
88 "collective resource scope is reserved and cannot be a cast key".into(),
89 );
90 }
91 if root.verb != "hello"
92 || root.simple().thread() != Some(inst.thread.0.as_str())
93 || !root.predecessors.is_empty()
94 || opener.predecessors != alloc::vec![root.address.clone()]
95 {
96 return Err("collective genesis root context mismatch".into());
97 }
98 let amount = match opener.fields.get(&rule.initial_key) {
99 Some(SExpr::Atom(Atom::Num(n))) if *n >= 0 => i128::from(*n),
100 _ => return Err("collective initial rights must be a nonnegative integer".into()),
101 };
102 let headroom = match rule.ceiling {
103 Some(cap) => i128::from(cap) - i128::from(rule.floor) - amount,
104 None => 0,
105 };
106 if headroom < 0 {
107 return Err("collective genesis exceeds ceiling".into());
108 }
109 (
110 [(
111 COLLECTIVE_POOL.into(),
112 Resources {
113 rights: amount,
114 headroom,
115 },
116 )]
117 .into_iter()
118 .collect(),
119 cast_keys,
120 )
121 } else {
122 let mut genesis_rule = (**rule).clone();
123 genesis_rule.certification = Certification::HostGate;
124 let snapshot = match crate::escrow::observe_in(
125 inst.dialect,
126 &inst.thread.0,
127 &genesis_rule,
128 &genesis,
129 ) {
130 Outcome::Ready(s) => s,
131 other => return Err(other.value().render()),
132 };
133 let initial: BTreeMap<_, _> = snapshot
134 .rights
135 .iter()
136 .map(|(k, n)| {
137 (
138 k.clone(),
139 Resources {
140 rights: *n,
141 headroom: snapshot
142 .headroom
143 .as_ref()
144 .and_then(|h| h.get(k))
145 .copied()
146 .unwrap_or(0),
147 },
148 )
149 })
150 .collect();
151 let actors = initial.keys().cloned().collect();
152 (initial, actors)
153 };
154 let issuers = actors
155 .iter()
156 .filter(|k| cast.admits(&rule.issuer, &AgentKey((*k).clone())))
157 .cloned()
158 .collect();
159 let dialect_hash = crate::canonical::dialect_hash(inst.dialect);
160 let id = digest(alloc::vec![
161 text("cbcl/quorum-context/multi-parent/v1"),
162 text(&dialect_hash),
163 text(&inst.thread.0),
164 text(&root.address),
165 text(&opener.address),
166 text(field),
167 SExpr::List(committee.validators.iter().map(|k| text(k)).collect()),
168 text(&committee.faults.to_string())
169 ]);
170 let mut root_ids = BTreeMap::new();
171 let mut root_manifests = BTreeMap::new();
172 for (account, allocation) in &initial {
173 let root = digest(alloc::vec![
174 text("cbcl/root-epoch/v1"),
175 text(&id),
176 text(account)
177 ]);
178 root_ids.insert(account.clone(), root.clone());
179 root_manifests.insert(
180 root,
181 VersionManifest {
182 phase: VersionPhase::Concurrent,
183 account: account.clone(),
184 parents: BTreeSet::new(),
185 rank: 0,
186 held: BTreeSet::new(),
187 refunded: BTreeSet::new(),
188 credited: BTreeSet::new(),
189 allocation: *allocation,
190 },
191 );
192 }
193 let context = Self {
194 id,
195 field: field.into(),
196 dialect: inst.dialect.clone(),
197 dialect_hash,
198 thread: inst.thread.clone(),
199 genesis,
200 opener: opener.address.clone(),
201 rule: (**rule).clone(),
202 committee,
203 initial,
204 root_ids,
205 root_manifests,
206 issuers,
207 actors,
208 };
209 if context.rule.ownership == Ownership::Collective {
210 context.structural(opener)?;
211 }
212 Ok(context)
213 }
214 pub fn id(&self) -> &str {
215 &self.id
216 }
217
218 pub fn committee(&self) -> &Committee {
219 &self.committee
220 }
221 pub fn ownership(&self) -> Ownership {
222 self.rule.ownership
223 }
224 pub fn pool(&self) -> Option<&str> {
225 (self.rule.ownership == Ownership::Collective).then_some(COLLECTIVE_POOL)
226 }
227 pub(crate) fn account<'a>(&self, actor: &'a str) -> Result<&'a str> {
228 if self.rule.ownership == Ownership::Collective
229 && (self.actors.contains(actor) || actor == COLLECTIVE_POOL)
230 {
231 return Ok(COLLECTIVE_POOL);
232 }
233 if self.initial.contains_key(actor) {
234 return Ok(actor);
235 }
236 Err("unknown actor or resource account".into())
237 }
238 pub(crate) fn version_actor(&self, account: &str, actor: &str) -> bool {
239 if self.rule.ownership == Ownership::Account {
240 return account == actor && self.initial.contains_key(actor);
241 }
242 if account != COLLECTIVE_POOL || !self.actors.contains(actor) {
243 return false;
244 }
245 let Ok(inst) = Instance::new(&self.dialect, self.thread.clone(), &self.genesis) else {
246 return false;
247 };
248 inst.cast.as_ref().is_some_and(|cast| {
249 self.rule.operation_verbs().iter().any(|v| {
250 self.dialect
251 .find_performative(v)
252 .and_then(|p| p.role.as_ref())
253 .is_some_and(|r| cast.admits(&r.from, &AgentKey(actor.into())))
254 })
255 })
256 }
257 pub fn root_epoch(&self, account: &str) -> Result<String> {
258 let account = self.account(account)?;
259 self.root_ids
260 .get(account)
261 .cloned()
262 .ok_or_else(|| "unknown actor or resource account".into())
263 }
264 pub(crate) fn root_manifest(&self, id: &str) -> Option<&VersionManifest> {
265 self.root_manifests.get(id)
266 }
267 pub(crate) fn request(&self, kind: VoteKind, payload: &str, signer: &str) -> SigningRequest {
268 SigningRequest {
269 vote: Vote {
270 context: self.id.clone(),
271 kind,
272 payload: payload.into(),
273 signer: signer.into(),
274 signature: Vec::new(),
275 },
276 }
277 }
278 pub fn cancellation_request(&self, owner: &str, operation: &str) -> Result<SigningRequest> {
279 if !self.actors.contains(owner) {
280 return Err("unknown owner".into());
281 }
282 Ok(self.request(VoteKind::CancelRequest, operation, owner))
283 }
284 pub fn version_request(
286 &self,
287 manifest: &VersionManifest,
288 actor: &str,
289 ) -> Result<SigningRequest> {
290 if !self.version_actor(&manifest.account, actor) {
291 return Err("unauthorized DAG version actor".into());
292 }
293 Ok(self.request(VoteKind::VersionRequest, &manifest.id(&self.id), actor))
294 }
295 pub fn owned_seal_request(
297 &self,
298 manifest: &VersionManifest,
299 actor: &str,
300 ) -> Result<SigningRequest> {
301 if manifest.phase != VersionPhase::Owned
302 || self.ownership() != Ownership::Account
303 || !self.version_actor(&manifest.account, actor)
304 {
305 return Err("only the account owner can authorize a permanent seal".into());
306 }
307 Ok(self.request(VoteKind::OwnedSealRequest, &manifest.id(&self.id), actor))
308 }
309 pub(crate) fn matches(&self, inst: &Instance) -> bool {
310 self.thread == inst.thread
311 && inst.instance_id() == Some(self.opener.as_str())
312 && crate::canonical::dialect_hash(inst.dialect) == self.dialect_hash
313 }
314 pub(crate) fn structural(&self, act: &Act) -> Result<()> {
315 act.validate_identity()?;
316 if !self.actors.contains(&act.signer) {
317 return Err("owner outside pinned accounts".into());
318 }
319 fn language(m: &crate::message::Message) -> Option<&str> {
320 match m {
321 crate::message::Message::Dialect { dialect_name, .. } => Some(dialect_name),
322 crate::message::Message::Wrapped { content, .. } => language(content),
323 _ => None,
324 }
325 }
326 if act.simple().thread() != Some(self.thread.0.as_str())
327 || language(&act.message) != Some(self.dialect.name.as_str())
328 {
329 return Err("act context mismatch".into());
330 }
331 let crate::message::Message::Simple { params, .. } = act.simple() else {
333 return Err("not simple".into());
334 };
335 let mut seen = BTreeSet::new();
336 for pair in params.chunks(2) {
337 let [SExpr::Atom(Atom::Keyword(key)), _] = pair else {
338 return Err("malformed resource parameters".into());
339 };
340 if !seen.insert(key) {
341 return Err("duplicate resource keyword".into());
342 }
343 }
344 crate::r7::verify_state_shape(&self.dialect, &act.message)
346 .map_err(|e| alloc::format!("{e}"))?;
347 for shape in self
348 .dialect
349 .shapes
350 .iter()
351 .filter(|s| s.performative == act.verb)
352 {
353 shape
354 .check(&SExpr::from(act.simple()))
355 .map_err(|e| alloc::format!("{e}"))?;
356 }
357 let inst = Instance::new(&self.dialect, self.thread.clone(), &self.genesis)?;
358 if let Some(role) = self
359 .dialect
360 .find_performative(&act.verb)
361 .and_then(|p| p.role.as_ref())
362 {
363 if !inst
364 .cast
365 .as_ref()
366 .is_some_and(|cast| cast.admits(&role.from, &AgentKey(act.signer.clone())))
367 {
368 return Err("owner role not admitted".into());
369 }
370 }
371 if act.fields.contains_key("from") {
372 return Err("routing field in data".into());
373 }
374 let crate::message::Message::Simple { params, .. } = act.simple() else {
375 return Err("not simple".into());
376 };
377 let from = params.windows(2).find_map(|p| match (&p[0], &p[1]) {
378 (SExpr::Atom(Atom::Keyword(k)), SExpr::Atom(Atom::Symbol(v))) if k == "from" => Some(v),
379 _ => None,
380 });
381 if from != Some(&act.signer) {
382 return Err("from does not match authenticated owner".into());
383 }
384 Ok(())
385 }
386}