1use serde_json::{Map, Value, json};
15
16use crate::api::{
17 Engine, Res, RpcError, account_id, as_bool, gravatar, hash256, internal, invalid_params,
18 keylet, rpc_err,
19};
20use crate::xrpl_json::{self, iou_text};
21
22const OWNED_LIMIT_MIN: u32 = 10;
23const OWNED_LIMIT_MAX: u32 = 400;
24const OWNED_LIMIT_DEFAULT: u32 = 200;
25const DATA_LIMIT_JSON: u32 = 256;
26const DATA_LIMIT_BINARY: u32 = 2048;
27type Visit<'a> = dyn FnMut(&[u8; 32], &[u8]) -> Res<()> + 'a;
29pub(crate) type DirWalk = (Vec<[u8; 32]>, Option<([u8; 32], u32)>);
31
32const MPT_LIMIT_DEFAULT: u64 = 50;
34const MPT_LIMIT_MAX: u64 = 100;
35
36const NFT_HINT: u32 = u32::MAX;
38
39#[derive(Clone, Copy, PartialEq, Eq)]
41enum Kind {
42 Chain,
45 Owned,
46 Blocker,
48}
49
50const TYPES: &[(&str, &str, Kind)] = &[
52 ("AccountRoot", "account", Kind::Owned),
53 ("Amendments", "amendments", Kind::Chain),
54 ("Check", "check", Kind::Blocker),
55 ("DepositPreauth", "deposit_preauth", Kind::Owned),
56 ("DirectoryNode", "directory", Kind::Chain),
57 ("Escrow", "escrow", Kind::Blocker),
58 ("FeeSettings", "fee", Kind::Chain),
59 ("LedgerHashes", "hashes", Kind::Chain),
60 ("Offer", "offer", Kind::Owned),
61 ("PayChannel", "payment_channel", Kind::Blocker),
62 ("SignerList", "signer_list", Kind::Owned),
63 ("RippleState", "state", Kind::Blocker),
64 ("Ticket", "ticket", Kind::Owned),
65 ("NFTokenOffer", "nft_offer", Kind::Owned),
66 ("NFTokenPage", "nft_page", Kind::Blocker),
67 ("AMM", "amm", Kind::Owned),
68 ("Bridge", "bridge", Kind::Blocker),
69 ("XChainOwnedClaimID", "xchain_owned_claim_id", Kind::Blocker),
70 (
71 "XChainOwnedCreateAccountClaimID",
72 "xchain_owned_create_account_claim_id",
73 Kind::Blocker,
74 ),
75 ("DID", "did", Kind::Owned),
76 ("Oracle", "oracle", Kind::Owned),
77 ("Credential", "credential", Kind::Owned),
78 ("Vault", "vault", Kind::Owned),
79 ("LoanBroker", "loan_broker", Kind::Owned),
80 ("Loan", "loan", Kind::Blocker),
81 ("NegativeUNL", "nunl", Kind::Chain),
82 ("MPTokenIssuance", "mpt_issuance", Kind::Blocker),
83 ("MPToken", "mptoken", Kind::Blocker),
84 ("PermissionedDomain", "permissioned_domain", Kind::Blocker),
85 ("Delegate", "delegate", Kind::Owned),
86];
87
88fn kind_of(s: &str) -> Option<(&'static str, Kind)> {
90 TYPES
91 .iter()
92 .find(|(_, rpc, _)| *rpc == s)
93 .or_else(|| TYPES.iter().find(|(n, _, _)| n.eq_ignore_ascii_case(s)))
94 .map(|(n, _, k)| (*n, *k))
95}
96
97fn type_filter(p: &Map<String, Value>, owned: bool) -> Res<Option<&'static str>> {
99 match p.get("type") {
100 None => Ok(None),
101 Some(Value::String(s)) => match kind_of(s) {
102 Some((_, Kind::Chain)) if owned => Err(invalid_params("Invalid field 'type'.")),
103 Some((n, _)) => Ok(Some(n)),
104 None => Err(invalid_params("Invalid field 'type'.")),
105 },
106 Some(_) => Err(invalid_params("Invalid field 'type', not string.")),
107 }
108}
109
110fn owned_limit(p: &Map<String, Value>) -> Res<u32> {
112 match p.get("limit") {
113 None => Ok(OWNED_LIMIT_DEFAULT),
114 Some(v) => v
115 .as_u64()
116 .filter(|n| *n >= 1)
117 .and_then(|n| u32::try_from(n).ok())
118 .map(|n| n.clamp(OWNED_LIMIT_MIN, OWNED_LIMIT_MAX))
119 .ok_or_else(|| invalid_params("Invalid parameters.")),
120 }
121}
122
123fn malformed_cursor() -> RpcError {
124 invalid_params("Malformed cursor.")
125}
126
127fn invalid_marker() -> RpcError {
128 invalid_params("Invalid marker.")
129}
130
131fn spelled_out(e: RpcError) -> RpcError {
136 if e.error == "actMalformed" {
137 rpc_err("actMalformed", 35, "Account malformed.")
138 } else {
139 e
140 }
141}
142
143fn parse_cursor(p: &Map<String, Value>) -> Res<Option<([u8; 32], u32)>> {
145 let s = match p.get("marker") {
146 None => return Ok(None),
147 Some(Value::String(s)) => s,
148 Some(_) => return Err(invalid_params("markerNotString")),
149 };
150 let (k, h) = s.split_once(',').ok_or_else(malformed_cursor)?;
151 let h = h.split(',').next().unwrap_or_default();
152 let key = hex::decode(k)
153 .ok()
154 .and_then(|b| <[u8; 32]>::try_from(b).ok())
155 .ok_or_else(malformed_cursor)?;
156 let hint = h.parse::<u64>().map_err(|_| malformed_cursor())? as u32;
158 Ok(Some((key, hint)))
159}
160
161fn cursor_text(key: &[u8; 32], hint: u32) -> String {
162 format!("{},{hint}", hex::encode_upper(key))
163}
164
165pub(crate) fn h256(node: &Map<String, Value>, field: &str) -> [u8; 32] {
166 node.get(field)
167 .and_then(Value::as_str)
168 .and_then(|s| hex::decode(s).ok())
169 .and_then(|b| <[u8; 32]>::try_from(b).ok())
170 .unwrap_or([0; 32])
171}
172
173fn u32_field(node: &Map<String, Value>, field: &str) -> u64 {
174 node.get(field).and_then(Value::as_u64).unwrap_or(0)
175}
176
177fn dir_page(key: &[u8; 32], data: &[u8]) -> Res<(Vec<[u8; 32]>, u64)> {
179 let node = xrpl_json::ledger_entry(key, data).map_err(internal)?;
180 let broken = || corrupt(key, "directory page without Indexes");
183 let indexes = node
184 .get("Indexes")
185 .and_then(Value::as_array)
186 .ok_or_else(broken)?
187 .iter()
188 .map(|v| {
189 v.as_str()
190 .and_then(|s| hex::decode(s).ok())
191 .and_then(|b| <[u8; 32]>::try_from(b).ok())
192 .ok_or_else(broken)
193 })
194 .collect::<Res<Vec<_>>>()?;
195 let next = node
196 .get("IndexNext")
197 .and_then(Value::as_str)
198 .and_then(|s| u64::from_str_radix(s, 16).ok())
199 .unwrap_or(0);
200 Ok((indexes, next))
201}
202
203pub(crate) fn corrupt(key: &[u8; 32], what: &str) -> RpcError {
206 internal(format!("corrupt_state: {what}: {}", hex::encode_upper(key)))
207}
208
209fn required_amount(node: &Map<String, Value>, field: &str, key: &[u8; 32]) -> Res<String> {
211 match node.get(field) {
212 Some(v @ (Value::Object(_) | Value::String(_))) => Ok(amount_value(Some(v))),
213 _ => Err(corrupt(key, &format!("missing {field}"))),
214 }
215}
216
217fn dir_page_key(root: &[u8; 32], n: u64) -> [u8; 32] {
219 if n == 0 {
220 *root
221 } else {
222 keylet(b'd', &[root, &n.to_be_bytes()])
223 }
224}
225
226fn amount_value(v: Option<&Value>) -> String {
228 match v {
229 Some(Value::Object(o)) => o
230 .get("value")
231 .and_then(Value::as_str)
232 .unwrap_or("0")
233 .to_owned(),
234 Some(Value::String(s)) => s.clone(),
235 _ => "0".into(),
236 }
237}
238
239pub(crate) fn negate(v: &str) -> String {
240 match v.strip_prefix('-') {
241 Some(rest) => rest.to_owned(),
242 None if v == "0" => v.to_owned(),
243 None => format!("-{v}"),
244 }
245}
246
247fn quality_text(book: &[u8; 32]) -> String {
249 let q = u64::from_be_bytes(book[24..].try_into().unwrap_or_default());
250 let mut m = q & ((1 << 56) - 1);
251 let mut e = (q >> 56) as i32 - 100;
252 if m == 0 {
253 return "0".into();
254 }
255 while m < 1_000_000_000_000_000 {
256 m *= 10;
257 e -= 1;
258 }
259 while m > 9_999_999_999_999_999 {
260 m /= 10;
261 e += 1;
262 }
263 iou_text(false, m, e)
264}
265
266impl Engine {
267 pub(crate) fn fetch(&self, key: &[u8; 32], seq: u32) -> Res<Option<Vec<u8>>> {
268 self.state.get(key, seq).map_err(internal)
269 }
270
271 pub(crate) fn owner_of(&self, p: &Map<String, Value>) -> Res<([u8; 20], u32, [u8; 32])> {
273 self.owner_at(p, false)
274 }
275
276 pub(crate) fn owner_at(
280 &self,
281 p: &Map<String, Value>,
282 old: bool,
283 ) -> Res<([u8; 20], u32, [u8; 32])> {
284 let a = account_id(
285 p.get("account")
286 .ok_or_else(|| invalid_params("Required field 'account' missing"))?,
287 )?;
288 let seq = if old {
289 self.resolve_old_state(p)?
290 } else {
291 self.resolve_state(p)?
292 };
293 let (_, h) = self.header(seq)?;
294 if self.fetch(&keylet(b'a', &[&a]), seq)?.is_none() {
295 return Err(rpc_err("actNotFound", 19, "Account not found."));
296 }
297 Ok((a, seq, h.hash()))
298 }
299
300 fn owned(
303 &self,
304 account: &[u8; 20],
305 seq: u32,
306 mut limit: u32,
307 cursor: Option<([u8; 32], u32)>,
308 nft: bool,
309 visit: &mut Visit<'_>,
310 ) -> Res<Option<String>> {
311 let (mut marker, mut hint) = cursor.unwrap_or(([0; 32], 0));
312 let nft_marker = hint == NFT_HINT && marker != [0; 32];
313 let nft_marker_zero = hint == NFT_HINT && marker == [0; 32];
314 if nft && (cursor.is_none() || nft_marker) {
315 let (next, count) = self.nft_pages(account, seq, marker, limit, visit)?;
316 if count >= limit {
317 return Ok(Some(cursor_text(&next, NFT_HINT)));
318 }
319 limit -= count;
320 (marker, hint) = ([0; 32], 0);
321 } else if nft && nft_marker_zero {
322 (marker, hint) = ([0; 32], 0);
323 }
324
325 let root = keylet(b'O', &[account]);
326 let (keys, next_cursor) = self.dir_walk(&root, seq, limit, marker, hint)?;
327 let objects = self.state.get_many(&keys, seq).map_err(internal)?;
328 for (key, data) in keys.iter().zip(objects) {
329 let data = data.ok_or_else(|| corrupt(key, "object from the directory is missing"))?;
330 visit(key, &data)?;
331 }
332 Ok(next_cursor.map(|(k, n)| cursor_text(&k, n)))
333 }
334
335 pub(crate) fn dir_walk(
340 &self,
341 root: &[u8; 32],
342 seq: u32,
343 mut limit: u32,
344 marker: [u8; 32],
345 hint: u32,
346 ) -> Res<DirWalk> {
347 let root = *root;
348 let mut keys = Vec::new();
349 let mut found = marker == [0; 32];
352 let mut page = if found { 0 } else { u64::from(hint) };
353 let mut number = hint;
354 let mut next_cursor = None;
355 if !found {
356 let k = dir_page_key(&root, page);
357 let data = self.fetch(&k, seq)?.ok_or_else(invalid_marker)?;
358 if !dir_page(&k, &data)?.0.contains(&marker) {
359 return Err(invalid_marker());
360 }
361 }
362 let mut visited = std::collections::HashSet::new();
363 loop {
364 crate::limits::check_rpc()?;
365 let k = dir_page_key(&root, page);
366 if !visited.insert(page) {
367 return Err(corrupt(&k, "owner directory pages form a cycle"));
368 }
369 let Some(data) = self.fetch(&k, seq)? else {
370 if page == 0 && marker == [0; 32] {
373 break;
374 }
375 if found && marker == [0; 32] {
376 return Err(corrupt(&k, "IndexNext points to a nonexistent page"));
377 }
378 return Err(invalid_params("Owner directory not found."));
379 };
380 let (indexes, next) = dir_page(&k, &data)?;
381 for key in indexes {
382 if !found {
383 found = key == marker;
384 continue;
385 }
386 keys.push(key);
387 limit -= 1;
388 if limit == 0 {
389 break;
390 }
391 }
392 if limit == 0 {
393 next_cursor = keys.last().map(|k| (*k, number));
394 break;
395 }
396 if next == 0 {
397 break;
398 }
399 page = next;
400 number = next as u32;
402 }
403 Ok((keys, next_cursor))
404 }
405
406 fn nft_pages(
409 &self,
410 account: &[u8; 20],
411 seq: u32,
412 next: [u8; 32],
413 limit: u32,
414 visit: &mut Visit<'_>,
415 ) -> Res<([u8; 32], u32)> {
416 let mut first = [0u8; 32];
417 first[..20].copy_from_slice(account);
418 let mut last = first;
419 last[20..].fill(0xFF);
420 if next != [0; 32] && next[..20] != first[..20] {
421 return Err(invalid_marker());
422 }
423 let mut current = if next == [0; 32] { last } else { next };
424 let Some(mut data) = self.fetch(¤t, seq)? else {
425 if next == [0; 32] {
426 return Ok(([0; 32], 0));
427 }
428 return Err(invalid_marker());
429 };
430 let mut count = 0;
431 loop {
432 crate::limits::check_rpc()?;
433 let node = xrpl_json::ledger_entry(¤t, &data).map_err(internal)?;
434 let previous = h256(&node, "PreviousPageMin");
435 visit(¤t, &data)?;
436 count += 1;
437 if count == limit || previous == [0; 32] {
438 return Ok((previous, count));
439 }
440 match self.fetch(&previous, seq)? {
441 Some(d) => {
442 current = previous;
443 data = d;
444 }
445 None => {
448 return Err(corrupt(
449 &previous,
450 "PreviousPageMin points to a nonexistent NFT page",
451 ));
452 }
453 }
454 }
455 }
456
457 pub(crate) fn account_objects(&self, p: &Map<String, Value>) -> Res<Map<String, Value>> {
458 let limit = owned_limit(p)?;
459 let only = type_filter(p, true)?;
460 let cursor = parse_cursor(p)?;
461 let (account, seq, hash) = self.owner_at(p, true)?;
462 let blockers = as_bool(p.get("deletion_blockers_only"));
463 let keep = |t: &str| -> bool {
464 if blockers {
465 kind_of(t).is_some_and(|(_, k)| k == Kind::Blocker) && only.is_none_or(|o| o == t)
466 } else {
467 only.is_none_or(|o| o == t)
468 }
469 };
470 let mut objects = Vec::new();
471 let marker = self.owned(&account, seq, limit, cursor, true, &mut |k, d| {
472 let mut node = xrpl_json::ledger_entry(k, d).map_err(internal)?;
473 if keep(
474 node.get("LedgerEntryType")
475 .and_then(Value::as_str)
476 .unwrap_or_default(),
477 ) {
478 gravatar(&mut node);
479 objects.push(Value::Object(node));
480 }
481 Ok(())
482 })?;
483 let mut m = Map::new();
484 m.insert("ledger_hash".into(), json!(hex::encode_upper(hash)));
485 m.insert("ledger_index".into(), json!(seq));
486 m.insert("validated".into(), json!(true));
487 m.insert("limit".into(), json!(limit));
488 m.insert("account".into(), p["account"].clone());
489 m.insert("account_objects".into(), Value::Array(objects));
490 if let Some(mk) = marker {
491 m.insert("marker".into(), json!(mk));
492 }
493 Ok(m)
494 }
495
496 pub(crate) fn account_lines(&self, p: &Map<String, Value>) -> Res<Map<String, Value>> {
497 let limit = owned_limit(p)?;
498 let cursor = parse_cursor(p)?;
499 let peer = p
501 .get("peer")
502 .map(|v| account_id(v).map_err(spelled_out))
503 .transpose()?;
504 let (account, seq, hash) = self.owner_at(p, true).map_err(spelled_out)?;
505 let ignore_default = as_bool(p.get("ignore_default"));
506 let mut lines = Vec::new();
507 let marker = self.owned(&account, seq, limit, cursor, false, &mut |k, d| {
508 let node = xrpl_json::ledger_entry(k, d).map_err(internal)?;
509 if node.get("LedgerEntryType").and_then(Value::as_str) != Some("RippleState") {
510 return Ok(());
511 }
512 if let Some(line) = line(k, &node, &account, peer.as_ref(), ignore_default)? {
513 lines.push(line);
514 }
515 Ok(())
516 })?;
517 let mut m = Map::new();
518 m.insert("account".into(), p["account"].clone());
519 m.insert("ledger_hash".into(), json!(hex::encode_upper(hash)));
520 m.insert("ledger_index".into(), json!(seq));
521 m.insert("validated".into(), json!(true));
522 m.insert("limit".into(), json!(limit));
523 m.insert("lines".into(), Value::Array(lines));
524 if let Some(mk) = marker {
525 m.insert("marker".into(), json!(mk));
526 }
527 Ok(m)
528 }
529
530 pub(crate) fn account_offers(&self, p: &Map<String, Value>) -> Res<Map<String, Value>> {
531 let limit = owned_limit(p)?;
532 let cursor = parse_cursor(p)?;
533 let (account, seq, hash) = self.owner_of(p)?;
534 let mut offers = Vec::new();
535 let marker = self.owned(&account, seq, limit, cursor, false, &mut |k, d| {
536 let node = xrpl_json::ledger_entry(k, d).map_err(internal)?;
537 if node.get("LedgerEntryType").and_then(Value::as_str) == Some("Offer") {
538 offers.push(offer(k, &node)?);
539 }
540 Ok(())
541 })?;
542 let mut m = Map::new();
543 m.insert("ledger_hash".into(), json!(hex::encode_upper(hash)));
544 m.insert("ledger_index".into(), json!(seq));
545 m.insert("validated".into(), json!(true));
546 m.insert("account".into(), json!(xrpl_json::account(&account)));
547 m.insert("offers".into(), Value::Array(offers));
548 if let Some(mk) = marker {
549 m.insert("marker".into(), json!(mk));
550 }
551 Ok(m)
552 }
553
554 pub(crate) fn account_mptoken_issuances(
559 &self,
560 p: &Map<String, Value>,
561 ) -> Res<Map<String, Value>> {
562 let limit = owned_limit(p)?;
563 let cursor = parse_cursor(p)?;
564 let (account, seq, hash) = self.owner_at(p, true).map_err(spelled_out)?;
565 let issuer = json!(xrpl_json::account(&account));
566 let mut issuances = Vec::new();
567 let marker = self.owned(&account, seq, limit, cursor, false, &mut |k, d| {
568 let node = xrpl_json::ledger_entry(k, d).map_err(internal)?;
569 if node.get("LedgerEntryType").and_then(Value::as_str) == Some("MPTokenIssuance") {
570 issuances.push(mpt_issuance(&account, &node, &issuer));
571 }
572 Ok(())
573 })?;
574 Ok(owned_answer(
575 p,
576 hash,
577 seq,
578 limit,
579 "mpt_issuances",
580 issuances,
581 marker,
582 ))
583 }
584
585 pub(crate) fn account_mptokens(&self, p: &Map<String, Value>) -> Res<Map<String, Value>> {
587 let limit = owned_limit(p)?;
588 let cursor = parse_cursor(p)?;
589 let (account, seq, hash) = self.owner_at(p, true).map_err(spelled_out)?;
590 let mut tokens = Vec::new();
591 let marker = self.owned(&account, seq, limit, cursor, false, &mut |k, d| {
592 let node = xrpl_json::ledger_entry(k, d).map_err(internal)?;
593 if node.get("LedgerEntryType").and_then(Value::as_str) == Some("MPToken") {
594 tokens.push(mptoken(k, &node));
595 }
596 Ok(())
597 })?;
598 Ok(owned_answer(
599 p, hash, seq, limit, "mptokens", tokens, marker,
600 ))
601 }
602
603 pub(crate) fn mpt_holders(&self, p: &Map<String, Value>) -> Res<Map<String, Value>> {
607 let id = p
608 .get("mpt_issuance_id")
609 .ok_or_else(|| invalid_params("Required field 'mpt_issuance_id' missing"))?;
610 let id: [u8; 24] = id
611 .as_str()
612 .and_then(|s| hex::decode(s).ok())
613 .and_then(|b| b.try_into().ok())
614 .ok_or_else(|| invalid_params("mpt_issuance_idMalformed"))?;
615 let limit = match p.get("limit") {
616 None => MPT_LIMIT_DEFAULT,
617 Some(v) => v
618 .as_u64()
619 .filter(|n| *n >= 1)
620 .map(|n| n.min(MPT_LIMIT_MAX))
621 .ok_or_else(|| invalid_params("Invalid parameters."))?,
622 };
623 let after: Option<[u8; 20]> = match p.get("marker") {
624 None => None,
625 Some(v) => Some(
626 v.as_str()
627 .and_then(|s| hex::decode(s).ok())
628 .and_then(|b| b.try_into().ok())
629 .ok_or_else(|| invalid_params("markerMalformed"))?,
630 ),
631 };
632 let seq = self.resolve_state(p)?;
633 if self.fetch(&keylet(b'~', &[&id]), seq)?.is_none() {
634 return Err(rpc_err("objectNotFound", 92, "objectNotFound"));
635 }
636 let holders = self
637 .state
638 .mpt_holders(&id, seq, after.as_ref(), limit as usize)
639 .map_err(internal)?;
640 let keys: Vec<[u8; 32]> = holders.iter().map(|h| h.1).collect();
641 let objects = self.state.get_many(&keys, seq).map_err(internal)?;
642 let mut tokens = Vec::with_capacity(holders.len());
643 for ((acc, key), data) in holders.iter().zip(objects) {
644 let data =
645 data.ok_or_else(|| corrupt(key, "MPToken from the holder index is missing"))?;
646 let node = xrpl_json::ledger_entry(key, &data).map_err(internal)?;
647 tokens.push(json!({
648 "account": xrpl_json::account(acc),
649 "flags": u32_field(&node, "Flags"),
650 "mpt_amount": node.get("MPTAmount").cloned().unwrap_or_else(|| json!("0")),
651 "mptoken_index": hex::encode_upper(key),
652 }));
653 }
654 let mut m = Map::new();
655 m.insert("mpt_issuance_id".into(), json!(hex::encode_upper(id)));
656 m.insert("limit".into(), json!(limit));
657 m.insert("ledger_index".into(), json!(seq));
658 if tokens.len() as u64 == limit
659 && let Some((last, _)) = holders.last()
660 {
661 m.insert("marker".into(), json!(hex::encode_upper(last)));
662 }
663 m.insert("mptokens".into(), Value::Array(tokens));
664 m.insert("validated".into(), json!(true));
665 Ok(m)
666 }
667
668 pub(crate) fn ledger_data(&self, p: &Map<String, Value>, api: u32) -> Res<Map<String, Value>> {
669 let binary = match p.get("binary") {
670 None => false,
671 Some(Value::Bool(b)) => *b,
672 Some(_) => return Err(invalid_params("Invalid parameters.")),
673 };
674 let limit = match p.get("limit") {
675 None => None,
676 Some(v) => Some(
677 v.as_u64()
678 .filter(|n| *n >= 1)
679 .and_then(|n| u32::try_from(n).ok())
680 .ok_or_else(|| invalid_params("Invalid parameters."))?,
681 ),
682 };
683 if as_bool(p.get("out_of_order")) {
684 return Err(rpc_err(
685 "notSupported",
686 75,
687 "Operation not supported: out_of_order.",
688 ));
689 }
690 let marker = match p.get("marker") {
691 None => None,
692 Some(Value::String(_)) => Some(hash256(&p["marker"], "marker")?),
693 Some(_) => return Err(invalid_params("markerNotString")),
694 };
695 let only = type_filter(p, false)?;
696 let seq = self.resolve_state(p)?;
697 let (raw, h) = self.header(seq)?;
698 let mut m = Map::new();
699 match &marker {
700 None => {
701 m.insert(
702 "ledger".into(),
703 Value::Object(self.header_json(&raw, &h, binary, api)),
704 );
705 }
706 Some(k) => {
707 if self.fetch(k, seq)?.is_none() {
708 return Err(invalid_params("markerDoesNotExist"));
709 }
710 }
711 }
712 let cap = if binary {
713 DATA_LIMIT_BINARY
714 } else {
715 DATA_LIMIT_JSON
716 };
717 let take = limit.unwrap_or(cap).min(cap) as usize;
718 let mut state = Vec::new();
719 let mut last = None;
720 let mut count = 0;
721 for item in self.state.objects_page(seq, marker.as_ref()) {
722 crate::limits::check_rpc()?;
723 let (k, d) = item.map_err(internal)?;
724 count += 1;
725 last = Some(k);
726 let node = xrpl_json::ledger_entry(&k, &d).map_err(internal)?;
727 let t = node.get("LedgerEntryType").and_then(Value::as_str);
728 if only.is_none_or(|o| Some(o) == t) {
729 if binary {
730 state.push(json!({
731 "data": hex::encode_upper(&d),
732 "index": hex::encode_upper(k),
733 }));
734 } else {
735 let mut node = node;
736 gravatar(&mut node);
737 state.push(Value::Object(node));
738 }
739 }
740 if count == take {
741 break;
742 }
743 }
744 m.insert("ledger_hash".into(), json!(hex::encode_upper(h.hash())));
745 m.insert("ledger_index".into(), json!(seq));
746 m.insert("validated".into(), json!(true));
747 m.insert("state".into(), Value::Array(state));
748 if count == take
751 && let Some(k) = last
752 {
753 m.insert("marker".into(), json!(hex::encode_upper(k)));
754 }
755 Ok(m)
756 }
757}
758
759fn line(
761 key: &[u8; 32],
762 node: &Map<String, Value>,
763 account: &[u8; 20],
764 peer: Option<&[u8; 20]>,
765 ignore_default: bool,
766) -> Res<Option<Value>> {
767 const LOW_RESERVE: u64 = 0x0001_0000;
768 const HIGH_RESERVE: u64 = 0x0002_0000;
769 const LOW_AUTH: u64 = 0x0004_0000;
770 const HIGH_AUTH: u64 = 0x0008_0000;
771 const LOW_NO_RIPPLE: u64 = 0x0010_0000;
772 const HIGH_NO_RIPPLE: u64 = 0x0020_0000;
773 const LOW_FREEZE: u64 = 0x0040_0000;
774 const HIGH_FREEZE: u64 = 0x0080_0000;
775 const LOW_DEEP_FREEZE: u64 = 0x0200_0000;
776 const HIGH_DEEP_FREEZE: u64 = 0x0400_0000;
777
778 let flags = u32_field(node, "Flags");
779 let issuer = |f: &str| -> Res<String> {
780 node.get(f)
781 .and_then(|v| v.get("issuer"))
782 .and_then(Value::as_str)
783 .map(str::to_owned)
784 .ok_or_else(|| corrupt(key, &format!("trust line without {f}")))
785 };
786 let (low, high) = (issuer("LowLimit")?, issuer("HighLimit")?);
787 let me = xrpl_json::account(account);
788 let view_lowest = low == me;
789 if ignore_default {
790 let reserve = if view_lowest {
791 LOW_RESERVE
792 } else {
793 HIGH_RESERVE
794 };
795 if flags & reserve == 0 {
796 return Ok(None);
797 }
798 }
799 let peer_id = if view_lowest { &high } else { &low };
800 if let Some(p) = peer
801 && xrpl_json::account(p) != *peer_id
802 {
803 return Ok(None);
804 }
805 let (limit_f, limit_peer_f) = if view_lowest {
806 ("LowLimit", "HighLimit")
807 } else {
808 ("HighLimit", "LowLimit")
809 };
810 let (q_in, q_out) = if view_lowest {
811 ("LowQualityIn", "LowQualityOut")
812 } else {
813 ("HighQualityIn", "HighQualityOut")
814 };
815 let balance = required_amount(node, "Balance", key)?;
816 let balance = if view_lowest {
817 balance
818 } else {
819 negate(&balance)
820 };
821 let currency = node
822 .get("Balance")
823 .and_then(|v| v.get("currency"))
824 .cloned()
825 .unwrap_or(Value::Null);
826 let mut l = Map::new();
827 l.insert("account".into(), json!(peer_id));
828 l.insert("balance".into(), json!(balance));
829 l.insert("currency".into(), currency);
830 l.insert("limit".into(), json!(required_amount(node, limit_f, key)?));
831 l.insert(
832 "limit_peer".into(),
833 json!(required_amount(node, limit_peer_f, key)?),
834 );
835 l.insert("quality_in".into(), json!(u32_field(node, q_in)));
836 l.insert("quality_out".into(), json!(u32_field(node, q_out)));
837 let side = |lo: u64, hi: u64| if view_lowest { (lo, hi) } else { (hi, lo) };
838 for (name, peer_name, lo, hi) in [
839 ("no_ripple", "no_ripple_peer", LOW_NO_RIPPLE, HIGH_NO_RIPPLE),
840 ("authorized", "peer_authorized", LOW_AUTH, HIGH_AUTH),
841 ("freeze", "freeze_peer", LOW_FREEZE, HIGH_FREEZE),
842 (
843 "deep_freeze",
844 "deep_freeze_peer",
845 LOW_DEEP_FREEZE,
846 HIGH_DEEP_FREEZE,
847 ),
848 ] {
849 let (mine, theirs) = side(lo, hi);
850 if flags & mine != 0 {
851 l.insert(name.into(), json!(true));
852 }
853 if flags & theirs != 0 {
854 l.insert(peer_name.into(), json!(true));
855 }
856 }
857 Ok(Some(Value::Object(l)))
858}
859
860fn owned_answer(
863 p: &Map<String, Value>,
864 hash: [u8; 32],
865 seq: u32,
866 limit: u32,
867 field: &str,
868 items: Vec<Value>,
869 marker: Option<String>,
870) -> Map<String, Value> {
871 let mut m = Map::new();
872 m.insert("account".into(), p["account"].clone());
873 m.insert("ledger_hash".into(), json!(hex::encode_upper(hash)));
874 m.insert("ledger_index".into(), json!(seq));
875 m.insert("validated".into(), json!(true));
876 m.insert("limit".into(), json!(limit));
877 m.insert(field.into(), Value::Array(items));
878 if let Some(mk) = marker {
879 m.insert("marker".into(), json!(mk));
880 }
881 m
882}
883
884fn copy(out: &mut Map<String, Value>, node: &Map<String, Value>, field: &str, name: &str) {
887 if let Some(v) = node.get(field) {
888 out.insert(name.into(), v.clone());
889 }
890}
891
892fn flags(out: &mut Map<String, Value>, bits: u64, table: &[(u64, &str)]) {
894 for (mask, name) in table {
895 if bits & mask != 0 {
896 out.insert((*name).into(), json!(true));
897 }
898 }
899}
900
901const MPT_ISSUANCE_FLAGS: [(u64, &str); 8] = [
902 (0x01, "mpt_locked"),
903 (0x02, "mpt_can_lock"),
904 (0x04, "mpt_require_auth"),
905 (0x08, "mpt_can_escrow"),
906 (0x10, "mpt_can_trade"),
907 (0x20, "mpt_can_transfer"),
908 (0x40, "mpt_can_clawback"),
909 (0x80, "mpt_can_hold_confidential_balance"),
910];
911
912const MPT_IMMUTABLE_FLAGS: [(u64, &str); 9] = [
914 (0x02, "mpt_immutable_can_lock"),
915 (0x04, "mpt_immutable_require_auth"),
916 (0x08, "mpt_immutable_can_escrow"),
917 (0x10, "mpt_immutable_can_trade"),
918 (0x20, "mpt_immutable_can_transfer"),
919 (0x40, "mpt_immutable_can_clawback"),
920 (0x80, "mpt_immutable_can_hold_confidential_balance"),
921 (0x0001_0000, "mpt_immutable_metadata"),
922 (0x0002_0000, "mpt_immutable_transfer_fee"),
923];
924
925fn mpt_issuance(account: &[u8; 20], node: &Map<String, Value>, issuer: &Value) -> Value {
926 let mut out = Map::new();
927 let seq = node
929 .get("Sequence")
930 .and_then(Value::as_u64)
931 .and_then(|s| u32::try_from(s).ok())
932 .unwrap_or(0);
933 let mut id = seq.to_be_bytes().to_vec();
934 id.extend_from_slice(account);
935 out.insert("mpt_issuance_id".into(), json!(hex::encode_upper(id)));
936 out.insert("issuer".into(), issuer.clone());
937 copy(&mut out, node, "Sequence", "sequence");
938 copy(&mut out, node, "TransferFee", "transfer_fee");
939 copy(&mut out, node, "AssetScale", "asset_scale");
940 copy(&mut out, node, "MaximumAmount", "maximum_amount");
941 copy(&mut out, node, "OutstandingAmount", "outstanding_amount");
942 copy(&mut out, node, "LockedAmount", "locked_amount");
943 copy(&mut out, node, "MPTokenMetadata", "mptoken_metadata");
944 copy(&mut out, node, "DomainID", "domain_id");
945 flags(
946 &mut out,
947 node.get("Flags").and_then(Value::as_u64).unwrap_or(0),
948 &MPT_ISSUANCE_FLAGS,
949 );
950 if let Some(bits) = node.get("ImmutableFlags").and_then(Value::as_u64) {
951 flags(&mut out, bits, &MPT_IMMUTABLE_FLAGS);
952 }
953 copy(
954 &mut out,
955 node,
956 "ConfidentialOutstandingAmount",
957 "confidential_outstanding_amount",
958 );
959 copy(
960 &mut out,
961 node,
962 "IssuerEncryptionKey",
963 "issuer_encryption_key",
964 );
965 copy(
966 &mut out,
967 node,
968 "AuditorEncryptionKey",
969 "auditor_encryption_key",
970 );
971 Value::Object(out)
972}
973
974fn mptoken(key: &[u8; 32], node: &Map<String, Value>) -> Value {
975 let mut out = Map::new();
976 out.insert("mpt_id".into(), json!(hex::encode_upper(key)));
977 copy(&mut out, node, "Account", "account");
978 copy(&mut out, node, "MPTokenIssuanceID", "mpt_issuance_id");
979 out.insert(
981 "mpt_amount".into(),
982 node.get("MPTAmount").cloned().unwrap_or_else(|| json!("0")),
983 );
984 copy(&mut out, node, "LockedAmount", "locked_amount");
985 flags(
986 &mut out,
987 node.get("Flags").and_then(Value::as_u64).unwrap_or(0),
988 &[(0x01, "mpt_locked"), (0x02, "mpt_authorized")],
989 );
990 for (field, name) in [
991 ("ConfidentialBalanceInbox", "confidential_balance_inbox"),
992 (
993 "ConfidentialBalanceSpending",
994 "confidential_balance_spending",
995 ),
996 ("ConfidentialBalanceVersion", "confidential_balance_version"),
997 ("IssuerEncryptedBalance", "issuer_encrypted_balance"),
998 ("AuditorEncryptedBalance", "auditor_encrypted_balance"),
999 ("HolderEncryptionKey", "holder_encryption_key"),
1000 ] {
1001 copy(&mut out, node, field, name);
1002 }
1003 Value::Object(out)
1004}
1005
1006fn offer(key: &[u8; 32], node: &Map<String, Value>) -> Res<Value> {
1007 for f in ["TakerPays", "TakerGets", "BookDirectory"] {
1008 if !node.contains_key(f) {
1009 return Err(corrupt(key, &format!("offer without {f}")));
1010 }
1011 }
1012 let mut o = Map::new();
1013 o.insert("seq".into(), json!(u32_field(node, "Sequence")));
1014 o.insert("flags".into(), json!(u32_field(node, "Flags")));
1015 o.insert(
1016 "quality".into(),
1017 json!(quality_text(&h256(node, "BookDirectory"))),
1018 );
1019 if let Some(e) = node.get("Expiration") {
1020 o.insert("expiration".into(), e.clone());
1021 }
1022 for (out, field) in [("taker_pays", "TakerPays"), ("taker_gets", "TakerGets")] {
1023 o.insert(out.into(), node[field].clone());
1024 }
1025 Ok(Value::Object(o))
1026}
1027
1028#[cfg(test)]
1029mod tests {
1030 use super::*;
1031
1032 #[test]
1034 fn malformed_account_is_spelled_out_like_clio() {
1035 let e = spelled_out(account_id(&json!("rBadAddress")).unwrap_err());
1036 assert_eq!(
1037 (e.error, e.code, e.message.as_str()),
1038 ("actMalformed", 35, "Account malformed.")
1039 );
1040 let other = spelled_out(invalid_params("Invalid marker."));
1041 assert_eq!(other.message, "Invalid marker.");
1042 }
1043
1044 #[test]
1047 fn missing_required_fields_are_corrupt_state() {
1048 let me = [1u8; 20];
1049 let amount = |issuer: &[u8; 20], v: &str| json!({"currency": "USD", "issuer": xrpl_json::account(issuer), "value": v});
1050 let mut node = Map::new();
1051 node.insert("Flags".into(), json!(0));
1052 node.insert("LowLimit".into(), amount(&me, "10"));
1053 node.insert("HighLimit".into(), amount(&[2; 20], "0"));
1054 node.insert("Balance".into(), amount(&[0; 20], "5"));
1055 let k = [7u8; 32];
1056 let got = line(&k, &node, &me, None, false).unwrap().unwrap();
1057 assert_eq!(got["balance"], "5");
1058 let mut broken = node.clone();
1059 broken.remove("Balance");
1060 let e = line(&k, &broken, &me, None, false).unwrap_err();
1061 assert!(e.message.starts_with("corrupt_state"), "{}", e.message);
1062 let mut broken = node;
1063 broken.remove("HighLimit");
1064 assert!(line(&k, &broken, &me, None, false).is_err());
1065 assert!(
1066 offer(&k, &Map::new())
1067 .unwrap_err()
1068 .message
1069 .contains("TakerPays")
1070 );
1071 }
1072
1073 #[test]
1074 fn cursor_round_trip_and_errors() {
1075 let mut p = Map::new();
1076 let k = [0xAB; 32];
1077 p.insert("marker".into(), json!(cursor_text(&k, 7)));
1078 assert_eq!(parse_cursor(&p).unwrap(), Some((k, 7)));
1079 p.insert("marker".into(), json!("AB,1"));
1080 assert_eq!(parse_cursor(&p).unwrap_err().message, "Malformed cursor.");
1081 p.insert("marker".into(), json!(1));
1082 assert_eq!(parse_cursor(&p).unwrap_err().message, "markerNotString");
1083 }
1084
1085 #[test]
1086 fn negation_and_quality() {
1087 assert_eq!(negate("0"), "0");
1088 assert_eq!(negate("-1.5"), "1.5");
1089 assert_eq!(negate("2e-30"), "-2e-30");
1090 let mut book = [0u8; 32];
1092 book[24..].copy_from_slice(&((85u64 << 56) | 1_000_000_000_000_000).to_be_bytes());
1093 assert_eq!(quality_text(&book), "1");
1094 }
1095
1096 #[test]
1097 fn type_names_like_clio() {
1098 assert_eq!(kind_of("state").map(|t| t.0), Some("RippleState"));
1099 assert_eq!(kind_of("ripplestate").map(|t| t.0), Some("RippleState"));
1100 assert!(kind_of("nope").is_none());
1101 let mut p = Map::new();
1102 p.insert("type".into(), json!("fee"));
1103 assert!(type_filter(&p, true).is_err());
1104 assert_eq!(type_filter(&p, false).unwrap(), Some("FeeSettings"));
1105 }
1106}