interplane.Get Omega
Read in your language

aien-protocols-mv

Canonical specifications, wire protocols, and schemas for the AIEN sovereign ecosystem

Brought by drakestapleton

branch main Branches Tags History

aien-protocols-mv / crates / aien-discovery-capsule / src / recipient.rs

489 lines · 16132 bytes Raw Blame History
1//! Stateful recipient rules of SPEC.md section 11: the owner's retraction
2//! chain, use checks for serving / training / republication, execution
3//! admission, honest retraction delivery status, and experience lineage.
4//!
5//! Every function takes [`Verified`] records, so static rules and signatures
6//! have always been checked first. A refusal changes no state.
7
8use std::collections::HashMap;
9
10use crate::{
11 key_digest, perm, recipients_digest, retract, scope, Ack, Capsule, Consent, Lineage, Refusal,
12 Retraction, Verified,
13};
14
15/// Whether an apply changed state.
16#[derive(Debug, Clone, Copy, PartialEq, Eq)]
17pub enum Applied {
18 New,
19 Replay,
20}
21
22/// One owner's retraction chain as one node knows it.
23#[derive(Debug, Clone)]
24pub struct OwnerChain {
25 owner: [u8; 33],
26 custodians: Vec<[u8; 32]>,
27 entries: Vec<(Retraction, [u8; 32])>,
28}
29
30impl OwnerChain {
31 /// An empty chain for `consent`'s owner, with the custodians that consent
32 /// declares (and no others).
33 pub fn new(consent: &Verified<Consent>) -> Self {
34 OwnerChain {
35 owner: consent.get().owner_key,
36 custodians: consent.get().custodians.clone(),
37 entries: Vec::new(),
38 }
39 }
40
41 /// The owner whose chain this is.
42 pub fn owner(&self) -> [u8; 33] {
43 self.owner
44 }
45
46 /// Sequence of the newest retraction, 0 when none.
47 pub fn head_seq(&self) -> u64 {
48 self.entries.len() as u64
49 }
50
51 /// `record_digest` of the retraction at `seq` (1-based).
52 pub fn digest_at(&self, seq: u64) -> Option<[u8; 32]> {
53 if seq == 0 {
54 return None;
55 }
56 self.entries.get(seq as usize - 1).map(|(_, d)| *d)
57 }
58
59 /// Append one retraction. Concurrent conflicting operations, gaps and a
60 /// wrong `prev_retraction` fail closed (`DCP_CONFLICT`).
61 pub fn apply(&mut self, r: &Verified<Retraction>) -> Result<Applied, Refusal> {
62 let x = r.get();
63 if x.owner_key != self.owner {
64 return Err(Refusal::OwnerMismatch);
65 }
66 if x.signer_key != self.owner && !self.custodians.contains(&key_digest(&x.signer_key)) {
67 return Err(Refusal::UnknownCustodian);
68 }
69 let head = self.head_seq();
70 if x.seq <= head {
71 return if self.digest_at(x.seq) == Some(r.digest()) {
72 Ok(Applied::Replay)
73 } else {
74 Err(Refusal::Conflict)
75 };
76 }
77 let prev_ok = if x.seq == 1 {
78 true
79 } else {
80 self.digest_at(head) == Some(x.prev_retraction)
81 };
82 if x.seq != head + 1 || !prev_ok {
83 return Err(Refusal::Conflict);
84 }
85 self.entries.push((x.clone(), r.digest()));
86 Ok(Applied::New)
87 }
88
89 /// Whether a retraction in effect at `now` targets `target` with any of
90 /// `scope_bits`.
91 pub fn retracts(&self, target: &[u8; 32], scope_bits: u8, now: u64) -> bool {
92 self.entries.iter().any(|(r, _)| {
93 &r.target_digest == target && r.scope & scope_bits != 0 && r.effective_at <= now
94 })
95 }
96}
97
98/// The use a recipient asks to make of a capsule.
99#[derive(Debug, Clone, Copy, PartialEq, Eq)]
100pub enum Use {
101 /// Retrieve and read.
102 Serve,
103 /// Make it training-eligible.
104 Train,
105 /// Pass it on.
106 Republish,
107}
108
109impl Use {
110 fn permission(self) -> u8 {
111 match self {
112 Use::Serve => perm::READ,
113 Use::Train => perm::TRAIN,
114 Use::Republish => perm::REDISTRIBUTE,
115 }
116 }
117 fn retraction_scope(self) -> u8 {
118 match self {
119 Use::Serve => retract::FUTURE_AVAILABILITY | retract::RETRIEVAL,
120 Use::Train => retract::TRAINING,
121 Use::Republish => retract::REPUBLICATION,
122 }
123 }
124}
125
126/// What the recipient knows when it asks.
127#[derive(Debug, Clone)]
128pub struct UseRequest<'a> {
129 pub use_: Use,
130 pub requester: [u8; 33],
131 /// The full NAMED recipient list, when the capsule is NAMED.
132 pub named_recipients: &'a [[u8; 33]],
133 pub now: u64,
134 /// The newest `consent_version` this node knows for the same fragment.
135 pub newest_consent_version: u32,
136 /// The parent capsule, when `parent_capsule` is not zero.
137 pub parent: Option<&'a Verified<Capsule>>,
138}
139
140/// Check one use of a capsule against its consent and the owner's chain
141/// (SPEC.md section 11). `Ok` means "this use is not refused by the capsule
142/// contract"; it is not an authorization for any effect.
143pub fn check_use(
144 capsule: &Verified<Capsule>,
145 consent: Option<&Verified<Consent>>,
146 chain: &OwnerChain,
147 req: &UseRequest<'_>,
148) -> Result<(), Refusal> {
149 let c = capsule.get();
150 if chain.owner() != c.owner_key || consent.is_some_and(|k| k.get().owner_key != c.owner_key) {
151 return Err(Refusal::OwnerMismatch);
152 }
153 if c.share_scope == scope::PRIVATE && req.requester != c.owner_key {
154 return Err(Refusal::Private);
155 }
156 let needs_consent = c.permissions & (perm::READ | perm::REDISTRIBUTE | perm::TRAIN) != 0
157 || c.share_scope != scope::PRIVATE;
158 if needs_consent {
159 match consent {
160 Some(k)
161 if k.digest() == c.consent_ref && k.get().fragment_digest == c.meaning_digest => {}
162 _ => return Err(Refusal::NoConsent),
163 }
164 }
165 if let Some(k) = consent {
166 if c.permissions & !k.get().purposes != 0 {
167 return Err(Refusal::PermissionAmplification);
168 }
169 }
170 if c.parent_capsule != [0; 32] {
171 match req.parent {
172 Some(p) if p.digest() == c.parent_capsule => {
173 if c.permissions & !p.get().permissions != 0 {
174 return Err(Refusal::PermissionAmplification);
175 }
176 }
177 _ => return Err(Refusal::UnknownParent),
178 }
179 }
180 if req.requester != c.owner_key && c.permissions & req.use_.permission() == 0 {
181 return Err(Refusal::NotPermitted);
182 }
183 if c.share_scope == scope::NAMED
184 && req.requester != c.owner_key
185 && (recipients_digest(req.named_recipients) != c.recipient_set_digest
186 || !req.named_recipients.contains(&req.requester))
187 {
188 return Err(Refusal::NotRecipient);
189 }
190 if req.now < c.valid_from
191 || req.now > c.expires_at
192 || consent.is_some_and(|k| req.now > k.get().retention_end)
193 {
194 return Err(Refusal::Expired);
195 }
196 if c.revocation_seq > chain.head_seq()
197 || consent.is_some_and(|k| req.newest_consent_version > k.get().consent_version)
198 {
199 return Err(Refusal::Stale);
200 }
201 if c.revocation_seq > 0 && chain.digest_at(c.revocation_seq) != Some(c.revocation_head) {
202 return Err(Refusal::Conflict);
203 }
204 let bits = req.use_.retraction_scope();
205 if chain.retracts(&capsule.digest(), bits, req.now)
206 || chain.retracts(&c.meaning_digest, bits, req.now)
207 {
208 return Err(Refusal::Revoked);
209 }
210 Ok(())
211}
212
213/// A verdict from the recipient's own independent verifier, run on the
214/// recipient's platform. Local to the recipient; not a wire record.
215#[derive(Debug, Clone, PartialEq, Eq)]
216pub struct RecipientVerdict {
217 pub capsule_digest: [u8; 32],
218 pub platform_digest: [u8; 32],
219 pub verifier_key: [u8; 33],
220 pub passed: bool,
221}
222
223/// The result of [`admit_execution`]: which capsule may run, on which
224/// platform, within which requested capabilities. Effects still need AEGIS.
225#[derive(Debug, Clone, PartialEq, Eq)]
226pub struct ExecutionAdmission {
227 pub capsule_digest: [u8; 32],
228 pub platform_digest: [u8; 32],
229 pub capabilities: u32,
230}
231
232/// Admit a capsule for execution on `platform_digest`: only with a passing
233/// verdict from a verifier that is not the owner, for this exact capsule and
234/// platform, and only within `granted` capabilities.
235pub fn admit_execution(
236 capsule: &Verified<Capsule>,
237 verdict: &RecipientVerdict,
238 platform_digest: [u8; 32],
239 granted: u32,
240) -> Result<ExecutionAdmission, Refusal> {
241 let c = capsule.get();
242 if verdict.verifier_key == c.owner_key {
243 return Err(Refusal::SelfAuthorized);
244 }
245 if !verdict.passed
246 || verdict.capsule_digest != capsule.digest()
247 || verdict.platform_digest != platform_digest
248 {
249 return Err(Refusal::Unverified);
250 }
251 if c.required_capabilities & !granted != 0 {
252 return Err(Refusal::CapabilityDenied);
253 }
254 Ok(ExecutionAdmission {
255 capsule_digest: capsule.digest(),
256 platform_digest,
257 capabilities: c.required_capabilities,
258 })
259}
260
261/// Delivery status of one retraction at one recipient. There is no "erased".
262#[derive(Debug, Clone, Copy, PartialEq, Eq)]
263pub enum Delivery {
264 Pending,
265 Acknowledged { status: u8, acked_at: u64 },
266 Unreachable,
267}
268
269/// The owner-side view of one retraction's propagation (section 11.1).
270#[derive(Debug, Clone)]
271pub struct RetractionTracker {
272 retraction: [u8; 32],
273 recipients: Vec<([u8; 33], Delivery, Option<[u8; 32]>)>,
274}
275
276impl RetractionTracker {
277 /// Track `retraction` as sent to `recipients`; every one starts PENDING.
278 pub fn new(retraction: &Verified<Retraction>, recipients: &[[u8; 33]]) -> Self {
279 RetractionTracker {
280 retraction: retraction.digest(),
281 recipients: recipients
282 .iter()
283 .map(|k| (*k, Delivery::Pending, None))
284 .collect(),
285 }
286 }
287
288 /// Record one signed acknowledgement.
289 pub fn apply_ack(&mut self, ack: &Verified<Ack>) -> Result<Applied, Refusal> {
290 let a = ack.get();
291 if a.retraction_digest != self.retraction {
292 return Err(Refusal::Conflict);
293 }
294 let slot = self
295 .recipients
296 .iter_mut()
297 .find(|(k, _, _)| *k == a.recipient_key)
298 .ok_or(Refusal::NotRecipient)?;
299 match slot.2 {
300 Some(d) if d == ack.digest() => Ok(Applied::Replay),
301 Some(_) => Err(Refusal::Conflict),
302 None => {
303 slot.1 = Delivery::Acknowledged {
304 status: a.status,
305 acked_at: a.acked_at,
306 };
307 slot.2 = Some(ack.digest());
308 Ok(Applied::New)
309 }
310 }
311 }
312
313 /// Mark a recipient that cannot be reached; it is never shown as
314 /// acknowledged.
315 pub fn mark_unreachable(&mut self, key: &[u8; 33]) -> Result<(), Refusal> {
316 let slot = self
317 .recipients
318 .iter_mut()
319 .find(|(k, _, _)| k == key)
320 .ok_or(Refusal::NotRecipient)?;
321 if slot.2.is_none() {
322 slot.1 = Delivery::Unreachable;
323 }
324 Ok(())
325 }
326
327 /// Delivery status of one recipient.
328 pub fn status(&self, key: &[u8; 33]) -> Option<Delivery> {
329 self.recipients
330 .iter()
331 .find(|(k, _, _)| k == key)
332 .map(|(_, d, _)| *d)
333 }
334
335 /// Recipients still PENDING.
336 pub fn pending(&self) -> Vec<[u8; 33]> {
337 self.filter(|d| d == Delivery::Pending)
338 }
339
340 /// Recipients that acknowledged but retain copies or trained descendants.
341 pub fn retained(&self) -> Vec<[u8; 33]> {
342 self.filter(|d| {
343 matches!(
344 d,
345 Delivery::Acknowledged {
346 status: crate::ack_status::ENFORCED_WITH_RETAINED,
347 ..
348 }
349 )
350 })
351 }
352
353 /// True only when every recipient acknowledged. Even then this says
354 /// "future use stopped at compliant recipients", never "erased".
355 pub fn all_acknowledged(&self) -> bool {
356 self.recipients
357 .iter()
358 .all(|(_, d, _)| matches!(d, Delivery::Acknowledged { .. }))
359 }
360
361 fn filter(&self, f: impl Fn(Delivery) -> bool) -> Vec<[u8; 33]> {
362 self.recipients
363 .iter()
364 .filter(|(_, d, _)| f(*d))
365 .map(|(k, _, _)| *k)
366 .collect()
367 }
368}
369
370/// Experience lineage known to one node, keyed by `content_digest`.
371#[derive(Debug, Clone, Default)]
372pub struct LineageIndex {
373 records: HashMap<[u8; 32], (Lineage, [u8; 32])>,
374}
375
376impl LineageIndex {
377 pub fn new() -> Self {
378 Self::default()
379 }
380
381 /// Add one record. A second, different record for one content is
382 /// `DCP_DUPLICATE`; a known parent from another dataset is
383 /// `DCP_CROSS_DATASET`; a parent chain that leads back here is
384 /// `DCP_ANCESTOR_CYCLE`. Unknown parents are allowed here (offline sync)
385 /// and refused when ancestry is needed.
386 pub fn add(&mut self, l: &Verified<Lineage>) -> Result<Applied, Refusal> {
387 let x = l.get();
388 if let Some((_, d)) = self.records.get(&x.content_digest) {
389 return if *d == l.digest() {
390 Ok(Applied::Replay)
391 } else {
392 Err(Refusal::Duplicate)
393 };
394 }
395 for p in &x.parents {
396 if let Some((parent, _)) = self.records.get(p) {
397 if parent.dataset_id != x.dataset_id {
398 return Err(Refusal::CrossDataset);
399 }
400 }
401 }
402 let mut stack: Vec<[u8; 32]> = x.parents.clone();
403 let mut seen: Vec<[u8; 32]> = Vec::new();
404 while let Some(c) = stack.pop() {
405 if c == x.content_digest {
406 return Err(Refusal::AncestorCycle);
407 }
408 if seen.contains(&c) {
409 continue;
410 }
411 seen.push(c);
412 if let Some((r, _)) = self.records.get(&c) {
413 stack.extend(r.parents.iter().copied());
414 }
415 }
416 self.records
417 .insert(x.content_digest, (x.clone(), l.digest()));
418 Ok(Applied::New)
419 }
420
421 /// `content` and all its ancestors. Every ancestor must be held.
422 pub fn ancestry(&self, content: &[u8; 32]) -> Result<Vec<[u8; 32]>, Refusal> {
423 let mut out: Vec<[u8; 32]> = Vec::new();
424 let mut stack = vec![*content];
425 while let Some(c) = stack.pop() {
426 if out.contains(&c) {
427 continue;
428 }
429 let (r, _) = self.records.get(&c).ok_or(Refusal::UnknownParent)?;
430 out.push(c);
431 stack.extend(r.parents.iter().copied());
432 }
433 Ok(out)
434 }
435
436 /// Whether `content` may be used for training: every ancestor held, in
437 /// one dataset, and none retracted for TRAINING in its owner's chain.
438 pub fn training_eligible(
439 &self,
440 content: &[u8; 32],
441 chains: &[&OwnerChain],
442 now: u64,
443 ) -> Result<(), Refusal> {
444 let all = self.ancestry(content)?;
445 let dataset = self.records[content].0.dataset_id;
446 for c in &all {
447 let (r, _) = &self.records[c];
448 if r.dataset_id != dataset {
449 return Err(Refusal::CrossDataset);
450 }
451 let chain = chains
452 .iter()
453 .find(|ch| ch.owner() == r.owner_key)
454 .ok_or(Refusal::Stale)?;
455 if chain.retracts(c, retract::TRAINING, now) {
456 return Err(Refusal::Revoked);
457 }
458 }
459 Ok(())
460 }
461
462 /// The checkpoints and capsules influenced by `target` or any of its
463 /// descendants: what must be marked affected after a retraction.
464 pub fn affected(&self, target: &[u8; 32]) -> Vec<[u8; 32]> {
465 let mut hit: Vec<[u8; 32]> = vec![*target];
466 let mut grew = true;
467 while grew {
468 grew = false;
469 for (c, (r, _)) in &self.records {
470 if !hit.contains(c) && r.parents.iter().any(|p| hit.contains(p)) {
471 hit.push(*c);
472 grew = true;
473 }
474 }
475 }
476 let mut out: Vec<[u8; 32]> = Vec::new();
477 for c in &hit {
478 if let Some((r, _)) = self.records.get(c) {
479 for i in &r.influenced {
480 if !out.contains(i) {
481 out.push(*i);
482 }
483 }
484 }
485 }
486 out.sort();
487 out
488 }
489}