1use serde::{Deserialize, Serialize};
11
12use crate::ledger::LedgerHeader;
13use crate::shamap::{Hash, Path, tx_id, tx_leaf_hash, verify};
14
15pub const FORMAT: &str = "xrpl-witness/tx-proof/1";
16
17#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
18pub struct TxProof {
19 pub format: String,
20 pub ledger_header: String,
22 pub tx: String,
24 pub meta: String,
25 pub path: Vec<Vec<String>>,
27}
28
29#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
31pub struct Proven {
32 pub tx_hash: String,
33 pub ledger_index: u32,
34 pub ledger_hash: String,
37}
38
39impl TxProof {
40 pub fn new(header: &[u8], tx: &[u8], meta: &[u8], path: &Path) -> TxProof {
41 TxProof {
42 format: FORMAT.into(),
43 ledger_header: hex::encode_upper(header),
44 tx: hex::encode_upper(tx),
45 meta: hex::encode_upper(meta),
46 path: path
47 .levels
48 .iter()
49 .map(|l| l.iter().map(hex::encode_upper).collect())
50 .collect(),
51 }
52 }
53
54 pub fn verify(&self) -> Result<Proven, String> {
55 if self.format != FORMAT {
56 return Err(format!("format {}, expected {FORMAT}", self.format));
57 }
58 let dec = |s: &str, what: &str| hex::decode(s).map_err(|_| format!("{what} is not hex"));
59 let header =
60 LedgerHeader::parse(&dec(&self.ledger_header, "header")?).map_err(|e| e.to_string())?;
61 let tx = dec(&self.tx, "transaction")?;
62 let meta = dec(&self.meta, "metadata")?;
63 let mut levels = Vec::with_capacity(self.path.len());
64 for level in &self.path {
65 if level.len() != 16 {
66 return Err("path node is not 16 hashes".into());
67 }
68 let mut node = [[0u8; 32]; 16];
69 for (slot, h) in node.iter_mut().zip(level) {
70 *slot = dec(h, "node hash")?
71 .try_into()
72 .map_err(|_| "node hash is not 32 bytes".to_string())?;
73 }
74 levels.push(node);
75 }
76 let key: Hash = tx_id(&tx);
77 let leaf = tx_leaf_hash(&tx, &meta, &key);
78 if !verify(&Path { levels }, &key, &leaf, &header.transaction_hash) {
79 return Err("path does not match the header transaction root".into());
80 }
81 Ok(Proven {
82 tx_hash: hex::encode_upper(key),
83 ledger_index: header.sequence,
84 ledger_hash: hex::encode_upper(header.hash()),
85 })
86 }
87}