Skip to main content

ledger_engine/
proof.rs

1//! Proof API: evidence bundles that can be verified without trusting us
2//! (`witness-verify evidence`).
3//!
4//! A bundle uses the `xrpl-witness/evidence/3` format: quorum validations for the anchor
5//! ledger, the UNL lists and manifests that show who is in the quorum, the chain
6//! of headers from the target ledger to the anchor, and proofs of a transaction
7//! (path in the transaction tree) or a state object (path in the state
8//! tree, including proof that an object is absent).
9//!
10//! The anchor ledger is the nearest one after the target that has validations.
11//! The confirmation module keeps recent ones in memory; every 256 ledgers the ingester
12//! saves them to storage. The chain is at most `MAX_CHAIN` headers long.
13//!
14//! An older target is reached through a skip list (`xrpl-witness/evidence/4`):
15//! the latest state holds the hash of every 256th ledger since the start of
16//! history. The bundle proves that list in the state of the latest tree
17//! ledger, which is itself anchored as above, and adds the headers from the
18//! target up to the next multiple of 256, at most 256 of them.
19//!
20//! The response states plainly what is proven and how: whether the target ledger
21//! was itself validated by a quorum or is linked by hashes to a validated one, and what
22//! the bundle does not prove, for example that an account's history is complete.
23
24use serde_json::{Map, Value, json};
25use witness_core::evidence::{
26    Bundle, FORMAT_V3, FORMAT_V4, PolicySpec, Provenance, PublisherResponse, SkipHop, Trust,
27    ValidationEvidence, verify,
28};
29use witness_core::shamap::{prove, tx_id, tx_leaf_hash};
30use witness_core::skiplist;
31use witness_core::stateproof::StateProof;
32use witness_core::txproof::TxProof;
33
34use crate::api::{Engine, RpcError};
35use crate::state::Leaf;
36
37/// If the chain would be longer, no bundle is built; wait for the next anchor.
38pub const MAX_CHAIN: u32 = 512;
39
40/// How long `proof_entry` waits for the latest tree ledger to be validated.
41const CONFIRM_WAIT: std::time::Duration = std::time::Duration::from_secs(5);
42
43type Res<T> = Result<T, RpcError>;
44
45fn err(error: &'static str, code: i32, message: impl Into<String>) -> RpcError {
46    RpcError {
47        error,
48        code,
49        message: message.into(),
50    }
51}
52
53fn internal(e: String) -> RpcError {
54    err("internal", 73, e)
55}
56
57/// Anchor ledger, its hash, its validations, and the vote time window used
58/// to pick the UNL lists.
59struct Anchor {
60    sequence: u32,
61    hash: [u8; 32],
62    validations: Vec<ValidationEvidence>,
63    window: (u32, u32),
64}
65
66impl Engine {
67    fn hash_of(&self, seq: u32) -> Res<[u8; 32]> {
68        Ok(self.header(seq)?.1.hash())
69    }
70
71    /// Headers `from..=to` in hex, hot or cold.
72    fn headers_hex(&self, from: u32, to: u32) -> Res<Vec<String>> {
73        (from..=to)
74            .map(|seq| Ok(hex::encode_upper(self.header(seq)?.0)))
75            .collect()
76    }
77
78    /// The long skip list in the latest tree ledger that holds the hash of the
79    /// target's covering ledger, and the headers from the target to it. The
80    /// tree ledger is returned too: the bundle anchors it.
81    fn skip_hop(&self, target: u32) -> Res<(SkipHop, u32)> {
82        let last = skiplist::covering(target);
83        let key = skiplist::long_key(last);
84        let t = self.state.tree_path(&key).map_err(internal)?;
85        // The hash of `last` is written into the ledger after it.
86        if last >= t.ledger {
87            return Err(internal(format!(
88                "no skip list for ledger {target} in tree ledger {}",
89                t.ledger
90            )));
91        }
92        let crate::state::Leaf::Present(object) = &t.leaf else {
93            return Err(internal(format!("skip list for ledger {last} is missing")));
94        };
95        let list = StateProof::new(&t.header, &key, Some(object), None, &t.path);
96        Ok((
97            SkipHop {
98                list,
99                headers: self.headers_hex(target, last)?,
100            },
101            t.ledger,
102        ))
103    }
104
105    /// Nearest validated ledger with validations after `target`.
106    fn anchor(&self, target: u32) -> Res<Anchor> {
107        let confirmed = self.state.confirmed().map_err(internal)?.ok_or_else(|| {
108            err(
109                "notReady",
110                13,
111                "No ledger has been validated by a quorum yet.",
112            )
113        })?;
114        if target > confirmed {
115            return Err(err(
116                "lgrNotConfirmed",
117                22,
118                "Ledger has not been validated by a quorum yet.",
119            ));
120        }
121        let top = confirmed.min(target.saturating_add(MAX_CHAIN));
122        let c = self
123            .confirmer
124            .as_ref()
125            .ok_or_else(|| err("notImpl", 74, "Quorum confirmation is not enabled."))?;
126        // Recent ones from in-memory validations: the nearest to the target that reached quorum.
127        for seq in target..=top {
128            let hash = self.hash_of(seq)?;
129            let vals = c.validations_for(seq, &hash);
130            if vals.is_empty() {
131                continue;
132            }
133            let v = c.check(seq, &hash);
134            if let (true, Some(window)) = (v.confirmed, v.window) {
135                return Ok(Anchor {
136                    sequence: seq,
137                    hash,
138                    validations: vals
139                        .into_iter()
140                        .map(|(raw, at)| ValidationEvidence {
141                            data: hex::encode_upper(raw),
142                            received_ms: at,
143                        })
144                        .collect(),
145                    window,
146                });
147            }
148        }
149        // The rest from anchor evidence in storage, by the same rule.
150        if let Some((seq, validations)) = self.state.evidence_from(target).map_err(internal)?
151            && seq <= top
152        {
153            let hash = self.hash_of(seq)?;
154            let raws: Vec<Vec<u8>> = validations
155                .iter()
156                .filter_map(|v| hex::decode(&v.data).ok())
157                .collect();
158            let v = c.check_raw(seq, &raws, &hash);
159            if let (true, Some(window)) = (v.confirmed, v.window) {
160                return Ok(Anchor {
161                    sequence: seq,
162                    hash,
163                    validations,
164                    window,
165                });
166            }
167        }
168        Err(err(
169            "noEvidence",
170            5002,
171            format!(
172                "No validated ledger with validations within {MAX_CHAIN} after the target; the bundle cannot be built yet."
173            ),
174        ))
175    }
176
177    /// The state tree is at the latest loaded ledger, and quorum validation
178    /// arrives slightly later (the ingester checks for it once a second):
179    /// we wait for it; the path is already taken from the tree snapshot.
180    fn wait_confirmed(&self, seq: u32) -> Res<()> {
181        let until = std::time::Instant::now() + CONFIRM_WAIT;
182        while self.state.confirmed().map_err(internal)?.unwrap_or(0) < seq {
183            if std::time::Instant::now() >= until {
184                return Err(err(
185                    "lgrNotConfirmed",
186                    22,
187                    "Ledger has not been validated by a quorum yet.",
188                ));
189            }
190            std::thread::sleep(std::time::Duration::from_millis(100));
191        }
192        Ok(())
193    }
194
195    /// Bundle: anchor ledger, chain from `target` (or from the tree ledger and
196    /// a skip hop to `target`), proofs.
197    fn bundle(
198        &self,
199        target: u32,
200        transactions: Vec<TxProof>,
201        objects: Vec<StateProof>,
202    ) -> Res<(Bundle, u32)> {
203        let confirmed = self.state.confirmed().map_err(internal)?.unwrap_or(0);
204        // Within reach of a chain the target is anchored directly; deeper,
205        // through the skip list of the tree ledger.
206        let (from, skips) = if target.saturating_add(MAX_CHAIN) < confirmed {
207            let (hop, tree) = self.skip_hop(target)?;
208            self.wait_confirmed(tree)?;
209            (tree, vec![hop])
210        } else {
211            (target, Vec::new())
212        };
213        let a = self.anchor(from)?;
214        // The chain runs from its first ledger to the anchor inclusive, even if it is a single
215        // ledger: the header is always in the bundle and its hash is checked.
216        let chain = self.headers_hex(from, a.sequence)?;
217        let c = self
218            .confirmer
219            .as_ref()
220            .ok_or_else(|| err("notImpl", 74, "Quorum confirmation is not enabled."))?;
221        // Publisher responses use the same time window the decision was made with;
222        // otherwise the bundle might not reproduce it.
223        let responses = c
224            .publisher_responses(a.window.0, a.window.1)
225            .into_iter()
226            .map(|(site, body, seen)| PublisherResponse {
227                site,
228                body: base64::Engine::encode(&base64::engine::general_purpose::STANDARD, body),
229                first_seen_ms: (seen != u64::MAX).then_some(seen),
230            })
231            .collect();
232        let bundle = Bundle {
233            format: if skips.is_empty() {
234                FORMAT_V3
235            } else {
236                FORMAT_V4
237            }
238            .into(),
239            ledger_index: a.sequence,
240            ledger_hash: hex::encode_upper(a.hash),
241            policy: PolicySpec {
242                publishers: c.publishers().iter().map(hex::encode_upper).collect(),
243                threshold: 0,
244                trusted_directly: Vec::new(),
245            },
246            publisher_responses: responses,
247            manifests: c.node_manifests().iter().map(hex::encode_upper).collect(),
248            negative_unl: None,
249            validations: a.validations,
250            provenance: Provenance {
251                source: "astraea".into(),
252                exported_ms: std::time::SystemTime::now()
253                    .duration_since(std::time::UNIX_EPOCH)
254                    .map(|d| d.as_millis() as u64)
255                    .unwrap_or(0),
256                seals: Vec::new(),
257            },
258            transactions,
259            chain,
260            objects,
261            skips,
262        };
263        // The bundle is checked by the same offline verifier the recipient uses, and
264        // returned only if it reproduces our decision in full.
265        let trust = Trust {
266            publishers: c.publishers(),
267            threshold: 0,
268            trusted_directly: Default::default(),
269        };
270        let r = verify(&bundle, &trust);
271        let ok = r.confirmed_hash.as_deref() == Some(bundle.ledger_hash.as_str())
272            && r.chain_ok
273            && r.target_ledger == Some(target)
274            && r.transactions.iter().all(|t| t.in_confirmed_ledger)
275            && r.objects.iter().all(|o| o.proven);
276        if !ok {
277            return Err(err(
278                "evidenceInvalid",
279                5003,
280                format!(
281                    "The built bundle failed its own verification: {}",
282                    r.problems.join("; ")
283                ),
284            ));
285        }
286        Ok((bundle, a.sequence))
287    }
288
289    fn answer(
290        &self,
291        bundle: Bundle,
292        anchor: u32,
293        target: u32,
294        proves: &[&str],
295        not: &[&str],
296    ) -> Res<Map<String, Value>> {
297        let mut m = Map::new();
298        m.insert(
299            "guarantee".into(),
300            json!({
301                "target_ledger": target,
302                "anchor_ledger": anchor,
303                "target_confirmed_by": match (bundle.skips.is_empty(), anchor == target) {
304                    (false, _) => "skip-list",
305                    (true, true) => "quorum",
306                    (true, false) => "hash-chain",
307                },
308                "anchor_confirmed_by": "quorum",
309                "quorum_rule": "full-unl; UNL lists valid at ledger time; every possible policy must agree",
310                "proves": proves,
311                "does_not_prove": not,
312                "verify_with": "witness-verify evidence <bundle.json>",
313            }),
314        );
315        m.insert(
316            "proof".into(),
317            serde_json::to_value(bundle).map_err(|e| internal(e.to_string()))?,
318        );
319        Ok(m)
320    }
321
322    /// Ledger bundle: proves that the header with this hash was validated by the network.
323    pub fn proof_ledger(&self, p: &Map<String, Value>) -> Res<Map<String, Value>> {
324        let target = self.resolve_ledger(p)?;
325        let (b, anchor) = self.bundle(target, Vec::new(), Vec::new())?;
326        self.answer(
327            b,
328            anchor,
329            target,
330            &["ledger header and hash"],
331            &["contents beyond the header"],
332        )
333    }
334
335    /// Transaction bundle: proves that it was recorded with this metadata in a
336    /// validated ledger.
337    pub fn proof_tx(&self, p: &Map<String, Value>) -> Res<Map<String, Value>> {
338        let id = p
339            .get("transaction")
340            .and_then(Value::as_str)
341            .and_then(|s| hex::decode(s).ok())
342            .and_then(|b| <[u8; 32]>::try_from(b).ok())
343            .ok_or_else(|| {
344                err(
345                    "invalidParams",
346                    31,
347                    "transaction must be a transaction hash",
348                )
349            })?;
350        let not_found = || err("txnNotFound", 29, "Transaction not found.");
351        let (seq, pos) = match self.state.tx_location(&id).map_err(internal)? {
352            Some(at) => at,
353            None => self.cold_tx(&id)?.ok_or_else(not_found)?,
354        };
355        let (min, max) = self.range()?;
356        if seq < min || seq > max {
357            return Err(not_found());
358        }
359        let l = self.ledger_txs(seq)?;
360        let leaves: Vec<([u8; 32], [u8; 32])> = l
361            .transactions
362            .iter()
363            .map(|(t, m)| {
364                let k = tx_id(t);
365                (k, tx_leaf_hash(t, m, &k))
366            })
367            .collect();
368        let path = prove(&leaves, &id)
369            .ok_or_else(|| internal("could not build the transaction path".into()))?;
370        let (tx, meta) = &l.transactions[pos as usize];
371        let proof = TxProof::new(&l.header, tx, meta, &path);
372        let (b, anchor) = self.bundle(seq, vec![proof], Vec::new())?;
373        self.answer(
374            b,
375            anchor,
376            seq,
377            &["transaction with metadata included in the ledger"],
378            &["delivered_amount and other fields derived by servers"],
379        )
380    }
381
382    /// Bundle for a state object (present or absent) at the latest ledger of
383    /// the state tree, or at an earlier one from the tree history.
384    pub fn proof_entry(&self, p: &Map<String, Value>) -> Res<Map<String, Value>> {
385        let key = self.entry_key_of(p)?;
386        let earlier = p
387            .get("ledger_index")
388            .is_some_and(|v| !v.is_null() && v.as_str() != Some("validated"))
389            || p.get("ledger_hash").is_some_and(|v| !v.is_null());
390        let t = if earlier {
391            let seq = self.resolve_state(p)?;
392            self.state
393                .state_path_at(&key, seq)
394                .map_err(|e| err("noEvidence", 5002, e))?
395        } else {
396            let t = self.state.tree_path(&key).map_err(internal)?;
397            self.wait_confirmed(t.ledger)?;
398            t
399        };
400        let (object, other) = match &t.leaf {
401            Leaf::Present(o) => (Some(&o[..]), None),
402            Leaf::Empty => (None, None),
403            Leaf::Other(k, o) => (None, Some((k, &o[..]))),
404        };
405        let proof = StateProof::new(&t.header, &key, object, other, &t.path);
406        let present = object.is_some();
407        let (b, anchor) = self.bundle(t.ledger, Vec::new(), vec![proof])?;
408        self.answer(
409            b,
410            anchor,
411            t.ledger,
412            &[if present {
413                "object present in ledger state, byte for byte"
414            } else {
415                "object absent from ledger state"
416            }],
417            &["object state at other ledgers"],
418        )
419    }
420}