Skip to main content

ledger_engine/
bookchanges.rs

1//! `book_changes`: for every order book touched in a ledger, the volumes that
2//! crossed and the open, close, high and low rates, as in Clio 2.8
3//! (`BookChangesHelper.hpp`) and xrpld (`BookChanges.h`).
4//!
5//! Only offers that were partly or fully consumed count: a created offer has
6//! nothing crossed yet, and an offer deleted by the transaction's own
7//! `OfferSequence` (OfferCancel, or OfferCreate replacing an offer) was cancelled.
8//!
9//! Rates and sums follow xrpld's `STAmount` arithmetic to the last digit:
10//! `divide` scales both mantissas to 16 digits and keeps 17 more in the
11//! quotient; additions go through `Number` in the large mantissa range
12//! (19 digits) and are rounded back to the 16 digits of an issued amount,
13//! both times to nearest with ties to even.
14
15use std::collections::BTreeMap;
16
17use serde_json::{Map, Value, json};
18
19use crate::xrpl_json::{self, number_text};
20
21/// Issued amount: sign, mantissa in [10^15, 10^16) (0 for zero), exponent.
22#[derive(Debug, Clone, Copy, PartialEq, Eq)]
23struct Iou {
24    neg: bool,
25    m: u64,
26    e: i32,
27}
28
29const IOU_ZERO: Iou = Iou {
30    neg: false,
31    m: 0,
32    e: 0,
33};
34const MIN16: u128 = 1_000_000_000_000_000;
35const MAX16: u128 = 9_999_999_999_999_999;
36const MIN19: u128 = 1_000_000_000_000_000_000;
37const MAX19: u128 = 9_999_999_999_999_999_999;
38/// `Number::kMaxRepUp`: a larger 19-digit mantissa does not fit an int64 and
39/// loses one more digit before rounding.
40const MAX_REP_UP: u128 = 9_223_372_036_854_775_810;
41/// Exponent range of an issued amount.
42const MIN_EXP: i32 = -96;
43const MAX_EXP: i32 = 80;
44
45/// Drops digits until `v` is at most `max`, then rounds to nearest with ties to
46/// even, like `Number::Guard`: `digit` is the highest dropped digit and `sticky`
47/// tells whether anything below it was nonzero. Starts with an empty guard.
48fn round_to(mut v: u128, mut e: i32, max: u128) -> (u128, i32) {
49    let (mut digit, mut sticky) = (0u128, false);
50    while v > max {
51        sticky |= digit != 0;
52        digit = v % 10;
53        v /= 10;
54        e += 1;
55    }
56    if digit > 5 || (digit == 5 && (sticky || v % 2 == 1)) {
57        v += 1;
58        if v > max {
59            v /= 10;
60            e += 1;
61        }
62    }
63    (v, e)
64}
65
66/// An exact value as `Number` holds it in the large range: 19 digits, or 18
67/// when the 19-digit mantissa would not fit an int64.
68fn number(mut v: u128, mut e: i32) -> (u128, i32) {
69    while v < MIN19 {
70        v *= 10;
71        e -= 1;
72    }
73    // The first 19 digits decide whether one more goes; all dropped digits
74    // share one guard in xrpld, so this is a single rounding.
75    let head = v / 10u128.pow(digits(v).saturating_sub(19));
76    let max = if head > MAX_REP_UP { MAX19 / 10 } else { MAX19 };
77    let (mut v, mut e) = round_to(v, e, max);
78    while v < MIN19 {
79        v *= 10;
80        e -= 1;
81    }
82    (v, e)
83}
84
85fn digits(v: u128) -> u32 {
86    v.checked_ilog10().map_or(1, |l| l + 1)
87}
88
89/// `IOUAmount` from a `Number`: rounded to 16 digits; too small is zero, too
90/// large is an overflow (xrpld throws).
91fn iou(neg: bool, v: u128, e: i32) -> Option<Iou> {
92    if v == 0 {
93        return Some(IOU_ZERO);
94    }
95    let (v, e) = round_to(v, e, MAX16);
96    let (v, e) = {
97        let (mut v, mut e) = (v, e);
98        while v < MIN16 {
99            v *= 10;
100            e -= 1;
101        }
102        (v, e)
103    };
104    if e > MAX_EXP {
105        return None;
106    }
107    if e < MIN_EXP {
108        return Some(IOU_ZERO);
109    }
110    Some(Iou {
111        neg,
112        m: v as u64,
113        e,
114    })
115}
116
117/// `IOUAmount` addition: both sides go to `Number`, the sum comes back as an issued amount.
118fn iou_add(a: Iou, b: Iou) -> Option<Iou> {
119    if b.m == 0 {
120        return Some(a);
121    }
122    if a.m == 0 {
123        return Some(b);
124    }
125    let (hi, lo) = if a.e >= b.e { (a, b) } else { (b, a) };
126    let d = (hi.e - lo.e) as u32;
127    // Past 22 digits apart, the smaller side is below half a unit of the 19th
128    // digit of the larger and only decides the rounding, which keeps the larger.
129    if d > 22 {
130        return Some(hi);
131    }
132    let signed = |x: Iou, scale: u32| {
133        let v = i128::from(x.m) * 10i128.pow(scale);
134        if x.neg { -v } else { v }
135    };
136    let s = signed(hi, d) + signed(lo, 0);
137    if s == 0 {
138        return Some(IOU_ZERO);
139    }
140    let (v, e) = number(s.unsigned_abs(), lo.e);
141    iou(s < 0, v, e)
142}
143
144/// Amount of an offer side.
145#[derive(Debug, Clone, Copy, PartialEq, Eq)]
146enum Amount {
147    Drops(i64),
148    Iou(Iou),
149    Mpt(i64),
150}
151
152impl Amount {
153    fn is_zero(&self) -> bool {
154        match *self {
155            Amount::Drops(v) | Amount::Mpt(v) => v == 0,
156            Amount::Iou(x) => x.m == 0,
157        }
158    }
159
160    fn is_negative(&self) -> bool {
161        match *self {
162            Amount::Drops(v) | Amount::Mpt(v) => v < 0,
163            Amount::Iou(x) => x.neg && x.m != 0,
164        }
165    }
166
167    fn neg(self) -> Amount {
168        match self {
169            Amount::Drops(v) => Amount::Drops(-v),
170            Amount::Mpt(v) => Amount::Mpt(-v),
171            Amount::Iou(x) => Amount::Iou(Iou {
172                neg: x.m != 0 && !x.neg,
173                ..x
174            }),
175        }
176    }
177
178    fn add(self, o: Amount) -> Option<Amount> {
179        match (self, o) {
180            (Amount::Drops(a), Amount::Drops(b)) => a.checked_add(b).map(Amount::Drops),
181            (Amount::Mpt(a), Amount::Mpt(b)) => a.checked_add(b).map(Amount::Mpt),
182            (Amount::Iou(a), Amount::Iou(b)) => iou_add(a, b).map(Amount::Iou),
183            _ => None,
184        }
185    }
186
187    /// Mantissa, exponent and sign for `divide`; integral amounts are brought
188    /// up to 16 digits first.
189    fn for_divide(&self) -> (u128, i32, bool) {
190        match *self {
191            Amount::Drops(v) | Amount::Mpt(v) => {
192                let (mut m, mut e) = (u128::from(v.unsigned_abs()), 0);
193                if m != 0 {
194                    while m < MIN16 {
195                        m *= 10;
196                        e -= 1;
197                    }
198                }
199                (m, e, v < 0)
200            }
201            Amount::Iou(x) => (u128::from(x.m), x.e, x.neg),
202        }
203    }
204
205    /// Volume as text: drops or MPT units as an integer, an issued amount as
206    /// `to_string(IOUAmount)`.
207    fn text(&self) -> String {
208        match *self {
209            Amount::Drops(v) | Amount::Mpt(v) => v.to_string(),
210            Amount::Iou(x) => rate_text(x),
211        }
212    }
213}
214
215/// `divide(num, den, noIssue())`: the rate of a crossing.
216fn divide(num: Amount, den: Amount) -> Option<Iou> {
217    if num.is_zero() {
218        return Some(IOU_ZERO);
219    }
220    let (nv, ne, nneg) = num.for_divide();
221    let (dv, de, dneg) = den.for_divide();
222    if dv == 0 {
223        return None;
224    }
225    let q = nv * 100_000_000_000_000_000 / dv;
226    if q > u128::from(u64::MAX) {
227        return None;
228    }
229    let (v, e) = number(q + 5, ne - de - 17);
230    iou(nneg != dneg, v, e)
231}
232
233/// `STAmount` order for rates.
234fn less(a: Iou, b: Iou) -> bool {
235    let (an, bn) = (a.neg && a.m != 0, b.neg && b.m != 0);
236    if an != bn {
237        return an;
238    }
239    if a.m == 0 {
240        return !bn && b.m != 0;
241    }
242    if b.m == 0 {
243        return false;
244    }
245    if a.e != b.e {
246        return (a.e < b.e) != an;
247    }
248    (a.m < b.m) != an
249}
250
251/// `to_string(IOUAmount)`: through `Number`, large range.
252fn rate_text(x: Iou) -> String {
253    number_text(x.neg && x.m != 0, u128::from(x.m), x.e, 18)
254}
255
256/// Issued amount from its JSON text, as `STAmount::getText` wrote it: exact,
257/// at most 16 digits.
258fn parse_iou(s: &str) -> Option<Iou> {
259    let (neg, s) = match s.strip_prefix('-') {
260        Some(r) => (true, r),
261        None => (false, s),
262    };
263    let (num, exp) = match s.split_once('e') {
264        Some((n, x)) => (n, x.parse::<i32>().ok()?),
265        None => (s, 0),
266    };
267    let (int, frac) = num.split_once('.').unwrap_or((num, ""));
268    let digits = format!("{int}{frac}");
269    if digits.is_empty() || !digits.bytes().all(|b| b.is_ascii_digit()) {
270        return None;
271    }
272    let trimmed = digits.trim_start_matches('0');
273    if trimmed.is_empty() {
274        return Some(IOU_ZERO);
275    }
276    if trimmed.len() > 19 {
277        return None;
278    }
279    let v: u128 = trimmed.parse().ok()?;
280    let e = exp - frac.len() as i32;
281    iou(neg, v, e)
282}
283
284/// Offer side from its JSON form, with the asset as `to_string(Asset)` writes it.
285fn amount(v: &Value) -> Option<(Amount, String)> {
286    match v {
287        Value::String(s) => Some((Amount::Drops(s.parse().ok()?), "XRP".into())),
288        Value::Object(o) => {
289            let value = o.get("value")?.as_str()?;
290            if let Some(id) = o.get("mpt_issuance_id").and_then(Value::as_str) {
291                return Some((Amount::Mpt(value.parse().ok()?), id.to_owned()));
292            }
293            let currency = o.get("currency")?.as_str()?;
294            let issuer = o.get("issuer")?.as_str()?;
295            Some((
296                Amount::Iou(parse_iou(value)?),
297                format!("{issuer}/{currency}"),
298            ))
299        }
300        _ => None,
301    }
302}
303
304/// One order book in the ledger.
305#[derive(Debug)]
306struct Change {
307    a: (Amount, String),
308    b: (Amount, String),
309    high: Iou,
310    low: Iou,
311    open: Iou,
312    close: Iou,
313    domain: Option<String>,
314}
315
316#[derive(Debug, Default)]
317struct Tally {
318    books: BTreeMap<String, Change>,
319}
320
321impl Tally {
322    /// Transactions of one ledger, in the order of their hashes (as both Clio and
323    /// xrpld walk them: it decides the open and close rates).
324    fn transaction(&mut self, tx: &Map<String, Value>, meta: &Map<String, Value>) {
325        if !tx.contains_key("TransactionType") {
326            return;
327        }
328        let cancel = match tx.get("TransactionType").and_then(Value::as_str) {
329            Some("OfferCancel" | "OfferCreate") => tx.get("OfferSequence").and_then(Value::as_u64),
330            _ => None,
331        };
332        let nodes = meta
333            .get("AffectedNodes")
334            .and_then(Value::as_array)
335            .into_iter()
336            .flatten()
337            .filter_map(|n| n.as_object()?.iter().next());
338        for (kind, node) in nodes {
339            if let Some(node) = node.as_object() {
340                self.node(kind, node, cancel);
341            }
342        }
343    }
344
345    fn node(&mut self, kind: &str, node: &Map<String, Value>, cancel: Option<u64>) {
346        if node.get("LedgerEntryType").and_then(Value::as_str) != Some("Offer")
347            || kind == "CreatedNode"
348        {
349            return;
350        }
351        let (Some(ff), Some(pf)) = (
352            node.get("FinalFields").and_then(Value::as_object),
353            node.get("PreviousFields").and_then(Value::as_object),
354        ) else {
355            return;
356        };
357        let side = |o: &Map<String, Value>, f: &str| o.get(f).and_then(amount);
358        let (Some(fg), Some(fp), Some(pg), Some(pp)) = (
359            side(ff, "TakerGets"),
360            side(ff, "TakerPays"),
361            side(pf, "TakerGets"),
362            side(pf, "TakerPays"),
363        ) else {
364            return;
365        };
366        if kind == "DeletedNode"
367            && cancel.is_some()
368            && ff.get("Sequence").and_then(Value::as_u64) == cancel
369        {
370            return;
371        }
372        let (Some(gets), Some(pays)) = (fg.0.add(pg.0.neg()), fp.0.add(pp.0.neg())) else {
373            return;
374        };
375        let domain = ff
376            .get("DomainID")
377            .and_then(Value::as_str)
378            .map(str::to_owned);
379        self.store((gets, fg.1), (pays, fp.1), domain);
380    }
381
382    fn store(&mut self, gets: (Amount, String), pays: (Amount, String), domain: Option<String>) {
383        let xrp = |s: &(Amount, String)| matches!(s.0, Amount::Drops(_));
384        let noswap = xrp(&gets) || (!xrp(&pays) && gets.1 < pays.1);
385        let (mut first, mut second) = if noswap { (gets, pays) } else { (pays, gets) };
386        if second.0.is_zero() {
387            return;
388        }
389        let Some(rate) = divide(first.0, second.0) else {
390            return;
391        };
392        if first.0.is_negative() {
393            first.0 = first.0.neg();
394        }
395        if second.0.is_negative() {
396            second.0 = second.0.neg();
397        }
398        let key = format!("{}|{}", first.1, second.1);
399        match self.books.get_mut(&key) {
400            None => {
401                self.books.insert(
402                    key,
403                    Change {
404                        a: first,
405                        b: second,
406                        high: rate,
407                        low: rate,
408                        open: rate,
409                        close: rate,
410                        domain,
411                    },
412                );
413            }
414            Some(c) => {
415                let (Some(a), Some(b)) = (c.a.0.add(first.0), c.b.0.add(second.0)) else {
416                    return;
417                };
418                c.a.0 = a;
419                c.b.0 = b;
420                if less(c.high, rate) {
421                    c.high = rate;
422                }
423                if less(rate, c.low) {
424                    c.low = rate;
425                }
426                c.close = rate;
427                c.domain = domain;
428            }
429        }
430    }
431
432    fn json(self) -> Vec<Value> {
433        let side = |s: &(Amount, String), cur: &str, mpt: &str, m: &mut Map<String, Value>| {
434            match s.0 {
435                Amount::Drops(_) => m.insert(cur.into(), json!("XRP_drops")),
436                Amount::Mpt(_) => m.insert(mpt.into(), json!(s.1)),
437                Amount::Iou(_) => m.insert(cur.into(), json!(s.1)),
438            };
439        };
440        self.books
441            .into_values()
442            .map(|c| {
443                let mut m = Map::new();
444                side(&c.a, "currency_a", "mpt_issuance_id_a", &mut m);
445                side(&c.b, "currency_b", "mpt_issuance_id_b", &mut m);
446                m.insert("volume_a".into(), json!(c.a.0.text()));
447                m.insert("volume_b".into(), json!(c.b.0.text()));
448                m.insert("high".into(), json!(rate_text(c.high)));
449                m.insert("low".into(), json!(rate_text(c.low)));
450                m.insert("open".into(), json!(rate_text(c.open)));
451                m.insert("close".into(), json!(rate_text(c.close)));
452                if let Some(d) = c.domain {
453                    m.insert("domain".into(), json!(d));
454                }
455                Value::Object(m)
456            })
457            .collect()
458    }
459}
460
461/// The `changes` array for a ledger's transactions (binary transaction and
462/// metadata). A transaction that does not parse is skipped, as in Clio.
463pub fn compute(transactions: &[(Vec<u8>, Vec<u8>)]) -> Vec<Value> {
464    let mut txs: Vec<([u8; 32], &[u8], &[u8])> = transactions
465        .iter()
466        .map(|(t, m)| (witness_core::shamap::tx_id(t), &t[..], &m[..]))
467        .collect();
468    txs.sort_by_key(|t| t.0);
469    let mut tally = Tally::default();
470    for (_, tx, meta) in txs {
471        let (Ok(tx), Ok(meta)) = (xrpl_json::transaction(tx), xrpl_json::metadata(meta)) else {
472            continue;
473        };
474        tally.transaction(&tx, &meta);
475    }
476    tally.json()
477}
478
479#[cfg(test)]
480mod tests {
481    use super::*;
482
483    fn x(s: &str) -> Iou {
484        parse_iou(s).unwrap()
485    }
486
487    #[test]
488    fn issued_amounts_round_trip_through_text() {
489        for s in [
490            "0.044229388832",
491            "892.44067",
492            "1",
493            "-12.5",
494            "1234567890123456e-90",
495            "9999999999999999e80",
496            "0.000001",
497        ] {
498            assert_eq!(rate_text(x(s)), s, "{s}");
499        }
500        assert_eq!(x("0"), IOU_ZERO);
501        assert_eq!(parse_iou("1.2.3"), None);
502    }
503
504    #[test]
505    fn rates_divide_as_xrpld() {
506        // From xrpld 3.4.1 book_changes on mainnet ledger 107998249.
507        let r = divide(Amount::Drops(-100), Amount::Iou(x("-0.044229388832"))).unwrap();
508        assert_eq!(rate_text(r), "2260.940126933202");
509        let r = divide(Amount::Drops(-712_300_000), Amount::Iou(x("-892.44067"))).unwrap();
510        assert_eq!(rate_text(r), "798148.2959533882");
511        let r = divide(Amount::Drops(-5_730_000), Amount::Iou(x("-7.178051"))).unwrap();
512        assert_eq!(rate_text(r), "798266.827583142");
513    }
514
515    #[test]
516    fn rounding_is_to_nearest_ties_to_even() {
517        assert_eq!(round_to(12345, 0, 9999), (1234, 1));
518        assert_eq!(round_to(12355, 0, 9999), (1236, 1));
519        assert_eq!(round_to(12350, 0, 9999), (1235, 1));
520        assert_eq!(round_to(12250, 0, 9999), (1225, 1));
521        assert_eq!(round_to(1225, 0, 999), (122, 1));
522        assert_eq!(round_to(12251, 0, 999), (123, 2));
523        assert_eq!(round_to(99_999, 0, 9999), (1000, 2));
524    }
525
526    #[test]
527    fn sums_keep_sixteen_digits() {
528        let s = iou_add(x("1"), x("0.0000000000000001")).unwrap();
529        assert_eq!(rate_text(s), "1");
530        let s = iou_add(x("1"), x("0.000000000000001")).unwrap();
531        assert_eq!(rate_text(s), "1.000000000000001");
532        let s = iou_add(x("1"), x("-1")).unwrap();
533        assert_eq!(s, IOU_ZERO);
534        let s = iou_add(x("1e40"), x("1")).unwrap();
535        assert_eq!(rate_text(s), "1e40");
536    }
537
538    #[test]
539    fn rates_order_like_stamount() {
540        assert!(less(x("1"), x("2")));
541        assert!(less(x("-2"), x("-1")));
542        assert!(less(x("-1"), IOU_ZERO));
543        assert!(less(IOU_ZERO, x("0.1")));
544        assert!(less(x("0.9"), x("1")));
545        assert!(!less(x("1"), x("1")));
546    }
547}