qualia_core_db/bundle/stream/proof/
span.rs1use super::{decode_proof, verify_leaf, ProofError as E, Representation, TreeSpec, LEAF_BYTES};
5use crate::net::qdnf::types::StrongDigest;
6
7pub const MAX_SPAN_LEAVES: usize = 2048;
8pub const MAX_SPAN_BYTES: usize = MAX_SPAN_LEAVES * (LEAF_BYTES as usize + 16);
9
10pub struct SpanLimits {
13 pub max_leaves: usize,
14 pub max_encoded_bytes: usize,
15}
16pub struct VerifiedLeafSpan<'a> {
17 spec: TreeSpec,
18 root: StrongDigest,
19 first: u64,
20 count: usize,
21 bytes: &'a [u8],
22}
23impl VerifiedLeafSpan<'_> {
24 pub const fn tree_spec(&self) -> &TreeSpec {
25 &self.spec
26 }
27 pub const fn root(&self) -> StrongDigest {
28 self.root
29 }
30 pub const fn first_leaf(&self) -> u64 {
31 self.first
32 }
33 pub const fn leaf_count(&self) -> usize {
34 self.count
35 }
36 pub fn encoded_bytes(&self) -> &[u8] {
37 self.bytes
38 }
39 pub fn plaintext_range(&self, offset: u64, length: usize) -> Result<&[u8], E> {
42 if self.spec.representation() != Representation::Plaintext {
43 return Err(E::InvalidSpec);
44 }
45 let base = self.first.checked_mul(LEAF_BYTES).ok_or(E::Index)?;
46 let start = offset.checked_sub(base).ok_or(E::Index)?;
47 let start = usize::try_from(start).map_err(|_| E::Length)?;
48 let end = start.checked_add(length).ok_or(E::Length)?;
49 self.bytes.get(start..end).ok_or(E::Length)
50 }
51}
52
53pub fn verify_leaf_span<'a>(
58 spec: &TreeSpec,
59 root: StrongDigest,
60 first: u64,
61 bytes: &'a [u8],
62 proofs: &[&[u8]],
63 sibling_scratch: &mut [StrongDigest],
64 limits: SpanLimits,
65) -> Result<VerifiedLeafSpan<'a>, E> {
66 if limits.max_leaves == 0
67 || limits.max_leaves > MAX_SPAN_LEAVES
68 || limits.max_encoded_bytes == 0
69 || limits.max_encoded_bytes > MAX_SPAN_BYTES
70 || proofs.len() > limits.max_leaves
71 || bytes.len() > limits.max_encoded_bytes
72 {
73 return Err(E::Limit);
74 }
75 if proofs.is_empty() {
76 return Err(E::Incomplete);
77 }
78 let count = u64::try_from(proofs.len()).map_err(|_| E::Limit)?;
79 let end = first.checked_add(count).ok_or(E::Index)?;
80 if first >= spec.leaf_count() || end > spec.leaf_count() {
81 return Err(E::Index);
82 }
83 let mut expected = 0usize;
84 for index in first..end {
85 expected = expected
86 .checked_add(spec.encoded_leaf_length(index)?)
87 .ok_or(E::Length)?;
88 }
89 if bytes.len() != expected {
90 return Err(E::Length);
91 }
92 let mut position = 0usize;
93 for (i, proof) in proofs.iter().enumerate() {
94 let index = first + i as u64;
95 let next = position + spec.encoded_leaf_length(index)?;
96 let siblings = decode_proof(proof, sibling_scratch)?;
97 verify_leaf(spec, root, index, &bytes[position..next], siblings)?;
98 position = next;
99 }
100 Ok(VerifiedLeafSpan {
101 spec: *spec,
102 root,
103 first,
104 count: proofs.len(),
105 bytes,
106 })
107}