Skip to main content

ledger_engine/
api.rs

1//! Ledger Engine v0 API, compatible with Clio: ledger, tx, account_tx,
2//! ledger_entry, account_info, server_info, ping; account objects and
3//! ledger_data live in the `owned` module.
4//!
5//! Responses match Clio 2.8 field for field, in API v1 and v2 (v2 by default,
6//! as in a stock Clio): the same object JSON (the `xrpl_json` module), the same
7//! transaction additions (delivered_amount, DeliverMax, ctid, synthetic
8//! NFT fields, mpt_issuance_id), the same account_tx marker, the same error codes.
9//!
10//! Data covers only validated ledgers, starting with the first one after the state snapshot:
11//! there is no "current" or "closed" here. Requests are served from the same
12//! process that writes ledgers, because only one process can open the fjall store.
13
14use std::sync::Arc;
15use std::time::Instant;
16
17use serde_json::{Map, Value, json};
18use witness_core::keys::decode_base58;
19use witness_core::ledger::LedgerHeader;
20use witness_core::sha512_half;
21
22use crate::history::HistoryReader;
23use crate::ledger::Ledger;
24use crate::state::{AccountTx, StateStore, TxPosition};
25use crate::xrpl_json::{self, definitions};
26
27/// Seconds from the Unix epoch to the XRPL epoch (2000-01-01).
28const RIPPLE_EPOCH: i64 = 946_684_800;
29const ACCOUNT_TX_LIMIT_DEFAULT: usize = 200;
30const ACCOUNT_TX_LIMIT_MAX: usize = 1000;
31/// How often the history directory is checked for new cold files.
32const COLD_RESCAN: std::time::Duration = std::time::Duration::from_secs(30);
33
34/// Response error: code, number and message, as in Clio.
35#[derive(Debug, Clone, PartialEq, Eq)]
36pub struct RpcError {
37    pub error: &'static str,
38    pub code: i32,
39    pub message: String,
40}
41
42pub(crate) fn rpc_err(error: &'static str, code: i32, message: impl Into<String>) -> RpcError {
43    RpcError {
44        error,
45        code,
46        message: message.into(),
47    }
48}
49
50pub(crate) fn invalid_params(message: &str) -> RpcError {
51    rpc_err("invalidParams", 31, message)
52}
53
54pub(crate) fn lgr_not_found() -> RpcError {
55    rpc_err("lgrNotFound", 21, "ledgerNotFound")
56}
57
58pub(crate) fn internal(e: String) -> RpcError {
59    if e == crate::limits::EXCEEDED {
60        return crate::limits::exceeded();
61    }
62    rpc_err("internal", 73, e)
63}
64
65pub(crate) type Res<T> = Result<T, RpcError>;
66
67/// Date from a number of days since 1970-01-01 (Hinnant's algorithm).
68fn civil(days: i64) -> (i64, u32, u32) {
69    let z = days + 719_468;
70    let era = z.div_euclid(146_097);
71    let doe = z - era * 146_097;
72    let yoe = (doe - doe / 1460 + doe / 36_524 - doe / 146_096) / 365;
73    let doy = doe - (365 * yoe + yoe / 4 - yoe / 100);
74    let mp = (5 * doy + 2) / 153;
75    let d = (doy - (153 * mp + 2) / 5 + 1) as u32;
76    let m = if mp < 10 { mp + 3 } else { mp - 9 } as u32;
77    (yoe + era * 400 + i64::from(m <= 2), m, d)
78}
79
80fn split_time(ripple_secs: u32) -> (i64, u32, u32, i64, i64, i64) {
81    let t = i64::from(ripple_secs) + RIPPLE_EPOCH;
82    let (y, m, d) = civil(t.div_euclid(86_400));
83    let s = t.rem_euclid(86_400);
84    (y, m, d, s / 3600, s / 60 % 60, s % 60)
85}
86
87/// Like `toStringIso` in xrpld: 2026-10-24T17:39:52Z.
88pub fn time_iso(ripple_secs: u32) -> String {
89    let (y, m, d, hh, mm, ss) = split_time(ripple_secs);
90    format!("{y:04}-{m:02}-{d:02}T{hh:02}:{mm:02}:{ss:02}Z")
91}
92
93/// Like `to_string(NetClock::time_point)`: 2026-Oct-24 17:39:52.000000000 UTC.
94pub fn time_human(ripple_secs: u32) -> String {
95    const MONTHS: [&str; 12] = [
96        "Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec",
97    ];
98    let (y, m, d, hh, mm, ss) = split_time(ripple_secs);
99    format!(
100        "{y:04}-{}-{d:02} {hh:02}:{mm:02}:{ss:02}.000000000 UTC",
101        MONTHS[(m - 1) as usize]
102    )
103}
104
105/// Object key: SHA-512Half of the namespace and fields.
106pub(crate) fn keylet(space: u8, parts: &[&[u8]]) -> [u8; 32] {
107    let mut b = vec![0, space];
108    for p in parts {
109        b.extend_from_slice(p);
110    }
111    sha512_half(&b)
112}
113
114/// Request api_version: 1 or 2, default 2, as in Clio.
115pub(crate) fn api_version(p: &Map<String, Value>) -> Res<u32> {
116    match p.get("api_version") {
117        None | Some(Value::Null) => Ok(2),
118        Some(v) => match as_u32(v) {
119            Some(a @ 1..=2) => Ok(a),
120            _ => Err(rpc_err(
121                "invalid_API_version",
122                6000,
123                "API version must be an integer between 1 and 2",
124            )),
125        },
126    }
127}
128
129/// Whether a transaction involves the MPT issuance `id` (uppercase hex MPTID),
130/// as Clio's `referencesMptIssuance`: when it succeeded, an MPToken or
131/// MPTokenIssuance it touched belongs to the issuance; in any case, a field of
132/// the transaction itself names it (MPTokenIssuanceID, an MPT amount or asset).
133fn references_mpt(tx: &Map<String, Value>, meta: &Map<String, Value>, id: &str) -> bool {
134    let is = |v: Option<&Value>| {
135        v.and_then(Value::as_str)
136            .is_some_and(|s| s.eq_ignore_ascii_case(id))
137    };
138    if meta.get("TransactionResult").and_then(Value::as_str) == Some("tesSUCCESS") {
139        let nodes = meta.get("AffectedNodes").and_then(Value::as_array);
140        for n in nodes.into_iter().flatten() {
141            let Some((kind, node)) = n.as_object().and_then(|o| o.iter().next()) else {
142                continue;
143            };
144            let fields = if kind == "CreatedNode" {
145                "NewFields"
146            } else {
147                "FinalFields"
148            };
149            let Some(f) = node.get(fields).and_then(Value::as_object) else {
150                continue;
151            };
152            match node.get("LedgerEntryType").and_then(Value::as_str) {
153                Some("MPToken") if is(f.get("MPTokenIssuanceID")) => return true,
154                Some("MPTokenIssuance") => {
155                    let seq = f.get("Sequence").and_then(Value::as_u64);
156                    let issuer = f.get("Issuer").map(account_id);
157                    if let (Some(seq), Some(Ok(issuer))) = (seq, issuer)
158                        && let Ok(seq) = u32::try_from(seq)
159                    {
160                        let mut mptid = seq.to_be_bytes().to_vec();
161                        mptid.extend_from_slice(&issuer);
162                        if hex::encode_upper(mptid) == id {
163                            return true;
164                        }
165                    }
166                }
167                _ => {}
168            }
169        }
170    }
171    tx.iter().any(|(k, v)| {
172        (k == "MPTokenIssuanceID" && is(Some(v)))
173            || v.as_object().is_some_and(|o| is(o.get("mpt_issuance_id")))
174    })
175}
176
177pub(crate) fn account_id(v: &Value) -> Res<[u8; 20]> {
178    v.as_str()
179        .and_then(decode_account)
180        .ok_or_else(|| rpc_err("actMalformed", 35, "accountMalformed"))
181}
182
183/// An account ID from its base58 address.
184pub(crate) fn decode_account(s: &str) -> Option<[u8; 20]> {
185    match decode_base58(s) {
186        Some((0, a)) => a.try_into().ok(),
187        _ => None,
188    }
189}
190
191pub(crate) fn hash256(v: &Value, what: &str) -> Res<[u8; 32]> {
192    v.as_str()
193        .and_then(|s| hex::decode(s).ok())
194        .and_then(|b| <[u8; 32]>::try_from(b).ok())
195        .ok_or_else(|| invalid_params(&format!("{what}Malformed")))
196}
197
198pub(crate) fn as_bool(v: Option<&Value>) -> bool {
199    match v {
200        Some(Value::Bool(b)) => *b,
201        Some(Value::Number(n)) => n.as_i64().is_some_and(|n| n != 0),
202        _ => false,
203    }
204}
205
206pub(crate) fn as_u32(v: &Value) -> Option<u32> {
207    match v {
208        Value::Number(n) => n.as_u64().and_then(|n| u32::try_from(n).ok()),
209        Value::String(s) => s.parse().ok(),
210        _ => None,
211    }
212}
213
214/// Reads validated ledgers, state and indexes.
215#[derive(Debug)]
216pub struct Engine {
217    pub state: Arc<StateStore>,
218    pub blocks: HistoryReader,
219    pub network_id: u32,
220    pub started: Instant,
221    /// Quorum confirmation, for evidence bundles (Proof API).
222    pub confirmer: Option<crate::confirm::Confirmer>,
223    /// Latest quorum for server_info: ledger and count.
224    pub quorum: std::sync::Mutex<(u32, usize)>,
225}
226
227/// What to do with each transaction `txs_at` reads: its position, the
228/// transaction, its metadata and the ledger's header.
229pub(crate) type TxVisit<'a> = dyn FnMut(&AccountTx, &[u8], &[u8], &LedgerHeader) -> Res<()> + 'a;
230
231/// Transaction with metadata as JSON, plus what responses need to know about it.
232pub(crate) struct Expanded {
233    pub(crate) tx: Map<String, Value>,
234    pub(crate) meta: Map<String, Value>,
235    pub(crate) index: u32,
236}
237
238impl Engine {
239    /// Range of ledgers that have history, state and quorum
240    /// confirmation: anything loaded but not yet confirmed
241    /// is not served.
242    pub fn range(&self) -> Res<(u32, u32)> {
243        // Cold history published to the directory without a restart.
244        if let Err(e) = self.blocks.refresh_cold_every(COLD_RESCAN) {
245            tracing::warn!("cold history not reread: {e}");
246        }
247        let base = self.state.base().map_err(internal)?;
248        let confirmed = self.state.confirmed().map_err(internal)?;
249        match (base, confirmed) {
250            // Cold history with indexes that reaches the snapshot extends
251            // the range downward without a gap.
252            (Some(b), Some(c)) if c > b => {
253                let cold = self.blocks.cold_index().first_contiguous_to(b);
254                Ok((cold.unwrap_or(b + 1).min(b + 1), c))
255            }
256            _ => Err(rpc_err("notReady", 13, "Not ready to handle this request.")),
257        }
258    }
259
260    /// First ledger of hot history; everything before it is cold.
261    fn hot_first(&self) -> Res<u32> {
262        Ok(self.state.base().map_err(internal)?.map_or(0, |b| b + 1))
263    }
264
265    pub(crate) fn header(&self, seq: u32) -> Res<(Vec<u8>, LedgerHeader)> {
266        let raw = match self.state.header(seq).map_err(internal)? {
267            Some(r) => r,
268            // Before the snapshot: header from cold history, read alone; a
269            // ledger kept in hot history files falls back to its frame.
270            None if seq < self.hot_first()? => {
271                match self.blocks.cold_header(seq).map_err(internal)? {
272                    Some(h) => h,
273                    None => {
274                        self.blocks
275                            .get_txs(seq)
276                            .map_err(internal)?
277                            .ok_or_else(lgr_not_found)?
278                            .header
279                    }
280                }
281            }
282            None => return Err(lgr_not_found()),
283        };
284        let h = LedgerHeader::parse(&raw).map_err(|e| internal(e.to_string()))?;
285        Ok((raw, h))
286    }
287
288    pub(crate) fn ledger(&self, seq: u32) -> Res<Ledger> {
289        // Responses need only the header and transactions: the transaction frame
290        // is read without the state changes. If it isn't in history, it is still
291        // pending; between the two checks the ledger can move from pending to
292        // history, hence the second look at history.
293        if let Some(l) = self.blocks.get_txs_known(seq).map_err(internal)? {
294            return Ok(l);
295        }
296        match self.state.pending_ledger(seq).map_err(internal)? {
297            Some(b) => Ledger::decode(&b).map_err(internal),
298            None => {
299                // Outside the range, rereading the directory is pointless: such a request
300                // (a ctid for some other ledger) would otherwise cost two full scans.
301                let (lo, hi) = self.range()?;
302                if seq < lo || seq > hi {
303                    return Err(lgr_not_found());
304                }
305                self.blocks.refresh().map_err(internal)?;
306                self.blocks
307                    .get_txs(seq)
308                    .map_err(internal)?
309                    .ok_or_else(lgr_not_found)
310            }
311        }
312    }
313
314    pub(crate) fn resolve_ledger(&self, p: &Map<String, Value>) -> Res<u32> {
315        self.resolve(p)
316    }
317
318    pub(crate) fn ledger_txs(&self, seq: u32) -> Res<Ledger> {
319        self.ledger(seq)
320    }
321
322    pub(crate) fn entry_key_of(&self, p: &Map<String, Value>) -> Res<[u8; 32]> {
323        Ok(crate::selector::entry_key(p)?.0)
324    }
325
326    /// The requested ledger: ledger_hash, ledger_index, or the latest validated one.
327    pub(crate) fn resolve(&self, p: &Map<String, Value>) -> Res<u32> {
328        let (min, max) = self.range()?;
329        let by_hash = match p.get("ledger_hash") {
330            Some(v) if !v.is_null() => {
331                let h = hash256(v, "ledgerHash")?;
332                let hot = self.state.ledger_by_hash(&h).map_err(internal)?;
333                let seq = match hot {
334                    Some(s) => Some(s),
335                    None => self
336                        .blocks
337                        .cold_index()
338                        .ledger_by_hash(&h)
339                        .map_err(internal)?,
340                };
341                Some(seq.ok_or_else(lgr_not_found)?)
342            }
343            _ => None,
344        };
345        let by_index = match p.get("ledger_index") {
346            None | Some(Value::Null) => None,
347            Some(Value::String(s)) if s == "validated" => None,
348            Some(v) => Some(as_u32(v).ok_or_else(|| invalid_params("ledgerIndexMalformed"))?),
349        };
350        let seq = match (by_hash, by_index) {
351            (Some(h), Some(i)) if h != i => return Err(lgr_not_found()),
352            (Some(h), _) => h,
353            (None, Some(i)) => i,
354            (None, None) => max,
355        };
356        if seq < min || seq > max {
357            return Err(lgr_not_found());
358        }
359        Ok(seq)
360    }
361
362    /// Like `resolve`, for state methods: state exists only from the snapshot on,
363    /// and below it there is only transaction history. There the ledger is reported
364    /// as missing, as on a server without that ledger, not as an internal error.
365    pub(crate) fn resolve_state(&self, p: &Map<String, Value>) -> Res<u32> {
366        let seq = self.resolve(p)?;
367        match self.state.base().map_err(internal)? {
368            Some(b) if seq >= b => Ok(seq),
369            _ => Err(lgr_not_found()),
370        }
371    }
372
373    /// Like `resolve_state`, but below the snapshot it also accepts ledgers the
374    /// attached old state (the version index over cold history) answers for.
375    /// Only methods that read objects by key use it: account_info, ledger_entry,
376    /// account_lines and account_objects. The rest keep `resolve_state`.
377    pub(crate) fn resolve_old_state(&self, p: &Map<String, Value>) -> Res<u32> {
378        let seq = self.resolve(p)?;
379        if self
380            .state
381            .base()
382            .map_err(internal)?
383            .is_some_and(|b| seq >= b)
384        {
385            return Ok(seq);
386        }
387        match self.state.old_range() {
388            Some((lo, hi)) if seq >= lo && seq <= hi => Ok(seq),
389            _ => Err(lgr_not_found()),
390        }
391    }
392
393    pub(crate) fn header_json(
394        &self,
395        raw: &[u8],
396        h: &LedgerHeader,
397        binary: bool,
398        api: u32,
399    ) -> Map<String, Value> {
400        let mut m = Map::new();
401        if binary {
402            m.insert("ledger_data".into(), json!(hex::encode_upper(raw)));
403        } else {
404            m.insert(
405                "account_hash".into(),
406                json!(hex::encode_upper(h.account_hash)),
407            );
408            m.insert("close_flags".into(), json!(h.close_flags));
409            m.insert("close_time".into(), json!(h.close_time));
410            m.insert("close_time_human".into(), json!(time_human(h.close_time)));
411            m.insert(
412                "close_time_resolution".into(),
413                json!(h.close_time_resolution),
414            );
415            m.insert("close_time_iso".into(), json!(time_iso(h.close_time)));
416            m.insert("ledger_hash".into(), json!(hex::encode_upper(h.hash())));
417            m.insert("parent_close_time".into(), json!(h.parent_close_time));
418            m.insert(
419                "parent_hash".into(),
420                json!(hex::encode_upper(h.parent_hash)),
421            );
422            m.insert("total_coins".into(), json!(h.total_drops.to_string()));
423            m.insert(
424                "transaction_hash".into(),
425                json!(hex::encode_upper(h.transaction_hash)),
426            );
427            m.insert(
428                "ledger_index".into(),
429                if api < 2 {
430                    json!(h.sequence.to_string())
431                } else {
432                    json!(h.sequence)
433                },
434            );
435        }
436        m.insert("closed".into(), json!(true));
437        m
438    }
439
440    /// Like `toExpandedJson` in Clio.
441    /// `nft` adds synthetic NFT fields: Clio adds them in tx and account_tx,
442    /// but not in ledger.
443    pub(crate) fn expand(
444        &self,
445        tx: &[u8],
446        meta: &[u8],
447        seq: u32,
448        api: u32,
449        ctid: bool,
450        nft: bool,
451    ) -> Res<Expanded> {
452        let mut t = xrpl_json::transaction(tx).map_err(internal)?;
453        let mut m = xrpl_json::metadata(meta).map_err(internal)?;
454        let index = m
455            .get("TransactionIndex")
456            .and_then(Value::as_u64)
457            .and_then(|i| u32::try_from(i).ok())
458            .unwrap_or(0);
459        let tt = t
460            .get("TransactionType")
461            .and_then(Value::as_str)
462            .unwrap_or("")
463            .to_owned();
464        let success = m.get("TransactionResult").and_then(Value::as_str) == Some("tesSUCCESS");
465
466        if success && matches!(tt.as_str(), "Payment" | "CheckCash" | "AccountDelete") {
467            let delivered = m
468                .get("DeliveredAmount")
469                .or_else(|| t.get("Amount"))
470                .cloned()
471                .unwrap_or_else(|| json!("unavailable"));
472            m.insert("delivered_amount".into(), delivered);
473        }
474        if tt == "Payment"
475            && let Some(a) = t.get("Amount").cloned()
476        {
477            t.insert("DeliverMax".into(), a);
478            if api > 1 {
479                t.remove("Amount");
480            }
481        }
482        if success
483            && tt == "MPTokenIssuanceCreate"
484            && let Some(id) = created_mpt_issuance(&m)
485        {
486            m.insert("mpt_issuance_id".into(), json!(id));
487        }
488        if success && nft {
489            nft_synthetic(&tt, &t, &mut m);
490        }
491        if ctid && let Some(c) = self.ctid(seq, index) {
492            t.insert("ctid".into(), json!(c));
493        }
494        Ok(Expanded {
495            tx: t,
496            meta: m,
497            index,
498        })
499    }
500
501    pub(crate) fn ctid(&self, seq: u32, index: u32) -> Option<String> {
502        if seq > 0x0FFF_FFFF || index > 0xFFFF || self.network_id > 0xFFFF {
503            return None;
504        }
505        let v = ((0xC000_0000u64 + u64::from(seq)) << 32)
506            + (u64::from(index) << 16)
507            + u64::from(self.network_id);
508        Some(format!("{v:016X}"))
509    }
510
511    pub fn handle(&self, method: &str, p: &Map<String, Value>) -> Res<Map<String, Value>> {
512        let api = api_version(p)?;
513        match method {
514            "ping" => Ok(Map::new()),
515            "server_info" => self.server_info(),
516            "ledger" => self.ledger_rpc(p, api),
517            "tx" => self.tx(p, api),
518            "account_tx" => self.account_tx(p, api),
519            "ledger_entry" => self.ledger_entry(p),
520            "account_info" => self.account_info(p, api),
521            "account_objects" => self.account_objects(p),
522            "account_lines" => self.account_lines(p),
523            "account_offers" => self.account_offers(p),
524            "mpt_holders" => self.mpt_holders(p),
525            "account_mptoken_issuances" => self.account_mptoken_issuances(p),
526            "account_mptokens" => self.account_mptokens(p),
527            "vault_info" => self.vault_info(p),
528            "feature" => self.feature(p),
529            "account_nfts" => self.account_nfts(p),
530            "nft_buy_offers" => self.nft_buy_offers(p),
531            "nft_sell_offers" => self.nft_sell_offers(p),
532            "nft_info" => self.nft_info(p),
533            "nft_history" => self.nft_history(p, api),
534            "nfts_by_issuer" => self.nfts_by_issuer(p),
535            "ledger_data" => self.ledger_data(p, api),
536            "book_changes" => self.book_changes(p),
537            "proof_ledger" => self.proof_ledger(p),
538            "proof_tx" => self.proof_tx(p),
539            "proof_entry" => self.proof_entry(p),
540            _ => Err(rpc_err("unknownCmd", 32, "Unknown method.")),
541        }
542    }
543
544    /// The last ledger served and how many seconds ago it closed.
545    pub fn last_ledger_age(&self) -> Res<(u32, i64)> {
546        let (_, max) = self.range()?;
547        let (_, h) = self.header(max)?;
548        let now = std::time::SystemTime::now()
549            .duration_since(std::time::UNIX_EPOCH)
550            .map(|d| d.as_secs() as i64)
551            .unwrap_or(0);
552        Ok((max, (now - RIPPLE_EPOCH - i64::from(h.close_time)).max(0)))
553    }
554
555    fn server_info(&self) -> Res<Map<String, Value>> {
556        let (min, max) = self.range()?;
557        let (_, h) = self.header(max)?;
558        let now = std::time::SystemTime::now()
559            .duration_since(std::time::UNIX_EPOCH)
560            .map(|d| d.as_secs() as i64)
561            .unwrap_or(0);
562        let age = (now - RIPPLE_EPOCH - i64::from(h.close_time)).max(0);
563        let micros = std::time::SystemTime::now()
564            .duration_since(std::time::UNIX_EPOCH)
565            .map(|d| d.subsec_micros())
566            .unwrap_or(0);
567        let mut validated = json!({
568            "age": age,
569            "hash": hex::encode_upper(h.hash()),
570            "seq": max,
571        });
572        // Fees and reserves come from the FeeSettings object.
573        if let Some((base, reserve, inc)) = self.fee_drops(max)? {
574            validated["base_fee_xrp"] = json!(base as f64 / 1e6);
575            validated["reserve_base_xrp"] = json!(reserve as f64 / 1e6);
576            validated["reserve_inc_xrp"] = json!(inc as f64 / 1e6);
577        }
578        let mut info = json!({
579            "complete_ledgers": format!("{min}-{max}"),
580            "load_factor": 1,
581            "astraea_version": env!("CARGO_PKG_VERSION"),
582            "network_id": self.network_id,
583            "uptime": self.started.elapsed().as_secs(),
584            "time": time_human((now - RIPPLE_EPOCH).max(0) as u32)
585                .replace(".000000000", &format!(".{micros:06}")),
586            "validated_ledger": validated,
587            // Our own: what is loaded and how much of it is confirmed by quorum.
588            "astraea": {
589                "loaded_ledger": self.state.last().map_err(internal)?,
590                "confirmed_ledger": max,
591                "confirmation_rule": "full-unl",
592                "state_root_checked": true,
593            },
594        });
595        if let Some(q) = self.quorum_at(max, &h.hash()) {
596            info["validation_quorum"] = json!(q);
597        }
598        // State before the snapshot, when a version index over cold history is attached.
599        if let Some((lo, hi)) = self.state.old_range() {
600            info["astraea"]["old_state_ledgers"] = json!(format!("{lo}-{hi}"));
601        }
602        let mut m = Map::new();
603        m.insert("info".into(), info);
604        m.insert("validated".into(), json!(true));
605        Ok(m)
606    }
607
608    /// Fee and reserves for the ledger from FeeSettings, in drops: base
609    /// fee, account reserve, owner reserve. Fields after XRPFees are
610    /// BaseFeeDrops and the rest; before it, BaseFee (hex) and ReserveBase/Increment.
611    pub(crate) fn fee_drops(&self, seq: u32) -> Res<Option<(u64, u64, u64)>> {
612        let Some(fees) = self.state.get(&keylet(b'e', &[]), seq).map_err(internal)? else {
613            return Ok(None);
614        };
615        let Ok(Value::Object(f)) = xrpl_json::object(definitions(), &fees) else {
616            return Ok(None);
617        };
618        let drops = |k: &str, old: &str| {
619            f.get(k)
620                .and_then(|v| v.as_str().and_then(|s| s.parse::<u64>().ok()))
621                .or_else(|| f.get(old).and_then(Value::as_u64))
622                .or_else(|| {
623                    f.get(old)
624                        .and_then(|v| v.as_str())
625                        .and_then(|s| u64::from_str_radix(s, 16).ok())
626                })
627        };
628        Ok(
629            match (
630                drops("BaseFeeDrops", "BaseFee"),
631                drops("ReserveBaseDrops", "ReserveBase"),
632                drops("ReserveIncrementDrops", "ReserveIncrement"),
633            ) {
634                (Some(b), Some(r), Some(i)) => Some((b, r, i)),
635                _ => None,
636            },
637        )
638    }
639
640    /// UNL quorum per ledger: server_info is requested often, and deciding from
641    /// validations isn't cheap, so it's done once per ledger.
642    fn quorum_at(&self, seq: u32, hash: &[u8; 32]) -> Option<usize> {
643        let c = self.confirmer.as_ref()?;
644        let mut g = self.quorum.lock().unwrap_or_else(|p| p.into_inner());
645        if g.0 != seq {
646            *g = (seq, c.check(seq, hash).quorum);
647        }
648        (g.1 > 0).then_some(g.1)
649    }
650
651    fn ledger_rpc(&self, p: &Map<String, Value>, api: u32) -> Res<Map<String, Value>> {
652        let seq = self.resolve(p)?;
653        let (raw, h) = self.header(seq)?;
654        let binary = as_bool(p.get("binary"));
655        let mut header = self.header_json(&raw, &h, binary, api);
656        if as_bool(p.get("transactions")) {
657            let l = self.ledger(seq)?;
658            // Clio returns a ledger's transactions in hash order.
659            let mut txs: Vec<(String, &[u8], &[u8])> = l
660                .transactions
661                .iter()
662                .map(|(t, m)| {
663                    (
664                        hex::encode_upper(witness_core::shamap::tx_id(t)),
665                        &t[..],
666                        &m[..],
667                    )
668                })
669                .collect();
670            txs.sort_by(|a, b| a.0.cmp(&b.0));
671            let mut out = Vec::with_capacity(txs.len());
672            for (hash, tx, meta) in txs {
673                crate::limits::check_rpc()?;
674                if !as_bool(p.get("expand")) {
675                    out.push(json!(hash));
676                    continue;
677                }
678                let e = self.expand(tx, meta, seq, api, false, false)?;
679                let mut entry = Map::new();
680                if api < 2 {
681                    if binary {
682                        entry.insert("meta".into(), json!(hex::encode_upper(meta)));
683                        entry.insert("tx_blob".into(), json!(hex::encode_upper(tx)));
684                    } else {
685                        entry = e.tx;
686                        entry.insert("metaData".into(), Value::Object(e.meta));
687                    }
688                } else if binary {
689                    entry.insert("meta_blob".into(), json!(hex::encode_upper(meta)));
690                    entry.insert("tx_blob".into(), json!(hex::encode_upper(tx)));
691                    entry.insert("hash".into(), json!(hash));
692                } else {
693                    let mut t = e.tx;
694                    t.remove("hash");
695                    entry.insert("validated".into(), json!(true));
696                    entry.insert("ledger_index".into(), json!(seq));
697                    entry.insert("close_time_iso".into(), json!(time_iso(h.close_time)));
698                    entry.insert("ledger_hash".into(), json!(hex::encode_upper(h.hash())));
699                    entry.insert("hash".into(), json!(hash));
700                    entry.insert("tx_json".into(), Value::Object(t));
701                    entry.insert("meta".into(), Value::Object(e.meta));
702                }
703                out.push(Value::Object(entry));
704            }
705            header.insert("transactions".into(), Value::Array(out));
706        }
707        let mut m = Map::new();
708        m.insert("ledger_hash".into(), json!(hex::encode_upper(h.hash())));
709        m.insert("ledger_index".into(), json!(seq));
710        m.insert("validated".into(), json!(true));
711        m.insert("ledger".into(), Value::Object(header));
712        Ok(m)
713    }
714
715    fn book_changes(&self, p: &Map<String, Value>) -> Res<Map<String, Value>> {
716        let seq = self.resolve(p)?;
717        let (_, h) = self.header(seq)?;
718        let l = self.ledger(seq)?;
719        let mut m = Map::new();
720        m.insert("type".into(), json!("bookChanges"));
721        m.insert("ledger_hash".into(), json!(hex::encode_upper(h.hash())));
722        m.insert("ledger_index".into(), json!(seq));
723        m.insert("ledger_time".into(), json!(h.close_time));
724        m.insert("validated".into(), json!(true));
725        m.insert(
726            "changes".into(),
727            Value::Array(crate::bookchanges::compute(&l.transactions)),
728        );
729        Ok(m)
730    }
731
732    fn tx(&self, p: &Map<String, Value>, api: u32) -> Res<Map<String, Value>> {
733        let (seq, pos) = match (p.get("transaction"), p.get("ctid")) {
734            (Some(_), Some(_)) | (None, None) => return Err(invalid_params("Invalid parameters.")),
735            (Some(t), None) => {
736                // Clio's errors for a hash that is not one.
737                let id = t
738                    .as_str()
739                    .ok_or_else(|| invalid_params("transactionNotString"))?;
740                let id = hex::decode(id)
741                    .ok()
742                    .and_then(|b| <[u8; 32]>::try_from(b).ok())
743                    .ok_or_else(|| invalid_params("transactionMalformed"))?;
744                match self.state.tx_location(&id).map_err(internal)? {
745                    Some(at) => at,
746                    None => self
747                        .cold_tx(&id)?
748                        .ok_or_else(|| rpc_err("txnNotFound", 29, "Transaction not found."))?,
749                }
750            }
751            (None, Some(c)) => {
752                let v = c
753                    .as_str()
754                    .and_then(|s| u64::from_str_radix(s, 16).ok())
755                    .filter(|v| v >> 60 == 0xC)
756                    .ok_or_else(|| invalid_params("Invalid parameters."))?;
757                let seq = ((v >> 32) & 0x0FFF_FFFF) as u32;
758                let index = ((v >> 16) & 0xFFFF) as u32;
759                let net = (v & 0xFFFF) as u32;
760                if net != self.network_id {
761                    return Err(rpc_err(
762                        "wrongNetwork",
763                        4,
764                        format!(
765                            "Wrong network. You should submit this request to a node running on NetworkID: {net}"
766                        ),
767                    ));
768                }
769                // A request out of time is not a missing transaction.
770                let l = self.ledger(seq).map_err(|e| {
771                    if e.error == "tooBusy" {
772                        e
773                    } else {
774                        rpc_err("txnNotFound", 29, "Transaction not found.")
775                    }
776                })?;
777                let pos = l
778                    .transactions
779                    .iter()
780                    .position(|(_, m)| {
781                        xrpl_json::metadata(m)
782                            .ok()
783                            .and_then(|m| m.get("TransactionIndex").and_then(Value::as_u64))
784                            == Some(u64::from(index))
785                    })
786                    .ok_or_else(|| rpc_err("txnNotFound", 29, "Transaction not found."))?;
787                (seq, pos as u32)
788            }
789        };
790        let (min, max) = self.range()?;
791        if seq < min || seq > max {
792            return Err(rpc_err("txnNotFound", 29, "Transaction not found."));
793        }
794        let l = self.ledger(seq)?;
795        let (tx, meta) = l
796            .transactions
797            .get(pos as usize)
798            .ok_or_else(|| internal("no transaction at this position".into()))?;
799        let (_, h) = self.header(seq)?;
800        let e = self.expand(tx, meta, seq, api, true, true)?;
801        let ctid = self.ctid(seq, e.index);
802        let hash = e.tx.get("hash").cloned().unwrap_or(Value::Null);
803        let binary = as_bool(p.get("binary"));
804        let mut m = Map::new();
805        if api < 2 {
806            if binary {
807                m.insert("meta".into(), json!(hex::encode_upper(meta)));
808                m.insert("tx".into(), json!(hex::encode_upper(tx)));
809                m.insert("hash".into(), hash);
810            } else {
811                m = e.tx;
812                m.insert("meta".into(), Value::Object(e.meta));
813            }
814            m.insert("validated".into(), json!(true));
815            m.insert("date".into(), json!(h.close_time));
816            m.insert("ledger_index".into(), json!(seq));
817            m.insert("inLedger".into(), json!(seq));
818        } else {
819            if binary {
820                m.insert("meta_blob".into(), json!(hex::encode_upper(meta)));
821                m.insert("tx_blob".into(), json!(hex::encode_upper(tx)));
822                m.insert("hash".into(), hash);
823            } else {
824                let mut t = e.tx;
825                t.insert("date".into(), json!(h.close_time));
826                if let Some(c) = &ctid {
827                    t.insert("ctid".into(), json!(c));
828                }
829                t.insert("ledger_index".into(), json!(seq));
830                if let Some(hv) = t.remove("hash") {
831                    m.insert("hash".into(), hv);
832                }
833                m.insert("tx_json".into(), Value::Object(t));
834                m.insert("meta".into(), Value::Object(e.meta));
835            }
836            m.insert("validated".into(), json!(true));
837            m.insert("ledger_index".into(), json!(seq));
838            m.insert("ledger_hash".into(), json!(hex::encode_upper(h.hash())));
839            m.insert("close_time_iso".into(), json!(time_iso(h.close_time)));
840        }
841        if let Some(c) = ctid {
842            m.insert("ctid".into(), json!(c));
843        }
844        Ok(m)
845    }
846
847    /// Transaction by hash in cold history: XTXH candidates are checked by
848    /// recomputing the hash.
849    pub(crate) fn cold_tx(&self, id: &[u8; 32]) -> Res<Option<(u32, u32)>> {
850        for (seq, pos) in self
851            .blocks
852            .cold_index()
853            .tx_candidates(id)
854            .map_err(internal)?
855        {
856            if let Some(l) = self.blocks.get_txs(seq).map_err(internal)?
857                && l.transactions
858                    .get(pos as usize)
859                    .is_some_and(|(t, _)| witness_core::shamap::tx_id(t) == *id)
860            {
861                return Ok(Some((seq, pos)));
862            }
863        }
864        Ok(None)
865    }
866
867    /// Account history positions in [min, max] starting from `start` (inclusive):
868    /// the hot part uses fjall indexes, deeper ones use cold indexes, and a page
869    /// continues across the boundary. Cold entries have u32::MAX as the position in the ledger.
870    fn account_positions(
871        &self,
872        account: &[u8; 20],
873        min: u32,
874        max: u32,
875        forward: bool,
876        take: usize,
877        start: Option<TxPosition>,
878    ) -> Res<Vec<AccountTx>> {
879        let hot_first = self.hot_first()?;
880        let cold_max = hot_first.checked_sub(1);
881        let mut out = Vec::new();
882        let cold = |lo: TxPosition, hi: TxPosition, n: usize| -> Res<Vec<AccountTx>> {
883            Ok(self
884                .blocks
885                .cold_index()
886                .account_tx(account, lo, hi, forward, n)
887                .map_err(internal)?
888                .into_iter()
889                .map(|at| AccountTx { at, pos: u32::MAX })
890                .collect())
891        };
892        let hot = |n: usize, s: Option<TxPosition>| -> Res<Vec<AccountTx>> {
893            Ok(self
894                .state
895                .account_tx(account, min.max(hot_first), max, forward, n, s)
896                .map_err(internal)?
897                .transactions)
898        };
899        let lowest = TxPosition {
900            ledger: min,
901            index: 0,
902        };
903        let cold_top = cold_max.map(|c| TxPosition {
904            ledger: max.min(c),
905            index: u32::MAX,
906        });
907        if forward {
908            if let Some(top) = cold_top
909                && min <= top.ledger
910                && start.is_none_or(|s| s <= top)
911            {
912                out.extend(cold(start.unwrap_or(lowest).max(lowest), top, take)?);
913            }
914            if out.len() < take && max >= hot_first {
915                out.extend(hot(
916                    take - out.len(),
917                    start.filter(|s| s.ledger >= hot_first),
918                )?);
919            }
920        } else {
921            if max >= hot_first && start.is_none_or(|s| s.ledger >= hot_first) {
922                out.extend(hot(take, start)?);
923            }
924            if out.len() < take
925                && let Some(top) = cold_top
926                && min <= top.ledger
927            {
928                let hi = start.filter(|s| *s <= top).unwrap_or(top);
929                out.extend(cold(lowest, hi, take - out.len())?);
930            }
931        }
932        Ok(out)
933    }
934
935    fn account_tx(&self, p: &Map<String, Value>, api: u32) -> Res<Map<String, Value>> {
936        let account = account_id(
937            p.get("account")
938                .ok_or_else(|| invalid_params("Required field 'account' missing"))?,
939        )?;
940        let (range_min, range_max) = self.range()?;
941        let (mut min, mut max) = (range_min, range_max);
942        let bound = |k: &str| -> Res<Option<u32>> {
943            match p.get(k) {
944                None | Some(Value::Null) => Ok(None),
945                Some(v) => match v.as_i64() {
946                    Some(-1) => Ok(None),
947                    Some(n) => u32::try_from(n)
948                        .map(Some)
949                        .map_err(|_| invalid_params("Invalid parameters.")),
950                    None => Err(invalid_params("Invalid parameters.")),
951                },
952            }
953        };
954        let (lo, hi) = (bound("ledger_index_min")?, bound("ledger_index_max")?);
955        if let Some(lo) = lo {
956            if api > 1 && (lo > range_max || lo < range_min) {
957                return Err(rpc_err("lgrIdxMalformed", 58, "ledgerSeqMinOutOfRange"));
958            }
959            min = min.max(lo);
960        }
961        if let Some(hi) = hi {
962            if api > 1 && (hi > range_max || hi < range_min) {
963                return Err(rpc_err("lgrIdxMalformed", 58, "ledgerSeqMaxOutOfRange"));
964            }
965            max = max.min(hi);
966        }
967        if min > max {
968            return Err(if api == 1 {
969                rpc_err("lgrIdxsInvalid", 57, "Ledger indexes invalid.")
970            } else {
971                rpc_err("invalidLgrRange", 79, "Ledger range is invalid.")
972            });
973        }
974        if p.contains_key("ledger_hash") || p.contains_key("ledger_index") {
975            if api > 1 && (lo.is_some() || hi.is_some()) {
976                return Err(invalid_params("containsLedgerSpecifierAndRange"));
977            }
978            if lo.is_none() && hi.is_none() {
979                let seq = self.resolve(p)?;
980                (min, max) = (seq, seq);
981            }
982        }
983        let forward = as_bool(p.get("forward"));
984        let limit = match p.get("limit") {
985            None | Some(Value::Null) => None,
986            Some(v) => Some(
987                v.as_u64()
988                    .filter(|n| *n >= 1)
989                    .ok_or_else(|| invalid_params("Invalid parameters."))? as usize,
990            ),
991        };
992        let take = limit
993            .unwrap_or(ACCOUNT_TX_LIMIT_DEFAULT)
994            .clamp(1, ACCOUNT_TX_LIMIT_MAX);
995        // Clio's marker is the position of the last returned transaction: the next
996        // page starts strictly after it.
997        let after = match p.get("marker") {
998            None | Some(Value::Null) => None,
999            Some(Value::Object(mk)) => {
1000                let ledger = mk
1001                    .get("ledger")
1002                    .and_then(as_u32)
1003                    .ok_or_else(|| invalid_params("Invalid parameters."))?;
1004                let seq = mk
1005                    .get("seq")
1006                    .and_then(as_u32)
1007                    .ok_or_else(|| invalid_params("Invalid parameters."))?;
1008                Some(TxPosition { ledger, index: seq })
1009            }
1010            Some(_) => return Err(invalid_params("Invalid parameters.")),
1011        };
1012        if let Some(a) = after {
1013            marker_in_range(a, range_max)?;
1014        }
1015        // The next position after marker. There may be none if marker is right at
1016        // the edge: then the page is empty rather than starting over.
1017        let start = after.map(|a| after_marker(a, forward));
1018        let page = match start {
1019            Some(None) => crate::state::AccountTxPage {
1020                transactions: Vec::new(),
1021                marker: None,
1022            },
1023            start => crate::state::AccountTxPage {
1024                transactions: self.account_positions(
1025                    &account,
1026                    min,
1027                    max,
1028                    forward,
1029                    take,
1030                    start.flatten(),
1031                )?,
1032                marker: None,
1033            },
1034        };
1035        let binary = as_bool(p.get("binary"));
1036        // As in Clio, tx_type and mpt_issuance_id filter the page after it is
1037        // read: a page can come back shorter than limit, with a marker.
1038        let tx_type = match p.get("tx_type") {
1039            None => None,
1040            Some(Value::String(s)) if definitions().is_transaction_type(s) => {
1041                Some(s.to_ascii_lowercase())
1042            }
1043            Some(Value::String(_)) => return Err(invalid_params("Invalid field 'tx_type'.")),
1044            Some(_) => return Err(invalid_params("Invalid field 'tx_type', not string.")),
1045        };
1046        let mpt = match p.get("mpt_issuance_id") {
1047            None => None,
1048            Some(Value::String(s)) => Some(
1049                hex::decode(s)
1050                    .ok()
1051                    .filter(|b| b.len() == 24)
1052                    .map(hex::encode_upper)
1053                    .ok_or_else(|| invalid_params("mpt_issuance_idMalformed"))?,
1054            ),
1055            Some(_) => return Err(invalid_params("mpt_issuance_idNotString")),
1056        };
1057        let mut out = Vec::with_capacity(page.transactions.len());
1058        self.txs_at(&page.transactions, &mut |t, tx, meta, h| {
1059            if tx_type.is_some() || mpt.is_some() {
1060                let tj = xrpl_json::transaction(tx).map_err(internal)?;
1061                if let Some(want) = &tx_type {
1062                    let tt = tj.get("TransactionType").and_then(Value::as_str);
1063                    if tt.is_some_and(|tt| !tt.eq_ignore_ascii_case(want)) {
1064                        return Ok(());
1065                    }
1066                }
1067                if let Some(id) = &mpt {
1068                    let mj = xrpl_json::metadata(meta).map_err(internal)?;
1069                    if !references_mpt(&tj, &mj, id) {
1070                        return Ok(());
1071                    }
1072                }
1073            }
1074            let mut obj = Map::new();
1075            if binary {
1076                obj.insert(
1077                    if api > 1 { "meta_blob" } else { "meta" }.into(),
1078                    json!(hex::encode_upper(meta)),
1079                );
1080                obj.insert("tx_blob".into(), json!(hex::encode_upper(tx)));
1081                obj.insert("validated".into(), json!(true));
1082                obj.insert("ledger_index".into(), json!(t.at.ledger));
1083                out.push(Value::Object(obj));
1084                return Ok(());
1085            }
1086            let e = self.expand(tx, meta, t.at.ledger, api, false, true)?;
1087            let mut tj = e.tx;
1088            if let Some(c) = self.ctid(t.at.ledger, e.index) {
1089                tj.insert("ctid".into(), json!(c));
1090            }
1091            tj.insert("date".into(), json!(h.close_time));
1092            tj.insert("ledger_index".into(), json!(t.at.ledger));
1093            if api < 2 {
1094                tj.insert("inLedger".into(), json!(t.at.ledger));
1095            } else {
1096                obj.insert("ledger_index".into(), json!(t.at.ledger));
1097                if let Some(hv) = tj.remove("hash") {
1098                    obj.insert("hash".into(), hv);
1099                }
1100                obj.insert("ledger_hash".into(), json!(hex::encode_upper(h.hash())));
1101                obj.insert("close_time_iso".into(), json!(time_iso(h.close_time)));
1102            }
1103            obj.insert("meta".into(), Value::Object(e.meta));
1104            obj.insert(
1105                if api < 2 { "tx" } else { "tx_json" }.into(),
1106                Value::Object(tj),
1107            );
1108            obj.insert("validated".into(), json!(true));
1109            out.push(Value::Object(obj));
1110            Ok(())
1111        })?;
1112        let mut m = Map::new();
1113        m.insert("account".into(), json!(xrpl_json::account(&account)));
1114        m.insert("ledger_index_min".into(), json!(min));
1115        m.insert("ledger_index_max".into(), json!(max));
1116        // Full page: marker points to the last returned one, as in Clio.
1117        if page.transactions.len() == take
1118            && let Some(last) = page.transactions.last()
1119        {
1120            m.insert(
1121                "marker".into(),
1122                json!({ "ledger": last.at.ledger, "seq": last.at.index }),
1123            );
1124        }
1125        m.insert("transactions".into(), Value::Array(out));
1126        m.insert("validated".into(), json!(true));
1127        if let Some(l) = limit {
1128            m.insert("limit".into(), json!(l.clamp(1, ACCOUNT_TX_LIMIT_MAX)));
1129        }
1130        Ok(m)
1131    }
1132
1133    /// The transactions at these positions, in order, each with its
1134    /// ledger's header. Cold ones are read up front, block by block in
1135    /// parallel, and only those: a ledger's other transactions are not decoded.
1136    /// A transaction is found by TransactionIndex; the stored position is a
1137    /// hint, and cold history doesn't know it.
1138    pub(crate) fn txs_at(&self, list: &[AccountTx], each: &mut TxVisit<'_>) -> Res<()> {
1139        let hot_first = self.hot_first()?;
1140        let wants: Vec<(u32, u32)> = list
1141            .iter()
1142            .filter(|t| t.at.ledger < hot_first)
1143            .map(|t| (t.at.ledger, t.at.index))
1144            .collect();
1145        let mut cold = self.blocks.cold_transactions(&wants).map_err(internal)?;
1146        let mut cache: Option<(u32, Ledger, LedgerHeader)> = None;
1147        for t in list {
1148            crate::limits::check_rpc()?;
1149            if cache.as_ref().is_none_or(|(s, _, _)| *s != t.at.ledger) {
1150                let l = match cold.remove(&t.at.ledger) {
1151                    Some(l) => l,
1152                    None => self.ledger(t.at.ledger)?,
1153                };
1154                let h = LedgerHeader::parse(&l.header).map_err(|e| internal(e.to_string()))?;
1155                cache = Some((t.at.ledger, l, h));
1156            }
1157            let Some((_, l, h)) = &cache else { continue };
1158            let is = |(_, m): &&(Vec<u8>, Vec<u8>)| tx_index_of(m) == Some(t.at.index);
1159            let (tx, meta) =
1160                match l.transactions.get(t.pos as usize).filter(is) {
1161                    Some(x) => x,
1162                    None => l.transactions.iter().find(is).ok_or_else(|| {
1163                        internal("no transaction with this TransactionIndex".into())
1164                    })?,
1165                };
1166            each(t, tx, meta, h)?;
1167        }
1168        Ok(())
1169    }
1170
1171    fn ledger_entry(&self, p: &Map<String, Value>) -> Res<Map<String, Value>> {
1172        let (key, expected) = crate::selector::entry_key(p)?;
1173        let seq = self.resolve_old_state(p)?;
1174        let (_, h) = self.header(seq)?;
1175        let not_found = || rpc_err("entryNotFound", 98, "Entry not found.");
1176        // include_deleted, as in Clio: a deleted object as it was in the
1177        // ledger before the one that deleted it.
1178        let version = self.state.version(&key, seq).map_err(internal)?;
1179        // The ledger before the deleting one must have state, hot or old.
1180        let before_readable = match &version {
1181            Some((at, _)) if *at > 0 => self.state.serves(at - 1).map_err(internal)?,
1182            _ => false,
1183        };
1184        let (data, deleted) = match version {
1185            Some((_, v)) if !v.is_empty() => (v, None),
1186            Some((at, _)) if as_bool(p.get("include_deleted")) && before_readable => {
1187                let v = self
1188                    .state
1189                    .get(&key, at - 1)
1190                    .map_err(internal)?
1191                    .ok_or_else(not_found)?;
1192                (v, Some(at))
1193            }
1194            _ => return Err(not_found()),
1195        };
1196        let mut node = xrpl_json::ledger_entry(&key, &data).map_err(internal)?;
1197        if let Some(t) = expected
1198            && node.get("LedgerEntryType").and_then(Value::as_str) != Some(t)
1199        {
1200            return Err(rpc_err(
1201                "unexpectedLedgerType",
1202                37,
1203                "Unexpected ledger type.",
1204            ));
1205        }
1206        gravatar(&mut node);
1207        let mut m = Map::new();
1208        m.insert("index".into(), json!(hex::encode_upper(key)));
1209        m.insert("ledger_index".into(), json!(seq));
1210        m.insert("ledger_hash".into(), json!(hex::encode_upper(h.hash())));
1211        if let Some(at) = deleted {
1212            m.insert("deleted_ledger_index".into(), json!(at));
1213        }
1214        if as_bool(p.get("binary")) {
1215            m.insert("node_binary".into(), json!(hex::encode_upper(&data)));
1216        } else {
1217            m.insert("node".into(), Value::Object(node));
1218        }
1219        m.insert("validated".into(), json!(true));
1220        Ok(m)
1221    }
1222
1223    /// vault_info as in Clio 2.8/2.9 (`VaultInfo.cpp`): the Vault object, found
1224    /// by `vault_id` or by `owner` and `seq`, with its share issuance under
1225    /// `shares`. Field checks come first, in Clio's order, then the choice of
1226    /// selector, then the ledger.
1227    fn vault_info(&self, p: &Map<String, Value>) -> Res<Map<String, Value>> {
1228        let malformed = || rpc_err("malformedRequest", 5001, "Malformed request.");
1229        let present = |k: &str| p.get(k).filter(|v| !v.is_null());
1230        let vault_id = present("vault_id")
1231            .map(|v| {
1232                v.as_str()
1233                    .filter(|s| s.len() == 64)
1234                    .and_then(|s| hex::decode(s).ok())
1235                    .and_then(|b| <[u8; 32]>::try_from(b).ok())
1236                    .ok_or_else(malformed)
1237            })
1238            .transpose()?;
1239        let owner = present("owner")
1240            .map(|v| {
1241                v.as_str()
1242                    .and_then(decode_account)
1243                    .ok_or_else(|| rpc_err("malformedRequest", 5001, "OwnerNotHexString"))
1244            })
1245            .transpose()?;
1246        let seq = present("seq")
1247            .map(|v| {
1248                v.as_u64()
1249                    .and_then(|n| u32::try_from(n).ok())
1250                    .ok_or_else(malformed)
1251            })
1252            .transpose()?;
1253        if let Some(v) = present("ledger_index")
1254            && v.as_str() != Some("validated")
1255            && as_u32(v).is_none()
1256        {
1257            return Err(invalid_params("ledgerIndexMalformed"));
1258        }
1259        let by_owner = match (vault_id, owner, seq) {
1260            (Some(_), None, None) => None,
1261            (None, Some(o), Some(s)) => Some((o, s)),
1262            _ => return Err(malformed()),
1263        };
1264        let seq_l = self.resolve_old_state(p)?;
1265        let entry_not_found = |m: &str| rpc_err("entryNotFound", 98, m);
1266        let key = match (vault_id, by_owner) {
1267            (Some(k), _) => k,
1268            (None, Some((o, s))) => {
1269                if self
1270                    .state
1271                    .get(&keylet(b'a', &[&o]), seq_l)
1272                    .map_err(internal)?
1273                    .is_none()
1274                {
1275                    return Err(entry_not_found("Entry not found."));
1276                }
1277                keylet(b'V', &[&o, &s.to_be_bytes()])
1278            }
1279            (None, None) => unreachable!("checked above"),
1280        };
1281        let data = self
1282            .state
1283            .get(&key, seq_l)
1284            .map_err(internal)?
1285            .ok_or_else(|| entry_not_found("vault object not found."))?;
1286        let mut vault = xrpl_json::ledger_entry(&key, &data).map_err(internal)?;
1287        if vault.get("LedgerEntryType").and_then(Value::as_str) != Some("Vault") {
1288            return Err(entry_not_found("vault object not found."));
1289        }
1290        let mpt: [u8; 24] = vault
1291            .get("ShareMPTID")
1292            .and_then(Value::as_str)
1293            .and_then(|s| hex::decode(s).ok())
1294            .and_then(|b| b.try_into().ok())
1295            .ok_or_else(|| entry_not_found("issuance object not found."))?;
1296        let ikey = keylet(b'~', &[&mpt]);
1297        let idata = self
1298            .state
1299            .get(&ikey, seq_l)
1300            .map_err(internal)?
1301            .ok_or_else(|| entry_not_found("issuance object not found."))?;
1302        let shares = xrpl_json::ledger_entry(&ikey, &idata).map_err(internal)?;
1303        vault.insert("shares".into(), Value::Object(shares));
1304        let mut m = Map::new();
1305        m.insert("ledger_index".into(), json!(seq_l));
1306        m.insert("validated".into(), json!(true));
1307        m.insert("vault".into(), Value::Object(vault));
1308        Ok(m)
1309    }
1310
1311    /// `feature` as Clio serves it: the amendments this version knows, each
1312    /// with `enabled` read from the Amendments object of the ledger and
1313    /// `supported` from the table (crate::amendments). One amendment by
1314    /// `feature`, its name or ID; the admin part (`vetoed`) is refused.
1315    fn feature(&self, p: &Map<String, Value>) -> Res<Map<String, Value>> {
1316        if p.contains_key("vetoed") {
1317            return Err(rpc_err(
1318                "noPermission",
1319                6,
1320                "The admin portion of feature API is not available through Astraea.",
1321            ));
1322        }
1323        let wanted = match p.get("feature") {
1324            None | Some(Value::Null) => None,
1325            Some(Value::String(s)) => Some(s.as_str()),
1326            Some(_) => return Err(invalid_params("Invalid parameters.")),
1327        };
1328        let all = crate::amendments::AMENDMENTS
1329            .iter()
1330            .map(|(name, supported)| {
1331                (
1332                    hex::encode_upper(sha512_half(name.as_bytes())),
1333                    *name,
1334                    *supported,
1335                )
1336            });
1337        let chosen: Vec<(String, &str, bool)> = match wanted {
1338            None => all.collect(),
1339            Some(w) => {
1340                let one = all
1341                    .filter(|(id, name, _)| *name == w || id.eq_ignore_ascii_case(w))
1342                    .collect::<Vec<_>>();
1343                if one.is_empty() {
1344                    return Err(rpc_err("badFeature", 40, "Feature unknown or invalid."));
1345                }
1346                one
1347            }
1348        };
1349        let seq = self.resolve_old_state(p)?;
1350        let (_, h) = self.header(seq)?;
1351        let key = keylet(b'f', &[]);
1352        let enabled: Vec<String> = match self.state.get(&key, seq).map_err(internal)? {
1353            Some(data) => xrpl_json::ledger_entry(&key, &data)
1354                .map_err(internal)?
1355                .get("Amendments")
1356                .and_then(Value::as_array)
1357                .map(|a| {
1358                    a.iter()
1359                        .filter_map(Value::as_str)
1360                        .map(str::to_uppercase)
1361                        .collect()
1362                })
1363                .unwrap_or_default(),
1364            None => Vec::new(),
1365        };
1366        let mut features = Map::new();
1367        for (id, name, supported) in chosen {
1368            let on = enabled.contains(&id);
1369            features.insert(
1370                id,
1371                json!({"name": name, "enabled": on, "supported": supported}),
1372            );
1373        }
1374        let mut m = if wanted.is_some() {
1375            features
1376        } else {
1377            let mut m = Map::new();
1378            m.insert("features".into(), Value::Object(features));
1379            m
1380        };
1381        m.insert("ledger_hash".into(), json!(hex::encode_upper(h.hash())));
1382        m.insert("ledger_index".into(), json!(seq));
1383        m.insert("validated".into(), json!(true));
1384        Ok(m)
1385    }
1386
1387    fn account_info(&self, p: &Map<String, Value>, api: u32) -> Res<Map<String, Value>> {
1388        let v = p
1389            .get("account")
1390            .or_else(|| p.get("ident"))
1391            .ok_or_else(|| invalid_params("Missing field 'account'."))?;
1392        let seq = self.resolve_old_state(p)?;
1393        let a = account_id(v)?;
1394        let (_, h) = self.header(seq)?;
1395        let key = keylet(b'a', &[&a]);
1396        let data = self
1397            .state
1398            .get(&key, seq)
1399            .map_err(internal)?
1400            .ok_or_else(|| rpc_err("actNotFound", 19, "Account not found."))?;
1401        let mut node = xrpl_json::ledger_entry(&key, &data).map_err(internal)?;
1402        gravatar(&mut node);
1403        let flags = node.get("Flags").and_then(Value::as_u64).unwrap_or(0);
1404        const FLAGS: [(&str, u64); 15] = [
1405            ("defaultRipple", 0x0080_0000),
1406            ("depositAuth", 0x0100_0000),
1407            ("disableMasterKey", 0x0010_0000),
1408            ("disallowIncomingXRP", 0x0008_0000),
1409            ("globalFreeze", 0x0040_0000),
1410            ("noFreeze", 0x0020_0000),
1411            ("passwordSpent", 0x0001_0000),
1412            ("requireAuthorization", 0x0004_0000),
1413            ("requireDestinationTag", 0x0002_0000),
1414            ("disallowIncomingNFTokenOffer", 0x0400_0000),
1415            ("disallowIncomingCheck", 0x0800_0000),
1416            ("disallowIncomingPayChan", 0x1000_0000),
1417            ("disallowIncomingTrustline", 0x2000_0000),
1418            ("allowTrustLineClawback", 0x8000_0000),
1419            ("allowTrustLineLocking", 0x4000_0000),
1420        ];
1421        let account_flags: Map<String, Value> = FLAGS
1422            .iter()
1423            .map(|(n, f)| ((*n).to_owned(), json!(flags & f != 0)))
1424            .collect();
1425        let pseudo = ["AMMID", "VaultID", "LoanBrokerID"]
1426            .iter()
1427            .find(|f| node.contains_key(**f))
1428            .map(|f| f.trim_end_matches("ID").to_owned());
1429        let mut m = Map::new();
1430        let signers = if as_bool(p.get("signer_lists")) {
1431            let k = keylet(b'S', &[&a, &0u32.to_be_bytes()]);
1432            let mut list = Vec::new();
1433            if let Some(d) = self.state.get(&k, seq).map_err(internal)? {
1434                list.push(Value::Object(
1435                    xrpl_json::ledger_entry(&k, &d).map_err(internal)?,
1436                ));
1437            }
1438            Some(Value::Array(list))
1439        } else {
1440            None
1441        };
1442        if api == 1
1443            && let Some(s) = &signers
1444        {
1445            node.insert("signer_lists".into(), s.clone());
1446        }
1447        m.insert("account_data".into(), Value::Object(node));
1448        m.insert("ledger_hash".into(), json!(hex::encode_upper(h.hash())));
1449        m.insert("ledger_index".into(), json!(seq));
1450        m.insert("validated".into(), json!(true));
1451        m.insert("account_flags".into(), Value::Object(account_flags));
1452        if let Some(t) = pseudo {
1453            m.insert("pseudo_account".into(), json!({ "type": t }));
1454        }
1455        if api > 1
1456            && let Some(s) = signers
1457        {
1458            m.insert("signer_lists".into(), s);
1459        }
1460        Ok(m)
1461    }
1462}
1463
1464/// The position right after an account_tx marker in the walk direction; `None` means
1465/// there is nothing further.
1466/// TransactionIndex from metadata.
1467fn tx_index_of(meta: &[u8]) -> Option<u32> {
1468    use witness_core::stobject::{self, FieldId, types};
1469    // Canonical metadata starts with TransactionIndex (UInt32 is the lowest
1470    // type in it): header 0x20 0x1C, then the value. Parsing all fields walks
1471    // AffectedNodes, and a cold account_tx page does that for every
1472    // transaction of every ledger it reads. Anything else is parsed in full.
1473    if let [0x20, 0x1C, a, b, c, d, ..] = *meta {
1474        return Some(u32::from_be_bytes([a, b, c, d]));
1475    }
1476    let fs = stobject::fields(meta).ok()?;
1477    stobject::find(&fs, FieldId::new(types::UINT32, 28)).and_then(stobject::u32_of)
1478}
1479
1480/// A marker past our last ledger came from a server further ahead. Going
1481/// forward there is nothing after it here, so the page would be empty with no
1482/// marker, which reads as "no more transactions" although we just haven't got
1483/// that far; going backward it would be ignored. Refused so that a client can't
1484/// take either for a finished read.
1485pub(crate) fn marker_in_range(marker: TxPosition, last: u32) -> Res<()> {
1486    if marker.ledger > last {
1487        return Err(invalid_params("markerOutOfRange"));
1488    }
1489    Ok(())
1490}
1491
1492fn after_marker(a: TxPosition, forward: bool) -> Option<TxPosition> {
1493    if forward {
1494        match a.index.checked_add(1) {
1495            Some(i) => Some(TxPosition {
1496                ledger: a.ledger,
1497                index: i,
1498            }),
1499            None => a.ledger.checked_add(1).map(|l| TxPosition {
1500                ledger: l,
1501                index: 0,
1502            }),
1503        }
1504    } else if a.index > 0 {
1505        Some(TxPosition {
1506            ledger: a.ledger,
1507            index: a.index - 1,
1508        })
1509    } else {
1510        a.ledger.checked_sub(1).map(|l| TxPosition {
1511            ledger: l,
1512            index: u32::MAX,
1513        })
1514    }
1515}
1516
1517/// Clio adds a Gravatar link to an AccountRoot with EmailHash.
1518pub(crate) fn gravatar(node: &mut Map<String, Value>) {
1519    if node.get("LedgerEntryType").and_then(Value::as_str) == Some("AccountRoot")
1520        && let Some(h) = node.get("EmailHash").and_then(Value::as_str)
1521    {
1522        let url = format!("http://www.gravatar.com/avatar/{}", h.to_lowercase());
1523        node.insert("urlgravatar".into(), json!(url));
1524    }
1525}
1526
1527/// Currency code from a request: a three-letter ISO code or 40 hex chars.
1528pub(crate) fn currency_code(s: &str) -> Option<[u8; 20]> {
1529    let mut c = [0u8; 20];
1530    if s.len() == 3 {
1531        if s == "XRP" {
1532            return Some(c);
1533        }
1534        c[12..15].copy_from_slice(s.as_bytes());
1535        return Some(c);
1536    }
1537    hex::decode(s)
1538        .ok()
1539        .and_then(|b| <[u8; 20]>::try_from(b).ok())
1540}
1541
1542fn affected(meta: &Map<String, Value>) -> impl Iterator<Item = (&str, &Map<String, Value>)> {
1543    meta.get("AffectedNodes")
1544        .and_then(Value::as_array)
1545        .into_iter()
1546        .flatten()
1547        .filter_map(|n| n.as_object()?.iter().next())
1548        .filter_map(|(k, v)| Some((k.as_str(), v.as_object()?)))
1549}
1550
1551fn nft_ids(fields: Option<&Value>) -> Vec<String> {
1552    fields
1553        .and_then(|f| f.get("NFTokens"))
1554        .and_then(Value::as_array)
1555        .into_iter()
1556        .flatten()
1557        .filter_map(|t| {
1558            t.get("NFToken")?
1559                .get("NFTokenID")?
1560                .as_str()
1561                .map(str::to_owned)
1562        })
1563        .collect()
1564}
1565
1566/// MPTID of the issuance created by a transaction: sequence and issuer.
1567fn created_mpt_issuance(meta: &Map<String, Value>) -> Option<String> {
1568    for (kind, node) in affected(meta) {
1569        if kind != "CreatedNode"
1570            || node.get("LedgerEntryType").and_then(Value::as_str) != Some("MPTokenIssuance")
1571        {
1572            continue;
1573        }
1574        let f = node.get("NewFields")?;
1575        let seq = u32::try_from(f.get("Sequence")?.as_u64()?).ok()?;
1576        let issuer = decode_base58(f.get("Issuer")?.as_str()?)?.1;
1577        let mut id = seq.to_be_bytes().to_vec();
1578        id.extend(issuer);
1579        return Some(hex::encode_upper(id));
1580    }
1581    None
1582}
1583
1584/// Synthetic NFT fields in metadata, like insertNFTSyntheticInJson
1585/// in xrpld: nftoken_id, nftoken_ids, offer_id.
1586fn nft_synthetic(tt: &str, tx: &Map<String, Value>, meta: &mut Map<String, Value>) {
1587    let deleted_offers = |meta: &Map<String, Value>| {
1588        let mut ids: Vec<String> = affected(meta)
1589            .filter(|(k, n)| {
1590                *k == "DeletedNode"
1591                    && n.get("LedgerEntryType").and_then(Value::as_str) == Some("NFTokenOffer")
1592            })
1593            .filter_map(|(_, n)| {
1594                n.get("FinalFields")?
1595                    .get("NFTokenID")?
1596                    .as_str()
1597                    .map(str::to_owned)
1598            })
1599            .collect();
1600        ids.sort();
1601        ids.dedup();
1602        ids
1603    };
1604    match tt {
1605        "NFTokenMint" => {
1606            let (mut prev, mut fin) = (Vec::new(), Vec::new());
1607            for (kind, n) in affected(meta) {
1608                if n.get("LedgerEntryType").and_then(Value::as_str) != Some("NFTokenPage") {
1609                    continue;
1610                }
1611                if kind == "CreatedNode" {
1612                    fin.extend(nft_ids(n.get("NewFields")));
1613                } else if kind == "ModifiedNode" {
1614                    let pf = n.get("PreviousFields");
1615                    if pf.and_then(|p| p.get("NFTokens")).is_none() {
1616                        continue;
1617                    }
1618                    prev.extend(nft_ids(pf));
1619                    fin.extend(nft_ids(n.get("FinalFields")));
1620                }
1621            }
1622            if fin.len() == prev.len() + 1 {
1623                let id = fin
1624                    .iter()
1625                    .zip(prev.iter().map(Some).chain(std::iter::once(None)))
1626                    .find(|(f, p)| p.is_none_or(|p| p != *f))
1627                    .map(|(f, _)| f.clone());
1628                if let Some(id) = id {
1629                    meta.insert("nftoken_id".into(), json!(id));
1630                }
1631            }
1632        }
1633        "NFTokenAcceptOffer" => {
1634            if let Some(id) = deleted_offers(meta).into_iter().next() {
1635                meta.insert("nftoken_id".into(), json!(id));
1636            }
1637        }
1638        "NFTokenCancelOffer" => {
1639            let ids = deleted_offers(meta);
1640            meta.insert("nftoken_ids".into(), json!(ids));
1641        }
1642        _ => {}
1643    }
1644    if tt == "NFTokenCreateOffer" || (tt == "NFTokenMint" && tx.contains_key("Amount")) {
1645        let id = affected(meta)
1646            .find(|(k, n)| {
1647                *k == "CreatedNode"
1648                    && n.get("LedgerEntryType").and_then(Value::as_str) == Some("NFTokenOffer")
1649            })
1650            .and_then(|(_, n)| n.get("LedgerIndex")?.as_str().map(str::to_owned));
1651        if let Some(id) = id {
1652            meta.insert("offer_id".into(), json!(id));
1653        }
1654    }
1655}
1656
1657#[cfg(test)]
1658mod tests {
1659    use super::*;
1660
1661    /// Which transactions of an account Clio keeps for `mpt_issuance_id` and
1662    /// `tx_type` (tests/fixtures/account-tx-filters.json, real mainnet history
1663    /// of an MPT holder and an MPT issuer, answers of public Clio 2.8).
1664    #[test]
1665    fn account_tx_filters_keep_what_clio_keeps() {
1666        let raw = std::fs::read_to_string(
1667            std::path::Path::new(env!("CARGO_MANIFEST_DIR"))
1668                .join("tests/fixtures/account-tx-filters.json"),
1669        )
1670        .unwrap();
1671        let f: Value = serde_json::from_str(&raw).unwrap();
1672        let hash_of = |blob: &str| {
1673            let b = hex::decode(blob).unwrap();
1674            hex::encode_upper(witness_core::hash::sha512_half_prefixed(
1675                witness_core::hash::HashPrefix::TransactionId,
1676                &b,
1677            ))
1678        };
1679        let mut filters = 0;
1680        for case in f["cases"].as_array().unwrap() {
1681            type Decoded = (String, Map<String, Value>, Map<String, Value>);
1682            let txs: Vec<Decoded> = case["transactions"]
1683                .as_array()
1684                .unwrap()
1685                .iter()
1686                .map(|t| {
1687                    let tx = hex::decode(t["tx_blob"].as_str().unwrap()).unwrap();
1688                    let meta = hex::decode(t["meta_blob"].as_str().unwrap()).unwrap();
1689                    (
1690                        hash_of(t["tx_blob"].as_str().unwrap()),
1691                        xrpl_json::transaction(&tx).unwrap(),
1692                        xrpl_json::metadata(&meta).unwrap(),
1693                    )
1694                })
1695                .collect();
1696            for flt in case["filters"].as_array().unwrap() {
1697                let kept: Vec<String> = flt["kept"]
1698                    .as_array()
1699                    .unwrap()
1700                    .iter()
1701                    .map(|k| {
1702                        let k = k.as_str().unwrap();
1703                        if k.len() == 64 {
1704                            k.to_owned()
1705                        } else {
1706                            hash_of(k)
1707                        }
1708                    })
1709                    .collect();
1710                let ours: Vec<String> = txs
1711                    .iter()
1712                    .filter(|(_, tx, meta)| {
1713                        if let Some(id) = flt.get("mpt_issuance_id").and_then(Value::as_str) {
1714                            references_mpt(tx, meta, &id.to_ascii_uppercase())
1715                        } else {
1716                            let want = flt["tx_type"].as_str().unwrap();
1717                            tx["TransactionType"]
1718                                .as_str()
1719                                .is_some_and(|t| t.eq_ignore_ascii_case(want))
1720                        }
1721                    })
1722                    .map(|(h, _, _)| h.clone())
1723                    .collect();
1724                assert_eq!(ours, kept, "{} {flt}", case["account"]);
1725                filters += 1;
1726            }
1727        }
1728        assert!(filters >= 8);
1729    }
1730
1731    #[test]
1732    fn transaction_index_read_from_the_header_matches_a_full_parse() {
1733        use witness_core::stobject::{self, FieldId, types};
1734        let full = |m: &[u8]| {
1735            stobject::find(
1736                &stobject::fields(m).unwrap(),
1737                FieldId::new(types::UINT32, 28),
1738            )
1739            .and_then(stobject::u32_of)
1740        };
1741        // TransactionIndex 7, TransactionResult tesSUCCESS, empty AffectedNodes.
1742        let meta = [0x20, 0x1C, 0, 0, 0, 7, 0x03, 0x10, 0x00, 0xF8, 0xF1];
1743        assert_eq!(tx_index_of(&meta), Some(7));
1744        assert_eq!(tx_index_of(&meta), full(&meta));
1745        // Without TransactionIndex up front the full parse decides.
1746        let other = [0x03, 0x10, 0x00, 0xF8, 0xF1];
1747        assert_eq!(tx_index_of(&other), full(&other));
1748        assert_eq!(tx_index_of(&other), None);
1749        assert_eq!(tx_index_of(&[0x20, 0x1C, 0]), None);
1750    }
1751
1752    #[test]
1753    fn marker_past_the_last_ledger_is_refused() {
1754        let at = |ledger| TxPosition { ledger, index: 7 };
1755        assert!(marker_in_range(at(99), 100).is_ok());
1756        assert!(marker_in_range(at(100), 100).is_ok());
1757        let e = marker_in_range(at(101), 100).unwrap_err();
1758        assert_eq!((e.error, e.code), ("invalidParams", 31));
1759        assert_eq!(e.message, "markerOutOfRange");
1760    }
1761
1762    #[test]
1763    fn marker_at_the_edges() {
1764        let p = |ledger, index| TxPosition { ledger, index };
1765        assert_eq!(after_marker(p(5, 7), true), Some(p(5, 8)));
1766        assert_eq!(after_marker(p(5, u32::MAX), true), Some(p(6, 0)));
1767        assert_eq!(after_marker(p(u32::MAX, u32::MAX), true), None);
1768        assert_eq!(after_marker(p(5, 0), false), Some(p(4, u32::MAX)));
1769        assert_eq!(after_marker(p(0, 0), false), None);
1770    }
1771
1772    #[test]
1773    fn times_render_like_xrpld() {
1774        // 846178792 is the close time of ledger 107876000.
1775        assert_eq!(time_iso(846_178_792), "2026-10-24T17:39:52Z");
1776        assert_eq!(
1777            time_human(846_178_792),
1778            "2026-Oct-24 17:39:52.000000000 UTC"
1779        );
1780        assert_eq!(time_iso(0), "2000-01-01T00:00:00Z");
1781    }
1782
1783    #[test]
1784    fn account_keylet() {
1785        // AccountRoot rhub8VRN55s94qWKDv6jmDy1pUykJzF3wq: index from a Clio response.
1786        let a = account_id(&json!("rhub8VRN55s94qWKDv6jmDy1pUykJzF3wq")).unwrap();
1787        assert_eq!(
1788            hex::encode_upper(keylet(b'a', &[&a])),
1789            "BF1F2A23D614916E3C6ED2DCC389468CFA09045BEDB54C71A05C5E94EA6C6CFE"
1790        );
1791    }
1792}