Skip to main content

witness_core/
stobject.rs

1//! Splitting a serialized XRPL object (STObject) into fields.
2//!
3//! Each field is a header (type code and field code) and a value. The parser
4//! does not rebuild the object; it returns slices of the original bytes:
5//! checking a signature needs exactly the bytes the validator signed, not our
6//! copy of them.
7//!
8//! All types found in validations, manifests, transactions, metadata and
9//! state objects are supported: fixed and variable length, amounts, nested
10//! objects and arrays, paths, Issue, the XChain bridge. An unknown type is an
11//! error: silently skipping what we don't understand is not allowed.
12
13use std::fmt;
14
15/// XRPL field type codes.
16pub mod types {
17    pub const UINT16: u16 = 1;
18    pub const UINT32: u16 = 2;
19    pub const UINT64: u16 = 3;
20    pub const HASH128: u16 = 4;
21    pub const HASH256: u16 = 5;
22    pub const AMOUNT: u16 = 6;
23    pub const BLOB: u16 = 7;
24    pub const ACCOUNT: u16 = 8;
25    /// Floating-point number: i64 mantissa and i32 exponent.
26    pub const NUMBER: u16 = 9;
27    pub const INT32: u16 = 10;
28    pub const INT64: u16 = 11;
29    pub const OBJECT: u16 = 14;
30    pub const ARRAY: u16 = 15;
31    pub const UINT8: u16 = 16;
32    pub const HASH160: u16 = 17;
33    pub const PATHSET: u16 = 18;
34    pub const VECTOR256: u16 = 19;
35    pub const UINT96: u16 = 20;
36    pub const HASH192: u16 = 21;
37    pub const UINT384: u16 = 22;
38    pub const UINT512: u16 = 23;
39    pub const ISSUE: u16 = 24;
40    pub const XCHAIN_BRIDGE: u16 = 25;
41    pub const CURRENCY: u16 = 26;
42}
43
44/// A field by its (type, code) pair, as in the xrpld field definitions.
45#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
46pub struct FieldId {
47    pub type_code: u16,
48    pub field_code: u16,
49}
50
51impl FieldId {
52    pub const fn new(type_code: u16, field_code: u16) -> FieldId {
53        FieldId {
54            type_code,
55            field_code,
56        }
57    }
58}
59
60/// Fields found in validations and manifests.
61pub mod fields {
62    use super::{FieldId, types::*};
63
64    pub const VERSION: FieldId = FieldId::new(UINT16, 16);
65    pub const FLAGS: FieldId = FieldId::new(UINT32, 2);
66    pub const SEQUENCE: FieldId = FieldId::new(UINT32, 4);
67    pub const LEDGER_SEQUENCE: FieldId = FieldId::new(UINT32, 6);
68    pub const CLOSE_TIME: FieldId = FieldId::new(UINT32, 7);
69    pub const SIGNING_TIME: FieldId = FieldId::new(UINT32, 9);
70    pub const LOAD_FEE: FieldId = FieldId::new(UINT32, 24);
71    pub const RESERVE_BASE: FieldId = FieldId::new(UINT32, 31);
72    pub const RESERVE_INCREMENT: FieldId = FieldId::new(UINT32, 32);
73    pub const BASE_FEE: FieldId = FieldId::new(UINT64, 5);
74    pub const COOKIE: FieldId = FieldId::new(UINT64, 10);
75    pub const SERVER_VERSION: FieldId = FieldId::new(UINT64, 11);
76    pub const LEDGER_HASH: FieldId = FieldId::new(HASH256, 1);
77    pub const CONSENSUS_HASH: FieldId = FieldId::new(HASH256, 23);
78    pub const VALIDATED_HASH: FieldId = FieldId::new(HASH256, 25);
79    pub const PUBLIC_KEY: FieldId = FieldId::new(BLOB, 1);
80    pub const SIGNING_PUB_KEY: FieldId = FieldId::new(BLOB, 3);
81    pub const SIGNATURE: FieldId = FieldId::new(BLOB, 6);
82    pub const DOMAIN: FieldId = FieldId::new(BLOB, 7);
83    pub const MASTER_SIGNATURE: FieldId = FieldId::new(BLOB, 18);
84    pub const AMENDMENTS: FieldId = FieldId::new(VECTOR256, 3);
85    pub const LEDGER_ENTRY_TYPE: FieldId = FieldId::new(UINT16, 1);
86    pub const FIRST_LEDGER_SEQUENCE: FieldId = FieldId::new(UINT32, 26);
87    pub const VALIDATOR_TO_DISABLE: FieldId = FieldId::new(BLOB, 20);
88    pub const VALIDATOR_TO_RE_ENABLE: FieldId = FieldId::new(BLOB, 21);
89    pub const DISABLED_VALIDATORS: FieldId = FieldId::new(ARRAY, 17);
90    pub const DISABLED_VALIDATOR: FieldId = FieldId::new(OBJECT, 19);
91}
92
93/// End of a nested object (type 14, field 1) and of an array (type 15, field 1).
94pub const OBJECT_END: u8 = 0xE1;
95pub const ARRAY_END: u8 = 0xF1;
96
97#[derive(Debug, Clone, PartialEq, Eq)]
98pub enum Error {
99    /// The data ended in the middle of a field.
100    Truncated { at: usize },
101    /// A type we do not parse.
102    UnsupportedType { at: usize, type_code: u16 },
103    /// Invalid length or value.
104    Malformed(String),
105}
106
107impl fmt::Display for Error {
108    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
109        match self {
110            Error::Truncated { at } => write!(f, "data truncated at offset {at}"),
111            Error::UnsupportedType { at, type_code } => {
112                write!(f, "field type {type_code} at offset {at} is not supported")
113            }
114            Error::Malformed(m) => write!(f, "{m}"),
115        }
116    }
117}
118
119impl std::error::Error for Error {}
120
121/// An object field: header and value as slices of the original bytes.
122#[derive(Debug, Clone, Copy, PartialEq, Eq)]
123pub struct Field<'a> {
124    pub id: FieldId,
125    /// The value without its length prefix.
126    pub value: &'a [u8],
127    /// The whole field: header, length prefix, value.
128    pub raw: &'a [u8],
129}
130
131fn take(buf: &[u8], at: usize, n: usize) -> Result<&[u8], Error> {
132    buf.get(at..at + n).ok_or(Error::Truncated { at })
133}
134
135/// Length of a variable-length (VL) value: a 1 to 3 byte prefix.
136fn read_vl(buf: &[u8], at: usize) -> Result<(usize, usize), Error> {
137    let b1 = usize::from(*buf.get(at).ok_or(Error::Truncated { at })?);
138    match b1 {
139        0..=192 => Ok((b1, 1)),
140        193..=240 => {
141            let b2 = usize::from(*buf.get(at + 1).ok_or(Error::Truncated { at })?);
142            Ok((193 + (b1 - 193) * 256 + b2, 2))
143        }
144        241..=254 => {
145            let b = take(buf, at + 1, 2)?;
146            Ok((
147                12_481 + (b1 - 241) * 65_536 + usize::from(b[0]) * 256 + usize::from(b[1]),
148                3,
149            ))
150        }
151        _ => Err(Error::Malformed(format!(
152            "invalid length prefix {b1} at offset {at}"
153        ))),
154    }
155}
156
157fn fixed_len(type_code: u16) -> Option<usize> {
158    use types::*;
159    Some(match type_code {
160        UINT8 => 1,
161        UINT16 => 2,
162        UINT32 | INT32 => 4,
163        UINT64 | INT64 => 8,
164        NUMBER => 12,
165        CURRENCY => 20,
166        UINT96 => 12,
167        HASH128 => 16,
168        HASH160 => 20,
169        HASH192 => 24,
170        HASH256 => 32,
171        UINT384 => 48,
172        UINT512 => 64,
173        _ => return None,
174    })
175}
176
177/// Length of an Issue: 20 zero bytes is XRP; otherwise currency and issuer,
178/// and for MPT the issuer in place of the currency, then the special
179/// "no account" value and the issuance sequence.
180fn issue_len(buf: &[u8], at: usize) -> Result<usize, Error> {
181    let first = take(buf, at, 20)?;
182    if first.iter().all(|b| *b == 0) {
183        return Ok(20);
184    }
185    let second = take(buf, at + 20, 20)?;
186    let no_account = second[..19].iter().all(|b| *b == 0) && second[19] == 1;
187    Ok(if no_account { 44 } else { 40 })
188}
189
190/// Length of a path set: steps with flags (account, currency, issuer, 20 bytes
191/// each), 0xFF is a path boundary, 0x00 is the end.
192fn pathset_len(buf: &[u8], start: usize) -> Result<usize, Error> {
193    let mut at = start;
194    loop {
195        let t = *buf.get(at).ok_or(Error::Truncated { at })?;
196        at += 1;
197        match t {
198            0x00 => return Ok(at - start),
199            0xFF => {}
200            _ if t & !0x31 != 0 => {
201                return Err(Error::Malformed(format!(
202                    "unknown path step {t:#04x} at offset {}",
203                    at - 1
204                )));
205            }
206            _ => at += 20 * (t & 0x31).count_ones() as usize,
207        }
208    }
209}
210
211/// Splits an object into fields in their original order.
212pub fn fields(buf: &[u8]) -> Result<Vec<Field<'_>>, Error> {
213    let (out, _) = sequence(buf, 0, None, 0, false)?;
214    Ok(out)
215}
216
217/// Array elements from the array's value: every element is an object, whatever
218/// field names it (as in XRPLA's `wire.cpp` and STArray in xrpld). An
219/// element's value is its fields without the end marker.
220pub fn items(buf: &[u8]) -> Result<Vec<Field<'_>>, Error> {
221    let (out, _) = sequence(buf, 0, None, 0, true)?;
222    Ok(out)
223}
224
225/// Nesting depth limit for objects and arrays. xrpld uses 10 (`STVar`); this
226/// one leaves headroom but is still finite: the parser is recursive, and
227/// network input with thousands of nesting levels would otherwise overflow the stack.
228pub const MAX_DEPTH: usize = 32;
229
230/// Fields of a nested object or elements of an array, from the field's value.
231pub fn children<'a>(f: &Field<'a>) -> Result<Vec<Field<'a>>, Error> {
232    if f.id.type_code == types::ARRAY {
233        items(f.value)
234    } else {
235        fields(f.value)
236    }
237}
238
239/// The field header at `at`: type, field code and the offset right after the header.
240pub fn head(buf: &[u8], mut at: usize) -> Result<(u16, u16, usize), Error> {
241    let b = *buf.get(at).ok_or(Error::Truncated { at })?;
242    let (mut type_code, mut field_code) = (u16::from(b >> 4), u16::from(b & 0x0F));
243    at += 1;
244    if type_code == 0 {
245        type_code = u16::from(*buf.get(at).ok_or(Error::Truncated { at })?);
246        at += 1;
247    }
248    if field_code == 0 {
249        field_code = u16::from(*buf.get(at).ok_or(Error::Truncated { at })?);
250        at += 1;
251    }
252    Ok((type_code, field_code, at))
253}
254
255/// Where the value of a field of type `type_code` is, if the header ended at `at`:
256/// (value start, length). `None` for an object or array: their value runs
257/// up to the end marker.
258pub fn extent(buf: &[u8], at: usize, type_code: u16) -> Result<Option<(usize, usize)>, Error> {
259    if let Some(n) = fixed_len(type_code) {
260        return Ok(Some((at, n)));
261    }
262    Ok(Some(match type_code {
263        types::BLOB | types::ACCOUNT | types::VECTOR256 => {
264            let (n, used) = read_vl(buf, at)?;
265            (at + used, n)
266        }
267        types::ISSUE => (at, issue_len(buf, at)?),
268        types::PATHSET => (at, pathset_len(buf, at)?),
269        types::XCHAIN_BRIDGE => {
270            // Door (length-prefixed account), Issue, door, Issue.
271            let mut n = 0;
272            for _ in 0..2 {
273                let (len, used) = read_vl(buf, at + n)?;
274                n += used + len;
275                n += issue_len(buf, at + n)?;
276            }
277            (at, n)
278        }
279        types::AMOUNT => {
280            let first = *buf.get(at).ok_or(Error::Truncated { at })?;
281            // The top bit means an issued currency (48 bytes). MPT (33 bytes)
282            // only when the first byte is flags alone, 0x60 or 0x20: in XRP
283            // amounts from 2013 the 0x20 bit can be part of the value (as in
284            // XRPLA's wire.cpp). Otherwise XRP in drops.
285            let n = if first & 0x80 != 0 {
286                48
287            } else if first == 0x60 || first == 0x20 {
288                33
289            } else {
290                8
291            };
292            (at, n)
293        }
294        _ => return Ok(None),
295    }))
296}
297
298/// Fields from `at` up to the end marker `stop` (not including it) or to the end of the buffer.
299/// Returns the fields and the offset right after the marker.
300fn sequence(
301    buf: &[u8],
302    mut at: usize,
303    stop: Option<u8>,
304    depth: usize,
305    in_array: bool,
306) -> Result<(Vec<Field<'_>>, usize), Error> {
307    if depth > MAX_DEPTH {
308        return Err(Error::Malformed(format!(
309            "nesting deeper than {MAX_DEPTH} at offset {at}"
310        )));
311    }
312    let mut out = Vec::new();
313    loop {
314        if at >= buf.len() {
315            return match stop {
316                None => Ok((out, at)),
317                Some(_) => Err(Error::Truncated { at }),
318            };
319        }
320        if let Some(m) = stop
321            && buf[at] == m
322        {
323            return Ok((out, at + 1));
324        }
325        if buf[at] == OBJECT_END || buf[at] == ARRAY_END {
326            return Err(Error::Malformed(format!("stray end marker at offset {at}")));
327        }
328        let start = at;
329        let (type_code, field_code, after_head) = head(buf, at)?;
330        at = after_head;
331        if in_array {
332            let (_, after) = sequence(buf, at, Some(OBJECT_END), depth + 1, false)?;
333            out.push(Field {
334                id: FieldId::new(type_code, field_code),
335                value: &buf[at..after - 1],
336                raw: &buf[start..after],
337            });
338            at = after;
339            continue;
340        }
341        let (value_at, len) = match extent(buf, at, type_code)? {
342            Some(x) => x,
343            None => match type_code {
344                types::OBJECT | types::ARRAY => {
345                    let marker = if type_code == types::OBJECT {
346                        OBJECT_END
347                    } else {
348                        ARRAY_END
349                    };
350                    let (_, after) =
351                        sequence(buf, at, Some(marker), depth + 1, type_code == types::ARRAY)?;
352                    // The value excludes the end marker; the whole field includes it.
353                    out.push(Field {
354                        id: FieldId::new(type_code, field_code),
355                        value: &buf[at..after - 1],
356                        raw: &buf[start..after],
357                    });
358                    at = after;
359                    continue;
360                }
361                _ => {
362                    return Err(Error::UnsupportedType {
363                        at: start,
364                        type_code,
365                    });
366                }
367            },
368        };
369        let value = take(buf, value_at, len)?;
370        at = value_at + len;
371        out.push(Field {
372            id: FieldId::new(type_code, field_code),
373            value,
374            raw: &buf[start..at],
375        });
376    }
377}
378
379/// Object bytes for signing: all fields except signatures, in their original order.
380pub fn signing_bytes(fields: &[Field<'_>]) -> Vec<u8> {
381    let mut out = Vec::new();
382    for f in fields {
383        if f.id != self::fields::SIGNATURE && f.id != self::fields::MASTER_SIGNATURE {
384            out.extend_from_slice(f.raw);
385        }
386    }
387    out
388}
389
390pub fn find<'a>(fields: &[Field<'a>], id: FieldId) -> Option<&'a [u8]> {
391    fields.iter().find(|f| f.id == id).map(|f| f.value)
392}
393
394pub fn u32_of(v: &[u8]) -> Option<u32> {
395    Some(u32::from_be_bytes(v.try_into().ok()?))
396}
397
398pub fn u64_of(v: &[u8]) -> Option<u64> {
399    Some(u64::from_be_bytes(v.try_into().ok()?))
400}
401
402#[cfg(test)]
403mod tests {
404    use super::*;
405
406    #[test]
407    fn issues_paths_and_numbers() {
408        // Issue (type 24, field 3): XRP, then a currency with an issuer.
409        let mut buf = vec![0x03, 0x18];
410        buf.extend([0u8; 20]);
411        buf.extend([0x03, 0x18]);
412        buf.extend([7u8; 40]);
413        // MPT: issuer, "no account", issuance sequence.
414        buf.extend([0x03, 0x18]);
415        buf.extend([7u8; 20]);
416        buf.extend([0u8; 19]);
417        buf.extend([1u8, 0, 0, 0, 5]);
418        // Number (type 9, field 1): 12 bytes.
419        buf.extend([0x91]);
420        buf.extend([1u8; 12]);
421        // Paths (type 18, field 1): a step with an account, a boundary, a step
422        // with a currency and issuer, the end.
423        buf.extend([0x01, 0x12, 0x01]);
424        buf.extend([2u8; 20]);
425        buf.push(0xFF);
426        buf.push(0x30);
427        buf.extend([3u8; 40]);
428        buf.push(0x00);
429        let f = fields(&buf).unwrap();
430        let lens: Vec<_> = f.iter().map(|f| f.value.len()).collect();
431        assert_eq!(lens, vec![20, 40, 44, 12, 64]);
432        assert!(fields(&[0x01, 0x12, 0x02]).is_err(), "unknown path step");
433    }
434
435    #[test]
436    fn length_prefixes() {
437        assert_eq!(read_vl(&[0], 0).unwrap(), (0, 1));
438        assert_eq!(read_vl(&[192], 0).unwrap(), (192, 1));
439        assert_eq!(read_vl(&[193, 0], 0).unwrap(), (193, 2));
440        assert_eq!(read_vl(&[240, 255], 0).unwrap(), (12_480, 2));
441        assert_eq!(read_vl(&[241, 0, 0], 0).unwrap(), (12_481, 3));
442        assert!(read_vl(&[255], 0).is_err());
443        assert!(read_vl(&[200], 0).is_err());
444    }
445
446    #[test]
447    fn headers_with_large_codes() {
448        // MasterSignature: type 7, field 18, the field code is in the second byte.
449        let buf = [0x70, 0x12, 0x02, 0xAA, 0xBB];
450        let f = fields(&buf).unwrap();
451        assert_eq!(f[0].id, self::fields::MASTER_SIGNATURE);
452        assert_eq!(f[0].value, &[0xAA, 0xBB]);
453        // Vector256 Amendments: type 19, the type code is in the second byte.
454        let buf = [0x03, 0x13, 0x00];
455        assert_eq!(fields(&buf).unwrap()[0].id, self::fields::AMENDMENTS);
456    }
457
458    #[test]
459    fn deep_nesting_is_an_error_not_a_crash() {
460        // 20 000 nested objects, 40 000 bytes.
461        let mut buf = vec![0xE2; 20_000];
462        buf.extend(vec![0xE1; 20_000]);
463        assert!(matches!(fields(&buf), Err(Error::Malformed(_))));
464        // Normal nesting parses.
465        let mut ok = vec![0xE2; 8];
466        ok.extend(vec![0xE1; 8]);
467        assert!(fields(&ok).is_ok());
468    }
469
470    #[test]
471    fn truncation_and_stray_markers_are_errors() {
472        assert!(matches!(
473            fields(&[0x22, 0x80]),
474            Err(Error::Truncated { .. })
475        ));
476        assert!(matches!(fields(&[0xE1]), Err(Error::Malformed(_))));
477        // An array without an end marker.
478        assert!(matches!(
479            fields(&[0xF0, 0x11, 0xE0, 0x13, 0xE1]),
480            Err(Error::Truncated { .. })
481        ));
482        // XRPL has no type 12.
483        assert!(matches!(
484            fields(&[0xC1, 0x00]),
485            Err(Error::UnsupportedType { type_code: 12, .. })
486        ));
487    }
488}