Skip to main content

ledger_engine/
unknown.rs

1//! What the network uses that this build does not know yet.
2//!
3//! Astraea decodes XRPL binary with the field and type tables of one xrpld
4//! release (`definitions.json`) and lists the amendments of that release
5//! (crate::amendments). A newer xrpld can bring a field, a transaction or
6//! object type, a result code or an amendment that is not in them. The
7//! loader still stores such a ledger as it came, byte for byte, and hashes
8//! and proofs stay valid; what it cannot do is turn the new parts into JSON.
9//! This module finds them, so the loader can report them (log and metrics)
10//! and a release with new tables can follow.
11//!
12//! Two checks:
13//! - `scan`: every transaction, its metadata and every changed object of a
14//!   ledger, walked field by field, nested objects and arrays included;
15//! - `amendments`: the Amendments object, for amendments enabled or with a
16//!   validator majority that the table does not have. A majority holds for
17//!   two weeks before the amendment is enabled, so this is the early warning.
18
19use std::collections::BTreeSet;
20
21use witness_core::stobject::{self, Field, FieldId, types};
22use witness_core::{sha512_half, shamap::tx_id};
23
24use crate::ledger::Ledger;
25use crate::xrpl_json::{Definitions, definitions};
26
27const LEDGER_ENTRY_TYPE: FieldId = FieldId::new(types::UINT16, 1);
28const TRANSACTION_TYPE: FieldId = FieldId::new(types::UINT16, 2);
29const TRANSACTION_RESULT: FieldId = FieldId::new(types::UINT8, 3);
30const AMENDMENTS: FieldId = FieldId::new(types::VECTOR256, 3);
31const MAJORITIES: FieldId = FieldId::new(types::ARRAY, 16);
32const AMENDMENT: FieldId = FieldId::new(types::HASH256, 19);
33
34/// Key of the Amendments object (a singleton).
35pub fn amendments_key() -> [u8; 32] {
36    sha512_half(&[0x00, b'f'])
37}
38
39/// At most this many findings per ledger: one new field can appear in every
40/// transaction of a ledger, and one line about it is enough.
41const MAX_FINDINGS: usize = 20;
42
43fn check(d: &Definitions, f: &Field<'_>, at: &str, out: &mut BTreeSet<String>) {
44    let id = f.id;
45    if !d.knows_field(id.type_code, id.field_code) {
46        out.insert(format!("field {}:{} in {at}", id.type_code, id.field_code));
47    }
48    let code16 = || <[u8; 2]>::try_from(f.value).ok().map(u16::from_be_bytes);
49    if id == TRANSACTION_TYPE
50        && let Some(c) = code16()
51        && d.transaction_type(c).is_none()
52    {
53        out.insert(format!("transaction type {c} in {at}"));
54    }
55    if id == LEDGER_ENTRY_TYPE
56        && let Some(c) = code16()
57        && d.ledger_entry_type(c).is_none()
58    {
59        out.insert(format!("ledger entry type {c} in {at}"));
60    }
61    if id == TRANSACTION_RESULT
62        && let [c] = f.value
63        && d.result(i32::from(*c)).is_none()
64    {
65        out.insert(format!("transaction result {c} in {at}"));
66    }
67}
68
69fn walk(d: &Definitions, buf: &[u8], array: bool, at: &str, out: &mut BTreeSet<String>) {
70    let parsed = if array {
71        stobject::items(buf)
72    } else {
73        stobject::fields(buf)
74    };
75    let fs = match parsed {
76        Ok(fs) => fs,
77        // An unknown type code: its length is unknown, nothing after it can be read.
78        Err(e) => {
79            out.insert(format!("cannot read {at}: {e}"));
80            return;
81        }
82    };
83    for f in &fs {
84        check(d, f, at, out);
85        match f.id.type_code {
86            types::OBJECT => walk(d, f.value, false, at, out),
87            types::ARRAY => walk(d, f.value, true, at, out),
88            _ => {}
89        }
90    }
91}
92
93/// What a ledger holds that the definitions do not know, one line per kind
94/// and place, at most `MAX_FINDINGS`. Empty for a ledger fully understood.
95pub fn scan(ledger: &Ledger) -> Vec<String> {
96    let d = definitions();
97    let mut out = BTreeSet::new();
98    for (tx, meta) in &ledger.transactions {
99        let h = hex::encode_upper(tx_id(tx));
100        walk(d, tx, false, &format!("transaction {h}"), &mut out);
101        walk(d, meta, false, &format!("metadata of {h}"), &mut out);
102        if out.len() >= MAX_FINDINGS {
103            break;
104        }
105    }
106    for c in &ledger.changes {
107        if out.len() >= MAX_FINDINGS {
108            break;
109        }
110        if !c.data.is_empty() {
111            let at = format!("object {}", hex::encode_upper(c.key));
112            walk(d, &c.data, false, &at, &mut out);
113        }
114    }
115    out.into_iter().take(MAX_FINDINGS).collect()
116}
117
118/// Amendments in the Amendments object (its binary) that the table does not
119/// have: enabled ones, and ones with a validator majority, as hex IDs.
120pub fn amendments(object: &[u8]) -> Result<(Vec<String>, Vec<String>), String> {
121    let known: BTreeSet<[u8; 32]> = crate::amendments::AMENDMENTS
122        .iter()
123        .map(|(name, _)| sha512_half(name.as_bytes()))
124        .collect();
125    let unknown = |id: &[u8]| -> Option<String> {
126        let id: [u8; 32] = id.try_into().ok()?;
127        (!known.contains(&id)).then(|| hex::encode_upper(id))
128    };
129    let fs = stobject::fields(object).map_err(|e| format!("Amendments object: {e}"))?;
130    let enabled = stobject::find(&fs, AMENDMENTS)
131        .map(|v| v.chunks(32).filter_map(unknown).collect())
132        .unwrap_or_default();
133    let mut majority = Vec::new();
134    if let Some(m) = fs.iter().find(|f| f.id == MAJORITIES) {
135        for item in stobject::children(m).map_err(|e| e.to_string())? {
136            let inner = stobject::fields(item.value).map_err(|e| e.to_string())?;
137            if let Some(id) = stobject::find(&inner, AMENDMENT).and_then(unknown) {
138                majority.push(id);
139            }
140        }
141    }
142    Ok((enabled, majority))
143}