Skip to main content

pask_wire/
proposed_content.rs

1// SPDX-License-Identifier: Apache-2.0
2// Copyright (c) 2026 Wilder Management Inc. (d/b/a Wilder Robotics)
3//! LOCAL PROPOSAL: salted fact membership, not a frozen PSER wire format.
4//!
5//! The input is canonical fact JSON, not original evidence bytes. This component
6//! never rewrites a signed statement or evidence object. A matched caller root
7//! does not authenticate its origin, a receipt, a fact attribution, or the truth
8//! of a value. Vocabulary constraints and evidence comparison remain separate.
9
10use alloc::{string::String, vec::Vec};
11use serde::Serialize;
12use serde_json::Value;
13use sha2::{Digest, Sha256};
14
15pub const CONSTRUCTION: &str = "pask-local-content-tree/1";
16pub const SCOPE: &str = "PRESENTED_AT_SEAL";
17pub const MAX_FACTS: usize = 256;
18pub const MAX_FACT_BYTES: usize = 16_384;
19pub const MAX_TOTAL_FACT_BYTES: usize = 1_048_576;
20pub const MAX_JSON_DEPTH: usize = 16;
21pub const MAX_PROOF_HASHES: usize = 8;
22const DOMAIN: &[u8] = b"PASK-LOCAL-CONTENT-TREE/1\0";
23const MAX_SAFE_INTEGER: u64 = 9_007_199_254_740_991;
24
25type Hash = [u8; 32];
26
27#[derive(Debug, Clone, Copy, PartialEq, Eq)]
28pub enum ContentError {
29    UnsupportedConstruction,
30    InvalidScope,
31    InvalidDigest,
32    FactCountLimit,
33    FactByteLimit,
34    TotalByteLimit,
35    JsonDepthLimit,
36    InvalidFactJson,
37    NonCanonicalFact,
38    UnsupportedNumber,
39    InvalidFactShape,
40    InvalidFactName,
41    DuplicateFactName,
42    ReusedSalt,
43    UnknownFactName,
44    InvalidIndex,
45    InvalidProofLength,
46    RootMismatch,
47    DuplicateDisclosure,
48    UnorderedNames,
49}
50
51#[derive(Clone, Copy, Debug)]
52pub struct ContentHeader<'a> {
53    pub construction: &'a str,
54    pub scope: &'a str,
55    /// Digest identifies the vocabulary; this API does not retrieve or validate it.
56    pub vocabulary_digest: &'a str,
57}
58
59#[derive(Clone, Copy, Debug)]
60pub struct SaltedFact<'a> {
61    /// Complete canonical JSON object, including all extra properties.
62    pub record: &'a [u8],
63    /// Caller supplies a fresh unpredictable salt; entropy is not verified here.
64    pub salt: Hash,
65}
66
67#[derive(Clone, Debug)]
68pub struct DisclosedFact<'a> {
69    pub record: &'a [u8],
70    pub salt: Hash,
71    pub index: u32,
72    /// Bottom-up siblings; directions follow index and total count, not caller flags.
73    pub siblings: Vec<Hash>,
74}
75
76#[derive(Debug, Serialize)]
77pub struct DisclosureReport {
78    pub schema: &'static str,
79    pub membership: &'static str,
80    pub disclosure: &'static str,
81    pub presented_facts: usize,
82    /// Authenticated to the supplied root only if membership is MATCHED.
83    pub claimed_fact_count: usize,
84    pub count_bound_to_supplied_root: bool,
85    pub root_origin: &'static str,
86    pub receipt_binding: &'static str,
87    pub fact_constraints: &'static str,
88    pub evidence_comparison: &'static str,
89    pub attributed_party_authenticated: bool,
90    pub latest_or_complete_history_established: bool,
91    pub semantic_absence_established: bool,
92}
93
94/// Validated bounded material for producing full or selected disclosures.
95/// Sorted order is ASCII fact-name order. Neither facts nor salts are regenerated.
96#[derive(Debug)]
97pub struct PreparedContent<'a> {
98    root: Hash,
99    header_hash: Hash,
100    facts: Vec<SaltedFact<'a>>,
101    names: Vec<String>,
102    leaves: Vec<Hash>,
103}
104
105fn hash(parts: &[&[u8]]) -> Hash {
106    let mut hasher = Sha256::new();
107    hasher.update(DOMAIN);
108    for part in parts {
109        hasher.update(part);
110    }
111    hasher.finalize().into()
112}
113
114fn digest_bytes(text: &str) -> Result<Hash, ContentError> {
115    if text.len() != 71 || !text.starts_with("sha256:") {
116        return Err(ContentError::InvalidDigest);
117    }
118    let mut result = [0; 32];
119    let (pairs, remainder) = text.as_bytes()[7..].as_chunks::<2>();
120    if !remainder.is_empty() {
121        return Err(ContentError::InvalidDigest);
122    }
123    fn nibble(b: u8) -> Result<u8, ContentError> {
124        match b {
125            b'0'..=b'9' => Ok(b - b'0'),
126            b'a'..=b'f' => Ok(b - b'a' + 10),
127            _ => Err(ContentError::InvalidDigest),
128        }
129    }
130    for (out, pair) in result.iter_mut().zip(pairs) {
131        *out = nibble(pair[0])? * 16 + nibble(pair[1])?;
132    }
133    Ok(result)
134}
135
136fn header_hash(header: &ContentHeader<'_>, count: usize) -> Result<Hash, ContentError> {
137    if header.construction != CONSTRUCTION {
138        return Err(ContentError::UnsupportedConstruction);
139    }
140    if header.scope != SCOPE {
141        return Err(ContentError::InvalidScope);
142    }
143    if count > MAX_FACTS {
144        return Err(ContentError::FactCountLimit);
145    }
146    let vocabulary = digest_bytes(header.vocabulary_digest)?;
147    // Fixed construction and scope are bound literally. No caller-selected encoding.
148    Ok(hash(&[
149        &[0],
150        &(count as u64).to_be_bytes(),
151        &(CONSTRUCTION.len() as u64).to_be_bytes(),
152        CONSTRUCTION.as_bytes(),
153        &(SCOPE.len() as u64).to_be_bytes(),
154        SCOPE.as_bytes(),
155        &vocabulary,
156    ]))
157}
158
159// Check an integer-form token by its original decimal digits, before serde can
160// represent an overflowing i64/u64 token as f64. This is not a JSON parser:
161// malformed number tokens are still rejected by the subsequent complete parse.
162fn integer_token_is_supported(token: &[u8]) -> bool {
163    const MAX_DIGITS: &[u8] = b"9007199254740991";
164    let digits = token.strip_prefix(b"-").unwrap_or(token);
165    if digits.is_empty()
166        || !digits.iter().all(u8::is_ascii_digit)
167        || (digits.len() > 1 && digits[0] == b'0')
168    {
169        // Fraction/exponent forms and invalid syntax are not integer tokens.
170        // They remain subject to the parser, finite-number and JCS checks.
171        return true;
172    }
173    digits.len() < MAX_DIGITS.len() || (digits.len() == MAX_DIGITS.len() && digits <= MAX_DIGITS)
174}
175
176// Bound bytes, nesting and lexical integer magnitude before serde allocates the
177// parsed tree. Quoted digits are not number tokens. This does not validate JSON
178// syntax; the subsequent parser must consume all input. No bytes are rewritten.
179fn raw_preflight(bytes: &[u8]) -> Result<(), ContentError> {
180    if bytes.len() > MAX_FACT_BYTES {
181        return Err(ContentError::FactByteLimit);
182    }
183    let (mut depth, mut string, mut escaped) = (0usize, false, false);
184    let mut offset = 0;
185    while offset < bytes.len() {
186        let b = bytes[offset];
187        if string {
188            if escaped {
189                escaped = false;
190            } else if b == b'\\' {
191                escaped = true;
192            } else if b == b'"' {
193                string = false;
194            }
195        } else {
196            match b {
197                b'"' => string = true,
198                b'{' | b'[' => {
199                    depth += 1;
200                    if depth > MAX_JSON_DEPTH {
201                        return Err(ContentError::JsonDepthLimit);
202                    }
203                }
204                b'}' | b']' => {
205                    depth = depth.checked_sub(1).ok_or(ContentError::InvalidFactJson)?;
206                }
207                b'-' | b'0'..=b'9' => {
208                    let start = offset;
209                    while offset < bytes.len()
210                        && matches!(
211                            bytes[offset],
212                            b'0'..=b'9' | b'-' | b'+' | b'.' | b'e' | b'E'
213                        )
214                    {
215                        offset += 1;
216                    }
217                    if !integer_token_is_supported(&bytes[start..offset]) {
218                        return Err(ContentError::UnsupportedNumber);
219                    }
220                    continue;
221                }
222                _ => {}
223            }
224        }
225        offset += 1;
226    }
227    Ok(())
228}
229
230fn safe_numbers(value: &Value) -> bool {
231    match value {
232        Value::Number(number) => {
233            if let Some(integer) = number.as_i64() {
234                integer.unsigned_abs() <= MAX_SAFE_INTEGER
235            } else if let Some(integer) = number.as_u64() {
236                integer <= MAX_SAFE_INTEGER
237            } else {
238                number.as_f64().is_some_and(f64::is_finite)
239            }
240        }
241        Value::Array(items) => items.iter().all(safe_numbers),
242        Value::Object(items) => items.values().all(safe_numbers),
243        _ => true,
244    }
245}
246
247fn fact_name(bytes: &[u8]) -> Result<String, ContentError> {
248    raw_preflight(bytes)?;
249    let value: Value = serde_json::from_slice(bytes).map_err(|_| ContentError::InvalidFactJson)?;
250    if !safe_numbers(&value) {
251        return Err(ContentError::UnsupportedNumber);
252    }
253    let canonical = crate::canonicalize_json(bytes).map_err(|_| ContentError::InvalidFactJson)?;
254    if canonical != bytes {
255        // Also rejects duplicate properties: their original input cannot equal
256        // canonical serialization of the unique-property parsed object.
257        return Err(ContentError::NonCanonicalFact);
258    }
259    let object = value.as_object().ok_or(ContentError::InvalidFactShape)?;
260    let name = object
261        .get("name")
262        .and_then(Value::as_str)
263        .ok_or(ContentError::InvalidFactShape)?;
264    if name.is_empty()
265        || name.len() > 128
266        || !name
267            .bytes()
268            .all(|b| b.is_ascii_lowercase() || b.is_ascii_digit() || b == b'.' || b == b'-')
269    {
270        return Err(ContentError::InvalidFactName);
271    }
272    if !object.contains_key("value")
273        || object.get("assertedBy").and_then(Value::as_str).is_none()
274        || object.get("basis").and_then(Value::as_str).is_none()
275    {
276        return Err(ContentError::InvalidFactShape);
277    }
278    // Deliberately do not run the vocabulary constraint classifier here.
279    // A well-formed forbidden attribution must remain provable and reportable.
280    Ok(String::from(name))
281}
282
283fn leaf(header: &Hash, index: usize, fact: &SaltedFact<'_>) -> Hash {
284    hash(&[
285        &[1],
286        header,
287        &(index as u64).to_be_bytes(),
288        &fact.salt,
289        &(fact.record.len() as u64).to_be_bytes(),
290        fact.record,
291    ])
292}
293
294fn split(count: usize) -> usize {
295    // Used only for 2..=MAX_FACTS. Largest power of two strictly below count.
296    let mut result = 1;
297    while result * 2 < count {
298        result *= 2;
299    }
300    result
301}
302
303fn tree_hash(leaves: &[Hash], header: &Hash) -> Hash {
304    match leaves {
305        [] => hash(&[&[2], header]),
306        [only] => *only,
307        _ => {
308            let (left, right) = leaves.split_at(split(leaves.len()));
309            hash(&[&[3], &tree_hash(left, header), &tree_hash(right, header)])
310        }
311    }
312}
313
314fn root_hash(header: &Hash, tree: &Hash) -> Hash {
315    hash(&[&[4], header, tree])
316}
317
318fn inclusion_path(leaves: &[Hash], index: usize, header: &Hash, path: &mut Vec<Hash>) {
319    if leaves.len() <= 1 {
320        return;
321    }
322    let k = split(leaves.len());
323    let (left, right) = leaves.split_at(k);
324    if index < k {
325        inclusion_path(left, index, header, path);
326        path.push(tree_hash(right, header));
327    } else {
328        inclusion_path(right, index - k, header, path);
329        path.push(tree_hash(left, header));
330    }
331}
332
333fn reconstructed_tree(
334    count: usize,
335    index: usize,
336    value: Hash,
337    path: &[Hash],
338    used: &mut usize,
339) -> Result<Hash, ContentError> {
340    if count == 1 {
341        return Ok(value);
342    }
343    let k = split(count);
344    let child = if index < k {
345        reconstructed_tree(k, index, value, path, used)?
346    } else {
347        reconstructed_tree(count - k, index - k, value, path, used)?
348    };
349    let sibling = path.get(*used).ok_or(ContentError::InvalidProofLength)?;
350    *used += 1;
351    Ok(if index < k {
352        hash(&[&[3], &child, sibling])
353    } else {
354        hash(&[&[3], sibling, &child])
355    })
356}
357
358fn report(count: usize, presented: usize, matched: bool) -> DisclosureReport {
359    DisclosureReport {
360        schema: "pask-local-content-disclosure-report/1",
361        membership: if matched { "MATCHED" } else { "NOT_PRESENTED" },
362        disclosure: if matched && presented == count {
363            "ALL_COMMITTED_SLOTS"
364        } else if matched {
365            "SELECTED_SLOTS_ONLY"
366        } else {
367            "NOT_PRESENTED"
368        },
369        presented_facts: presented,
370        claimed_fact_count: count,
371        count_bound_to_supplied_root: matched,
372        root_origin: "CALLER_SUPPLIED_UNAUTHENTICATED",
373        receipt_binding: "NOT_EVALUATED",
374        fact_constraints: "NOT_EVALUATED",
375        evidence_comparison: "NOT_RUN",
376        attributed_party_authenticated: false,
377        latest_or_complete_history_established: false,
378        semantic_absence_established: false,
379    }
380}
381
382/// Prepare bounded local commitments. Input order is irrelevant; ASCII fact names
383/// determine leaf order. Duplicate names and repeated salts in this block reject.
384/// Salt freshness/randomness across blocks cannot be established by this function.
385pub fn prepare_content<'a>(
386    header: &ContentHeader<'_>,
387    facts: &[SaltedFact<'a>],
388) -> Result<PreparedContent<'a>, ContentError> {
389    let h = header_hash(header, facts.len())?;
390    let mut total = 0usize;
391    let mut rows = Vec::with_capacity(facts.len());
392    for (i, fact) in facts.iter().enumerate() {
393        if fact.record.len() > MAX_TOTAL_FACT_BYTES - total {
394            return Err(ContentError::TotalByteLimit);
395        }
396        total += fact.record.len();
397        if facts[..i].iter().any(|previous| previous.salt == fact.salt) {
398            return Err(ContentError::ReusedSalt);
399        }
400        rows.push((fact_name(fact.record)?, *fact));
401    }
402    rows.sort_by(|a, b| a.0.cmp(&b.0));
403    if rows.windows(2).any(|pair| pair[0].0 == pair[1].0) {
404        return Err(ContentError::DuplicateFactName);
405    }
406    let mut sorted = Vec::with_capacity(rows.len());
407    let mut names = Vec::with_capacity(rows.len());
408    let mut leaves = Vec::with_capacity(rows.len());
409    for (index, (name, fact)) in rows.into_iter().enumerate() {
410        leaves.push(leaf(&h, index, &fact));
411        names.push(name);
412        sorted.push(fact);
413    }
414    Ok(PreparedContent {
415        root: root_hash(&h, &tree_hash(&leaves, &h)),
416        header_hash: h,
417        facts: sorted,
418        names,
419        leaves,
420    })
421}
422
423impl<'a> PreparedContent<'a> {
424    pub fn root(&self) -> Hash {
425        self.root
426    }
427
428    pub fn root_digest(&self) -> String {
429        const HEX: &[u8; 16] = b"0123456789abcdef";
430        let mut result = String::from("sha256:");
431        for byte in self.root {
432            result.push(HEX[usize::from(byte >> 4)] as char);
433            result.push(HEX[usize::from(byte & 15)] as char);
434        }
435        result
436    }
437
438    pub fn fact_count(&self) -> u32 {
439        self.facts.len() as u32
440    }
441
442    pub fn disclose(&self, name: &str) -> Result<DisclosedFact<'a>, ContentError> {
443        let index = self
444            .names
445            .iter()
446            .position(|item| item == name)
447            .ok_or(ContentError::UnknownFactName)?;
448        let fact = self.facts[index];
449        let mut siblings = Vec::new();
450        inclusion_path(&self.leaves, index, &self.header_hash, &mut siblings);
451        Ok(DisclosedFact {
452            record: fact.record,
453            salt: fact.salt,
454            index: index as u32,
455            siblings,
456        })
457    }
458}
459
460/// Verify selected disclosures relative ONLY to the caller-supplied root.
461/// Empty disclosure of a nonempty block is NOT_PRESENTED, not a verified header
462/// or proven absence. For an empty committed block, the header/root can be checked.
463/// Successful proofs bind count and presented values, not the global ordering or
464/// metadata validity of withheld facts, physical truth, or complete history.
465///
466/// Total input facts <=256, bytes <=1 MiB, each fact <=16 KiB and JSON container
467/// nesting <=16 before parsing; <=8 siblings per proof. The API does not bound
468/// the caller's previous allocation of records/proofs, nor parse a wire container.
469pub fn verify_content_disclosures(
470    expected_digest: &str,
471    header: &ContentHeader<'_>,
472    count: u32,
473    disclosures: &[DisclosedFact<'_>],
474) -> Result<DisclosureReport, ContentError> {
475    let expected = digest_bytes(expected_digest)?;
476    let count = count as usize;
477    let h = header_hash(header, count)?;
478    if disclosures.len() > count {
479        return Err(ContentError::DuplicateDisclosure);
480    }
481    if disclosures.is_empty() {
482        if count == 0 {
483            if root_hash(&h, &tree_hash(&[], &h)) != expected {
484                return Err(ContentError::RootMismatch);
485            }
486            return Ok(report(0, 0, true));
487        }
488        return Ok(report(count, 0, false));
489    }
490    let mut total = 0usize;
491    let mut presented = Vec::with_capacity(disclosures.len());
492    for (position, d) in disclosures.iter().enumerate() {
493        let index = d.index as usize;
494        if index >= count {
495            return Err(ContentError::InvalidIndex);
496        }
497        if d.siblings.len() > MAX_PROOF_HASHES {
498            return Err(ContentError::InvalidProofLength);
499        }
500        if d.record.len() > MAX_TOTAL_FACT_BYTES - total {
501            return Err(ContentError::TotalByteLimit);
502        }
503        total += d.record.len();
504        if disclosures[..position]
505            .iter()
506            .any(|earlier| earlier.index == d.index)
507        {
508            return Err(ContentError::DuplicateDisclosure);
509        }
510        if disclosures[..position]
511            .iter()
512            .any(|earlier| earlier.salt == d.salt)
513        {
514            return Err(ContentError::ReusedSalt);
515        }
516        let name = fact_name(d.record)?;
517        if presented
518            .iter()
519            .any(|(_, prior): &(usize, String)| prior == &name)
520        {
521            return Err(ContentError::DuplicateFactName);
522        }
523        let fact = SaltedFact {
524            record: d.record,
525            salt: d.salt,
526        };
527        let mut used = 0;
528        let tree =
529            reconstructed_tree(count, index, leaf(&h, index, &fact), &d.siblings, &mut used)?;
530        if used != d.siblings.len() {
531            return Err(ContentError::InvalidProofLength);
532        }
533        if root_hash(&h, &tree) != expected {
534            return Err(ContentError::RootMismatch);
535        }
536        presented.push((index, name));
537    }
538    presented.sort_by_key(|item| item.0);
539    if presented.windows(2).any(|pair| pair[0].1 >= pair[1].1) {
540        return Err(ContentError::UnorderedNames);
541    }
542    Ok(report(count, disclosures.len(), true))
543}