Skip to main content

ledger_engine/
delta.rs

1//! A ledger's state changes, stored as a diff against what is already known:
2//! the previous version of the object and the transaction metadata.
3//!
4//! Measured on 2048 mainnet ledgers (1.08 million objects, each one
5//! restored byte for byte): full objects take 26.8 KB per ledger in zstd-19
6//! blocks, this diff takes 8.8.
7//!
8//! For every created or modified object a "base" is built, with no
9//! protocol logic, only from what is at hand:
10//! - the object was touched by the ledger's transactions: the previous version
11//!   (nothing for a created one), overlaid with the fields from the last
12//!   touching transaction (NewFields for a created object, FinalFields for a
13//!   modified one), LedgerEntryType, PreviousTxnID and PreviousTxnLgrSeq set to
14//!   that transaction and this ledger, and Flags = 0 if the field is missing
15//!   (every object has it, and a zero value never appears in NewFields);
16//! - not touched (LedgerHashes and the like): the previous version.
17//!
18//! What gets stored is the remainder: changed and new fields in full, changed
19//! Vector256 lists as a patch (removed positions, inserted items), deleted fields
20//! by code. Whatever is missing from the metadata (directory Indexes, page
21//! numbers) ends up in the remainder.
22//!
23//! Encoding checks itself: every object is rebuilt right away and compared
24//! byte for byte. If it does not match, or the remainder is not shorter than
25//! the object, the full object is stored.
26
27use std::collections::HashMap;
28
29use witness_core::shamap::{encode_vl, tx_id};
30use witness_core::stobject::{self, Field, types};
31
32use crate::ledger::{Change, Ledger, StateChange};
33
34type Res<T> = Result<T, String>;
35type FieldKey = (u16, u16);
36
37const AFFECTED_NODES: FieldKey = (types::ARRAY, 8);
38const CREATED_NODE: FieldKey = (types::OBJECT, 3);
39const FINAL_FIELDS: FieldKey = (types::OBJECT, 7);
40const NEW_FIELDS: FieldKey = (types::OBJECT, 8);
41const LEDGER_INDEX: FieldKey = (types::HASH256, 6);
42const LEDGER_ENTRY_TYPE: FieldKey = (types::UINT16, 1);
43const TX_INDEX: FieldKey = (types::UINT32, 28);
44const FLAGS: FieldKey = (types::UINT32, 2);
45const PREVIOUS_TXN_ID: FieldKey = (types::HASH256, 5);
46const PREVIOUS_TXN_LGR_SEQ: FieldKey = (types::UINT32, 5);
47
48/// Kind of change record.
49const DELETED: u8 = 0;
50const FULL: u8 = 1;
51const DIFF: u8 = 2;
52
53fn e<E: std::fmt::Display>(x: E) -> String {
54    x.to_string()
55}
56
57fn fid(f: &Field<'_>) -> FieldKey {
58    (f.id.type_code, f.id.field_code)
59}
60
61fn put_u16(out: &mut Vec<u8>, v: usize) -> Res<()> {
62    let v = u16::try_from(v).map_err(|_| "value does not fit in u16")?;
63    out.extend_from_slice(&v.to_le_bytes());
64    Ok(())
65}
66
67fn field_header(t: u16, f: u16) -> Vec<u8> {
68    let mut h =
69        vec![(if t < 16 { (t as u8) << 4 } else { 0 }) | (if f < 16 { f as u8 } else { 0 })];
70    if t >= 16 {
71        h.push(t as u8);
72    }
73    if f >= 16 {
74        h.push(f as u8);
75    }
76    h
77}
78
79/// The last transaction in the ledger that touched the object: its hash, its
80/// fields for the object and LedgerEntryType (raw field bytes).
81#[derive(Debug, Clone)]
82pub struct Touch {
83    tx: [u8; 32],
84    fields: Vec<u8>,
85    entry_type: Vec<u8>,
86}
87
88/// Objects touched by the ledger's transactions, in order of application.
89pub fn touches(l: &Ledger) -> Res<HashMap<[u8; 32], Touch>> {
90    let mut order: Vec<(u32, &[u8], &[u8])> = Vec::with_capacity(l.transactions.len());
91    for (tx, meta) in &l.transactions {
92        let f = stobject::fields(meta).map_err(e)?;
93        let idx = f
94            .iter()
95            .find(|x| fid(x) == TX_INDEX)
96            .and_then(|x| stobject::u32_of(x.value))
97            .ok_or("no TransactionIndex in metadata")?;
98        order.push((idx, tx, meta));
99    }
100    order.sort_by_key(|o| o.0);
101    let mut out = HashMap::new();
102    for (_, tx, meta) in order {
103        let id = tx_id(tx);
104        let f = stobject::fields(meta).map_err(e)?;
105        let Some(nodes) = f.iter().find(|x| fid(x) == AFFECTED_NODES) else {
106            continue;
107        };
108        for node in stobject::children(nodes).map_err(e)? {
109            let inner = stobject::children(&node).map_err(e)?;
110            let Some(key) = inner
111                .iter()
112                .find(|x| fid(x) == LEDGER_INDEX)
113                .and_then(|x| <[u8; 32]>::try_from(x.value).ok())
114            else {
115                continue;
116            };
117            let want = if fid(&node) == CREATED_NODE {
118                NEW_FIELDS
119            } else {
120                FINAL_FIELDS
121            };
122            out.insert(
123                key,
124                Touch {
125                    tx: id,
126                    fields: inner
127                        .iter()
128                        .find(|x| fid(x) == want)
129                        .map(|x| x.value.to_vec())
130                        .unwrap_or_default(),
131                    entry_type: inner
132                        .iter()
133                        .find(|x| fid(x) == LEDGER_ENTRY_TYPE)
134                        .map(|x| x.raw.to_vec())
135                        .unwrap_or_default(),
136                },
137            );
138        }
139    }
140    Ok(out)
141}
142
143/// The object's base (see the module docs).
144fn base(prev: Option<&[u8]>, touch: Option<&Touch>, seq: u32) -> Res<Vec<u8>> {
145    let mut all: Vec<(FieldKey, Vec<u8>)> = match prev {
146        Some(p) => stobject::fields(p)
147            .map_err(e)?
148            .iter()
149            .map(|x| (fid(x), x.raw.to_vec()))
150            .collect(),
151        None => Vec::new(),
152    };
153    if let Some(t) = touch {
154        let mut set = |k: FieldKey, raw: Vec<u8>| {
155            all.retain(|(i, _)| *i != k);
156            all.push((k, raw));
157        };
158        for x in stobject::fields(&t.fields).map_err(e)? {
159            set(fid(&x), x.raw.to_vec());
160        }
161        if !t.entry_type.is_empty() {
162            set(LEDGER_ENTRY_TYPE, t.entry_type.clone());
163        }
164        let mut txid = field_header(PREVIOUS_TXN_ID.0, PREVIOUS_TXN_ID.1);
165        txid.extend_from_slice(&t.tx);
166        set(PREVIOUS_TXN_ID, txid);
167        let mut lseq = field_header(PREVIOUS_TXN_LGR_SEQ.0, PREVIOUS_TXN_LGR_SEQ.1);
168        lseq.extend_from_slice(&seq.to_be_bytes());
169        set(PREVIOUS_TXN_LGR_SEQ, lseq);
170        if !all.iter().any(|(k, _)| *k == FLAGS) {
171            all.push((FLAGS, vec![0x22, 0, 0, 0, 0]));
172        }
173    }
174    all.sort_by_key(|(k, _)| *k);
175    Ok(all.into_iter().flat_map(|(_, r)| r).collect())
176}
177
178/// A patch for a list of 32-byte items: removed positions and inserted (position,
179/// item) pairs. `None` if the order of the remaining items changed.
180fn vector_patch(old: &[u8], new: &[u8]) -> Res<Option<Vec<u8>>> {
181    let (o, n): (Vec<&[u8]>, Vec<&[u8]>) = (old.chunks(32).collect(), new.chunks(32).collect());
182    let removed: Vec<usize> = (0..o.len()).filter(|i| !n.contains(&o[*i])).collect();
183    let inserted: Vec<usize> = (0..n.len()).filter(|j| !o.contains(&n[*j])).collect();
184    let kept_old: Vec<&[u8]> = (0..o.len())
185        .filter(|i| !removed.contains(i))
186        .map(|i| o[i])
187        .collect();
188    let kept_new: Vec<&[u8]> = (0..n.len())
189        .filter(|j| !inserted.contains(j))
190        .map(|j| n[j])
191        .collect();
192    if kept_old != kept_new {
193        return Ok(None);
194    }
195    let mut out = Vec::new();
196    put_u16(&mut out, removed.len())?;
197    for i in removed {
198        put_u16(&mut out, i)?;
199    }
200    put_u16(&mut out, inserted.len())?;
201    for j in inserted {
202        put_u16(&mut out, j)?;
203        out.extend_from_slice(n[j]);
204    }
205    Ok(Some(out))
206}
207
208/// The remainder: what to change in the base to get the object.
209fn diff(base: &[u8], new: &[u8]) -> Res<Vec<u8>> {
210    let p = stobject::fields(base).map_err(e)?;
211    let n = stobject::fields(new).map_err(e)?;
212    let (mut changed, mut count, mut patches, mut npatch) = (Vec::new(), 0, Vec::new(), 0);
213    for f in &n {
214        let old = p.iter().find(|x| x.id == f.id);
215        if old.is_some_and(|x| x.raw == f.raw) {
216            continue;
217        }
218        if f.id.type_code == types::VECTOR256
219            && let Some(o) = old
220            && let Some(vp) = vector_patch(o.value, f.value)?
221            && vp.len() + 2 < f.raw.len()
222        {
223            put_u16(&mut patches, usize::from(f.id.field_code))?;
224            patches.extend_from_slice(&vp);
225            npatch += 1;
226            continue;
227        }
228        changed.extend_from_slice(f.raw);
229        count += 1;
230    }
231    let removed: Vec<_> = p
232        .iter()
233        .filter(|x| !n.iter().any(|f| f.id == x.id))
234        .collect();
235    let mut out = Vec::with_capacity(changed.len() + patches.len() + 8);
236    put_u16(&mut out, count)?;
237    out.extend_from_slice(&(changed.len() as u32).to_le_bytes());
238    out.extend_from_slice(&changed);
239    put_u16(&mut out, npatch)?;
240    out.extend_from_slice(&patches);
241    put_u16(&mut out, removed.len())?;
242    for r in removed {
243        put_u16(&mut out, usize::from(r.id.type_code))?;
244        put_u16(&mut out, usize::from(r.id.field_code))?;
245    }
246    Ok(out)
247}
248
249struct Cursor<'a> {
250    b: &'a [u8],
251    at: usize,
252}
253
254impl<'a> Cursor<'a> {
255    fn take(&mut self, n: usize) -> Res<&'a [u8]> {
256        let s = self
257            .b
258            .get(self.at..self.at + n)
259            .ok_or("changes truncated")?;
260        self.at += n;
261        Ok(s)
262    }
263    fn u16(&mut self) -> Res<usize> {
264        let s = self.take(2)?;
265        Ok(usize::from(u16::from_le_bytes([s[0], s[1]])))
266    }
267    fn u32(&mut self) -> Res<usize> {
268        let s = self.take(4)?;
269        Ok(u32::from_le_bytes([s[0], s[1], s[2], s[3]]) as usize)
270    }
271}
272
273/// An object from a base and a remainder.
274fn apply(base: &[u8], c: &mut Cursor<'_>) -> Res<Vec<u8>> {
275    let _count = c.u16()?;
276    let len = c.u32()?;
277    let changed = stobject::fields(c.take(len)?).map_err(e)?;
278    let p = stobject::fields(base).map_err(e)?;
279    let mut rebuilt: Vec<(FieldKey, Vec<u8>)> = Vec::new();
280    for _ in 0..c.u16()? {
281        let fcode = c.u16()? as u16;
282        let old = p
283            .iter()
284            .find(|x| fid(x) == (types::VECTOR256, fcode))
285            .ok_or("list patch without a previous value")?;
286        let mut rem = Vec::new();
287        for _ in 0..c.u16()? {
288            rem.push(c.u16()?);
289        }
290        let mut items: Vec<&[u8]> = old
291            .value
292            .chunks(32)
293            .enumerate()
294            .filter(|(i, _)| !rem.contains(i))
295            .map(|(_, v)| v)
296            .collect();
297        for _ in 0..c.u16()? {
298            let pos = c.u16()?;
299            let h = c.take(32)?;
300            if pos > items.len() {
301                return Err("list patch: position outside the list".into());
302            }
303            items.insert(pos, h);
304        }
305        let value = items.concat();
306        let mut raw = field_header(types::VECTOR256, fcode);
307        encode_vl(value.len(), &mut raw);
308        raw.extend_from_slice(&value);
309        rebuilt.push(((types::VECTOR256, fcode), raw));
310    }
311    let mut removed = Vec::new();
312    for _ in 0..c.u16()? {
313        removed.push((c.u16()? as u16, c.u16()? as u16));
314    }
315    let replaced = |k: FieldKey| {
316        removed.contains(&k)
317            || changed.iter().any(|x| fid(x) == k)
318            || rebuilt.iter().any(|(r, _)| *r == k)
319    };
320    let mut all: Vec<(FieldKey, Vec<u8>)> = p
321        .iter()
322        .filter(|x| !replaced(fid(x)))
323        .map(|x| (fid(x), x.raw.to_vec()))
324        .collect();
325    all.extend(changed.iter().map(|x| (fid(x), x.raw.to_vec())));
326    all.extend(rebuilt);
327    all.sort_by_key(|(k, _)| *k);
328    Ok(all.into_iter().flat_map(|(_, r)| r).collect())
329}
330
331/// The previous version of the object, as of the ledger before this one; `None` if it did not exist.
332pub type Prev<'a> = dyn Fn(&[u8; 32]) -> Res<Option<Vec<u8>>> + 'a;
333
334/// Changes of ledger `seq` as a format 3 record. Returns the record and how many
335/// objects had to be stored in full.
336pub fn encode(l: &Ledger, seq: u32, prev: &Prev<'_>) -> Res<(Vec<u8>, usize)> {
337    // Metadata this build cannot read (a field type from a newer xrpld) gives
338    // no touches: objects are then diffed against their previous version
339    // only, or stored in full. `decode` does the same on the same ledger.
340    let touched = touches(l).unwrap_or_default();
341    let mut out = (l.changes.len() as u32).to_le_bytes().to_vec();
342    let mut full = 0;
343    for c in &l.changes {
344        out.extend_from_slice(&c.key);
345        if c.change == Change::Deleted {
346            out.push(DELETED);
347            continue;
348        }
349        let prior = if c.change == Change::Modified {
350            prev(&c.key)?
351        } else {
352            None
353        };
354        // An object this build cannot read is stored in full.
355        let (b, d) = match base(prior.as_deref(), touched.get(&c.key), seq)
356            .and_then(|b| diff(&b, &c.data).map(|d| (b, d)))
357        {
358            Ok(bd) => bd,
359            Err(_) => (Vec::new(), c.data.clone()),
360        };
361        let ok = d.len() < c.data.len()
362            && apply(&b, &mut Cursor { b: &d, at: 0 }).is_ok_and(|x| x == c.data);
363        let kind = match c.change {
364            Change::Created => 0x10,
365            _ => 0x20,
366        };
367        if ok {
368            out.push(kind | DIFF);
369            out.extend_from_slice(&(d.len() as u32).to_le_bytes());
370            out.extend_from_slice(&d);
371        } else {
372            full += 1;
373            out.push(kind | FULL);
374            out.extend_from_slice(&(c.data.len() as u32).to_le_bytes());
375            out.extend_from_slice(&c.data);
376        }
377    }
378    Ok((out, full))
379}
380
381/// Changes of a ledger from a format 3 record; `l` is the ledger with its transactions.
382pub fn decode(l: &Ledger, seq: u32, record: &[u8], prev: &Prev<'_>) -> Res<Vec<StateChange>> {
383    let touched = touches(l).unwrap_or_default();
384    let mut c = Cursor { b: record, at: 0 };
385    let n = c.u32()?;
386    let mut out = Vec::with_capacity(n);
387    for _ in 0..n {
388        let key: [u8; 32] = c.take(32)?.try_into().map_err(e)?;
389        let tag = c.take(1)?[0];
390        if tag == DELETED {
391            out.push(StateChange {
392                key,
393                change: Change::Deleted,
394                data: Vec::new(),
395            });
396            continue;
397        }
398        let change = match tag & 0xF0 {
399            0x10 => Change::Created,
400            0x20 => Change::Modified,
401            _ => return Err(format!("unknown change record {tag:#04x}")),
402        };
403        let len = c.u32()?;
404        let payload = c.take(len)?;
405        let data = match tag & 0x0F {
406            FULL => payload.to_vec(),
407            DIFF => {
408                let prior = if change == Change::Modified {
409                    prev(&key)?
410                } else {
411                    None
412                };
413                let b = base(prior.as_deref(), touched.get(&key), seq)?;
414                apply(&b, &mut Cursor { b: payload, at: 0 })?
415            }
416            _ => return Err(format!("unknown change record {tag:#04x}")),
417        };
418        out.push(StateChange { key, change, data });
419    }
420    if c.at != record.len() {
421        return Err("trailing bytes after the changes".into());
422    }
423    Ok(out)
424}
425
426#[cfg(test)]
427mod tests {
428    use super::*;
429
430    fn obj(fields: &[(&[u8], &[u8])]) -> Vec<u8> {
431        fields
432            .iter()
433            .flat_map(|(h, v)| h.iter().chain(v.iter()).copied())
434            .collect()
435    }
436
437    #[test]
438    fn vector_patches_roundtrip() {
439        // Directory: Flags, Indexes (Vector256 field 1), one key removed, two added.
440        let mut idx_old = vec![0x01, 0x13, 96];
441        for i in 1..=3u8 {
442            idx_old.extend([i; 32]);
443        }
444        let mut idx_new = vec![0x01, 0x13, 96];
445        for i in [1u8, 9, 3] {
446            idx_new.extend([i; 32]);
447        }
448        let a = obj(&[
449            (&[0x11], &[0, 0x64]),
450            (&[0x22], &[0, 0, 0, 0]),
451            (&idx_old, &[]),
452        ]);
453        let b = obj(&[
454            (&[0x11], &[0, 0x64]),
455            (&[0x22], &[0, 0, 0, 1]),
456            (&idx_new, &[]),
457        ]);
458        let d = diff(&a, &b).unwrap();
459        assert!(
460            d.len() < 60,
461            "a list patch, not the whole list: {}",
462            d.len()
463        );
464        assert_eq!(apply(&a, &mut Cursor { b: &d, at: 0 }).unwrap(), b);
465    }
466
467    #[test]
468    fn encode_decode_without_transactions() {
469        // A ledger with no transactions: the modified object is a diff against the
470        // previous version, the created one is stored in full (no base), the deleted one by key.
471        let mut header = vec![0u8; 118];
472        header[..4].copy_from_slice(&5u32.to_be_bytes());
473        let prev_obj = obj(&[
474            (&[0x11], &[0, 0x68]),
475            (&[0x22], &[0, 0, 0, 0]),
476            (&[0x24], &[0, 0, 0, 7]),
477            (&[0x51], &[7; 32]),
478        ]);
479        let new_obj = obj(&[
480            (&[0x11], &[0, 0x68]),
481            (&[0x22], &[0, 0, 0, 0]),
482            (&[0x24], &[0, 0, 0, 8]),
483            (&[0x51], &[7; 32]),
484        ]);
485        let l = Ledger {
486            header,
487            transactions: Vec::new(),
488            changes: vec![
489                StateChange {
490                    key: [1; 32],
491                    change: Change::Modified,
492                    data: new_obj.clone(),
493                },
494                StateChange {
495                    key: [2; 32],
496                    change: Change::Created,
497                    data: prev_obj.clone(),
498                },
499                StateChange {
500                    key: [3; 32],
501                    change: Change::Deleted,
502                    data: Vec::new(),
503                },
504            ],
505        };
506        let prev = |k: &[u8; 32]| -> Res<Option<Vec<u8>>> {
507            Ok((*k == [1; 32]).then(|| prev_obj.clone()))
508        };
509        let (rec, full) = encode(&l, 5, &prev).unwrap();
510        assert_eq!(full, 1, "a created object without a base is stored in full");
511        assert_eq!(decode(&l, 5, &rec, &prev).unwrap(), l.changes);
512    }
513}