1use serde::{Deserialize, Serialize};
15
16use crate::ledger::LedgerHeader;
17use crate::shamap::{Hash, Path, state_leaf_hash, verify};
18
19pub const FORMAT: &str = "xrpl-witness/state-proof/1";
20
21#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
23pub struct OtherLeaf {
24 pub key: String,
25 pub object: String,
26}
27
28#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
29pub struct StateProof {
30 pub format: String,
31 pub ledger_header: String,
33 pub key: String,
34 pub object: Option<String>,
36 #[serde(default, skip_serializing_if = "Option::is_none")]
38 pub other_leaf: Option<OtherLeaf>,
39 pub path: Vec<Vec<String>>,
41}
42
43#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
45pub struct ProvenState {
46 pub key: String,
47 pub present: bool,
48 pub ledger_index: u32,
49 pub ledger_hash: String,
51}
52
53fn nibble(key: &Hash, depth: usize) -> u8 {
54 let b = key[depth / 2];
55 if depth.is_multiple_of(2) {
56 b >> 4
57 } else {
58 b & 0x0F
59 }
60}
61
62fn hash32(s: &str, what: &str) -> Result<Hash, String> {
63 hex::decode(s)
64 .map_err(|_| format!("{what} is not hex"))?
65 .try_into()
66 .map_err(|_| format!("{what} is not 32 bytes"))
67}
68
69impl StateProof {
70 pub fn new(
71 header: &[u8],
72 key: &Hash,
73 object: Option<&[u8]>,
74 other: Option<(&Hash, &[u8])>,
75 path: &Path,
76 ) -> StateProof {
77 StateProof {
78 format: FORMAT.into(),
79 ledger_header: hex::encode_upper(header),
80 key: hex::encode_upper(key),
81 object: object.map(hex::encode_upper),
82 other_leaf: other.map(|(k, o)| OtherLeaf {
83 key: hex::encode_upper(k),
84 object: hex::encode_upper(o),
85 }),
86 path: path
87 .levels
88 .iter()
89 .map(|l| l.iter().map(hex::encode_upper).collect())
90 .collect(),
91 }
92 }
93
94 pub fn verify(&self) -> Result<ProvenState, String> {
95 if self.format != FORMAT {
96 return Err(format!("format {}, expected {FORMAT}", self.format));
97 }
98 let header = LedgerHeader::parse(
99 &hex::decode(&self.ledger_header).map_err(|_| "header is not hex")?,
100 )
101 .map_err(|e| e.to_string())?;
102 let key = hash32(&self.key, "key")?;
103 let mut levels = Vec::with_capacity(self.path.len());
104 for level in &self.path {
105 if level.len() != 16 {
106 return Err("path node is not 16 hashes".into());
107 }
108 let mut node = [[0u8; 32]; 16];
109 for (slot, h) in node.iter_mut().zip(level) {
110 *slot = hash32(h, "node hash")?;
111 }
112 levels.push(node);
113 }
114 if levels.is_empty() || levels.len() > 64 {
115 return Err("path is empty or longer than the key".into());
116 }
117 let path = Path { levels };
118 let root = header.account_hash;
119 let present = match (&self.object, &self.other_leaf) {
120 (Some(o), None) => {
121 let object = hex::decode(o).map_err(|_| "object is not hex")?;
122 if !verify(&path, &key, &state_leaf_hash(&object, &key), &root) {
123 return Err("path does not match the header state root".into());
124 }
125 true
126 }
127 (None, None) => {
128 if !verify(&path, &key, &[0u8; 32], &root) {
130 return Err("empty slot does not match the state root".into());
131 }
132 false
133 }
134 (None, Some(other)) => {
135 let okey = hash32(&other.key, "other leaf key")?;
136 if okey == key {
137 return Err("\"other\" leaf has the same key".into());
138 }
139 let depth = path.levels.len();
142 if (0..depth).any(|d| nibble(&okey, d) != nibble(&key, d)) {
143 return Err("other leaf is not in the key's slot".into());
144 }
145 let object =
146 hex::decode(&other.object).map_err(|_| "other leaf object is not hex")?;
147 if !verify(&path, &key, &state_leaf_hash(&object, &okey), &root) {
148 return Err("other leaf does not match the state root".into());
149 }
150 false
151 }
152 (Some(_), Some(_)) => {
153 return Err("both an object and another leaf, expected one or the other".into());
154 }
155 };
156 Ok(ProvenState {
157 key: hex::encode_upper(key),
158 present,
159 ledger_index: header.sequence,
160 ledger_hash: hex::encode_upper(header.hash()),
161 })
162 }
163}
164
165#[cfg(test)]
166mod tests {
167 use super::*;
168 use crate::shamap::{prove, root};
169
170 fn header_with(account_hash: Hash) -> Vec<u8> {
171 let mut h = vec![0u8; 118];
172 h[76..108].copy_from_slice(&account_hash);
173 h
174 }
175
176 fn key(a: u8, b: u8) -> Hash {
177 let mut k = [0u8; 32];
178 k[0] = a;
179 k[1] = b;
180 k
181 }
182
183 #[test]
184 fn presence_and_both_kinds_of_absence() {
185 let objs: Vec<(Hash, Vec<u8>)> = vec![
186 (key(0x10, 1), vec![1]),
187 (key(0x10, 2), vec![2]),
188 (key(0x20, 0), vec![3]),
189 ];
190 let leaves: Vec<(Hash, Hash)> = objs
191 .iter()
192 .map(|(k, o)| (*k, state_leaf_hash(o, k)))
193 .collect();
194 let h = header_with(root(&leaves));
195
196 let p = prove(&leaves, &objs[0].0).unwrap();
198 let ok = StateProof::new(&h, &objs[0].0, Some(&objs[0].1), None, &p)
199 .verify()
200 .unwrap();
201 assert!(ok.present);
202 assert!(
204 StateProof::new(&h, &objs[0].0, Some(&[9]), None, &p)
205 .verify()
206 .is_err()
207 );
208
209 let p_root = Path {
211 levels: vec![prove(&leaves, &objs[0].0).unwrap().levels[0]],
212 };
213 let absent = StateProof::new(&h, &key(0x30, 0), None, None, &p_root)
214 .verify()
215 .unwrap();
216 assert!(!absent.present);
217
218 let other = StateProof::new(
220 &h,
221 &key(0x20, 7),
222 None,
223 Some((&objs[2].0, &objs[2].1)),
224 &p_root,
225 );
226 assert!(!other.verify().unwrap().present);
227 assert!(
229 StateProof::new(&h, &key(0x20, 7), None, None, &p_root)
230 .verify()
231 .is_err()
232 );
233 assert!(
235 StateProof::new(
236 &h,
237 &key(0x20, 7),
238 None,
239 Some((&objs[0].0, &objs[0].1)),
240 &p_root
241 )
242 .verify()
243 .is_err()
244 );
245 }
246}