Skip to main content

ledger_engine/
index.rs

1//! Ledger indexes: transaction by hash, ledger by hash, account history.
2//!
3//! A transaction's accounts follow the same rule as `TxMeta::getAffectedAccounts`
4//! in xrpld (which Clio also uses for account_tx): for every affected
5//! object take the top-level fields from FinalFields, or from NewFields for a
6//! created one; the history gets every account field, plus the issuers of LowLimit,
7//! HighLimit, TakerPays, TakerGets and the issuer of MPTokenIssuanceID.
8
9use witness_core::shamap::tx_id;
10use witness_core::stobject::{self, Field, FieldId, types};
11
12use crate::ledger::Ledger;
13
14const AFFECTED_NODES: FieldId = FieldId::new(types::ARRAY, 8);
15const CREATED_NODE: FieldId = FieldId::new(types::OBJECT, 3);
16const FINAL_FIELDS: FieldId = FieldId::new(types::OBJECT, 7);
17const NEW_FIELDS: FieldId = FieldId::new(types::OBJECT, 8);
18const TRANSACTION_INDEX: FieldId = FieldId::new(types::UINT32, 28);
19const TAKER_PAYS: FieldId = FieldId::new(types::AMOUNT, 4);
20const TAKER_GETS: FieldId = FieldId::new(types::AMOUNT, 5);
21const LOW_LIMIT: FieldId = FieldId::new(types::AMOUNT, 6);
22const HIGH_LIMIT: FieldId = FieldId::new(types::AMOUNT, 7);
23const MPT_ISSUANCE_ID: FieldId = FieldId::new(types::HASH192, 1);
24
25pub type AccountId = [u8; 20];
26
27/// A transaction in the indexes.
28#[derive(Debug, Clone, PartialEq, Eq)]
29pub struct TxEntry {
30    pub id: [u8; 32],
31    /// Position in the ledger's transaction list, as stored in the block.
32    pub pos: u32,
33    /// TransactionIndex from the metadata: order of application in the ledger.
34    pub index: u32,
35    pub accounts: Vec<AccountId>,
36}
37
38/// Accounts affected by a transaction, and its TransactionIndex.
39pub fn affected_accounts(meta: &[u8]) -> Result<(u32, Vec<AccountId>), String> {
40    let fields = stobject::fields(meta).map_err(|e| format!("metadata: {e}"))?;
41    let index = stobject::find(&fields, TRANSACTION_INDEX)
42        .and_then(stobject::u32_of)
43        .ok_or("no TransactionIndex in metadata")?;
44    let mut out: Vec<AccountId> = Vec::new();
45    let mut add = |a: &[u8]| {
46        if let Ok(a) = <AccountId>::try_from(a)
47            && a != [0; 20]
48        {
49            out.push(a);
50        }
51    };
52    let nodes = fields
53        .iter()
54        .find(|f| f.id == AFFECTED_NODES)
55        .ok_or("no AffectedNodes in metadata")?;
56    for node in stobject::children(nodes).map_err(|e| e.to_string())? {
57        let want = if node.id == CREATED_NODE {
58            NEW_FIELDS
59        } else {
60            FINAL_FIELDS
61        };
62        let inner = stobject::children(&node).map_err(|e| e.to_string())?;
63        let Some(inner) = inner.iter().find(|f| f.id == want) else {
64            continue;
65        };
66        for f in stobject::children(inner).map_err(|e| e.to_string())? {
67            issuer_or_account(&f, &mut add);
68        }
69    }
70    out.sort_unstable();
71    out.dedup();
72    Ok((index, out))
73}
74
75fn issuer_or_account(f: &Field<'_>, add: &mut impl FnMut(&[u8])) {
76    if f.id.type_code == types::ACCOUNT {
77        add(f.value);
78    } else if [LOW_LIMIT, HIGH_LIMIT, TAKER_PAYS, TAKER_GETS].contains(&f.id) {
79        // An issued currency amount is 48 bytes, the issuer is the last 20. XRP
80        // has no issuer; MPT never appears in these fields.
81        if f.value.len() == 48 {
82            add(&f.value[28..]);
83        }
84    } else if f.id == MPT_ISSUANCE_ID && f.value.len() == 24 {
85        // MPTID: issuance sequence (4 bytes) and the issuer.
86        add(&f.value[4..]);
87    }
88}
89
90/// The Account field of a transaction, if it can be read.
91fn sender(tx: &[u8]) -> Option<AccountId> {
92    let fs = stobject::fields(tx).ok()?;
93    stobject::find(&fs, stobject::FieldId::new(types::ACCOUNT, 1))?
94        .try_into()
95        .ok()
96}
97
98/// Index entries for a ledger.
99pub fn entries(ledger: &Ledger) -> Result<Vec<TxEntry>, String> {
100    ledger
101        .transactions
102        .iter()
103        .enumerate()
104        .map(|(pos, (tx, meta))| {
105            // Metadata this build cannot read (a field type from a newer
106            // xrpld) must not stop loading: the transaction is indexed by
107            // hash, under its sender, at its position in the ledger, and
108            // crate::unknown reports it.
109            let (index, accounts) = affected_accounts(meta).unwrap_or_else(|e| {
110                tracing::warn!(
111                    "transaction {}: {e}; indexed under its sender only",
112                    hex::encode_upper(tx_id(tx))
113                );
114                (pos as u32, sender(tx).into_iter().collect())
115            });
116            Ok(TxEntry {
117                id: tx_id(tx),
118                pos: pos as u32,
119                index,
120                accounts,
121            })
122        })
123        .collect()
124}
125
126#[cfg(test)]
127mod tests {
128    use super::*;
129
130    fn account_field(code: u8, a: u8) -> Vec<u8> {
131        // Type 8, field code, length 20.
132        let mut v = vec![0x80 | code, 20];
133        v.extend([a; 20]);
134        v
135    }
136
137    fn node(kind: u8, inner_kind: u8, body: &[u8]) -> Vec<u8> {
138        let mut v = vec![0xE0 | kind, 0xE0 | inner_kind];
139        v.extend(body);
140        v.extend([0xE1, 0xE1]);
141        v
142    }
143
144    #[test]
145    fn accounts_follow_xrpld_rule() {
146        // Modified object: Account (8,1) in FinalFields, and in PreviousFields
147        // a different account that does not count.
148        let mut modified = vec![0xE5, 0xE6];
149        modified.extend(account_field(1, 9));
150        modified.push(0xE1);
151        modified.push(0xE7);
152        modified.extend(account_field(1, 1));
153        // HighLimit (6,7): issued currency with issuer 2.
154        modified.extend([0x67, 0x80 | 0x40]);
155        modified.extend([0u8; 7 + 20]);
156        modified.extend([2u8; 20]);
157        modified.extend([0xE1, 0xE1]);
158        // Created object: Destination (8,3) in NewFields.
159        let created = node(3, 8, &account_field(3, 3));
160        // Deleted object: FinalFields; a zero account does not count.
161        let deleted = node(4, 7, &account_field(1, 0));
162
163        let mut meta = vec![0x20, 0x1C, 0, 0, 0, 5]; // TransactionIndex = 5
164        meta.push(0xF8); // AffectedNodes
165        meta.extend(modified);
166        meta.extend(created);
167        meta.extend(deleted);
168        meta.push(0xF1);
169        let (index, accounts) = affected_accounts(&meta).unwrap();
170        assert_eq!(index, 5);
171        assert_eq!(accounts, vec![[1; 20], [2; 20], [3; 20]]);
172    }
173}