1use std::collections::HashMap;
11use std::sync::OnceLock;
12
13use serde_json::{Map, Value, json};
14use witness_core::keys::encode_base58;
15use witness_core::shamap::tx_id;
16use witness_core::stobject::{self, Field, types};
17
18const BASE_TEN_UINT64: [u16; 5] = [24, 25, 26, 29, 32];
21
22const GRANULAR_PERMISSIONS: [&str; 12] = [
25 "TrustlineAuthorize",
26 "TrustlineFreeze",
27 "TrustlineUnfreeze",
28 "AccountDomainSet",
29 "AccountEmailHashSet",
30 "AccountMessageKeySet",
31 "AccountTransferRateSet",
32 "AccountTickSizeSet",
33 "PaymentMint",
34 "PaymentBurn",
35 "MPTokenIssuanceLock",
36 "MPTokenIssuanceUnlock",
37];
38
39#[derive(Debug)]
41pub struct Definitions {
42 fields: HashMap<(u16, u16), String>,
43 transaction_types: HashMap<u16, String>,
44 ledger_entry_types: HashMap<u16, String>,
45 results: HashMap<i32, String>,
46 permission_value: Option<(u16, u16)>,
47}
48
49fn load() -> Result<Definitions, String> {
50 let d: Value =
51 serde_json::from_str(include_str!("../definitions.json")).map_err(|e| e.to_string())?;
52 let types = d["TYPES"].as_object().ok_or("TYPES")?;
53 let mut fields = HashMap::new();
54 let mut permission_value = None;
55 for f in d["FIELDS"].as_array().ok_or("FIELDS")? {
56 let (Some(name), Some(info)) = (f[0].as_str(), f[1].as_object()) else {
57 continue;
58 };
59 let (Some(t), Some(nth)) = (
60 info.get("type")
61 .and_then(Value::as_str)
62 .and_then(|t| types.get(t))
63 .and_then(Value::as_i64),
64 info.get("nth").and_then(Value::as_i64),
65 ) else {
66 continue;
67 };
68 if !(1..=255).contains(&t) || !(1..=255).contains(&nth) {
69 continue;
70 }
71 let key = (t as u16, nth as u16);
72 if name == "PermissionValue" {
73 permission_value = Some(key);
74 }
75 fields.insert(key, name.to_owned());
76 }
77 let invert = |k: &str| -> Result<HashMap<i64, String>, String> {
78 Ok(d[k]
79 .as_object()
80 .ok_or(k.to_owned())?
81 .iter()
82 .filter_map(|(n, v)| v.as_i64().map(|v| (v, n.clone())))
83 .collect())
84 };
85 let u16s = |m: HashMap<i64, String>| {
86 m.into_iter()
87 .filter_map(|(k, v)| u16::try_from(k).ok().map(|k| (k, v)))
88 .collect()
89 };
90 Ok(Definitions {
91 fields,
92 transaction_types: u16s(invert("TRANSACTION_TYPES")?),
93 ledger_entry_types: u16s(invert("LEDGER_ENTRY_TYPES")?),
94 results: invert("TRANSACTION_RESULTS")?
95 .into_iter()
96 .filter_map(|(k, v)| i32::try_from(k).ok().map(|k| (k, v)))
97 .collect(),
98 permission_value,
99 })
100}
101
102pub fn definitions() -> &'static Definitions {
103 static DEFS: OnceLock<Definitions> = OnceLock::new();
104 DEFS.get_or_init(|| match load() {
105 Ok(d) => d,
106 Err(e) => panic!("definitions.json: {e}"),
108 })
109}
110
111impl Definitions {
112 pub fn transaction_type(&self, code: u16) -> Option<&str> {
113 self.transaction_types.get(&code).map(String::as_str)
114 }
115
116 pub fn is_transaction_type(&self, name: &str) -> bool {
118 self.transaction_types
119 .values()
120 .any(|t| t.eq_ignore_ascii_case(name))
121 }
122
123 pub fn knows_field(&self, type_code: u16, field_code: u16) -> bool {
125 self.fields.contains_key(&(type_code, field_code))
126 }
127
128 pub fn ledger_entry_type(&self, code: u16) -> Option<&str> {
129 self.ledger_entry_types.get(&code).map(String::as_str)
130 }
131
132 pub fn result(&self, code: i32) -> Option<&str> {
133 self.results.get(&code).map(String::as_str)
134 }
135}
136
137pub fn account(a: &[u8]) -> String {
138 encode_base58(0, a)
139}
140
141fn hex_upper(b: &[u8]) -> String {
142 hex::encode_upper(b)
143}
144
145fn be_u64(b: &[u8]) -> u64 {
146 let mut a = [0u8; 8];
147 a.copy_from_slice(&b[..8]);
148 u64::from_be_bytes(a)
149}
150
151pub fn currency(c: &[u8]) -> String {
153 const ISO: &str =
154 "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789<>(){}[]|?!@#$%^&*";
155 if c.iter().all(|b| *b == 0) {
156 return "XRP".into();
157 }
158 let mut no_currency = [0u8; 20];
159 no_currency[19] = 1;
160 if c == no_currency {
161 return "1".into();
162 }
163 let iso_bits_zero = c[..12].iter().all(|b| *b == 0) && c[15..].iter().all(|b| *b == 0);
164 if iso_bits_zero {
165 let code = &c[12..15];
166 if code != b"XRP" && code.iter().all(|b| ISO.as_bytes().contains(b)) {
167 return String::from_utf8_lossy(code).into_owned();
168 }
169 }
170 hex_upper(c)
171}
172
173pub fn iou_text(negative: bool, mantissa: u64, offset: i32) -> String {
175 if mantissa == 0 {
176 return "0".into();
177 }
178 let raw = mantissa.to_string();
179 let mut ret = String::new();
180 if negative {
181 ret.push('-');
182 }
183 let scientific = offset != 0 && !(-25..=-5).contains(&offset);
184 if scientific {
185 ret.push_str(&raw);
186 ret.push('e');
187 ret.push_str(&offset.to_string());
188 return ret;
189 }
190 decimal(&mut ret, &raw, offset as isize + 43, 27, 23);
191 ret
192}
193
194fn decimal(ret: &mut String, raw: &str, offset: isize, pad_prefix: usize, pad_suffix: usize) {
198 let val = format!("{}{raw}{}", "0".repeat(pad_prefix), "0".repeat(pad_suffix));
199 let v = val.as_bytes();
200 let offset = offset.clamp(0, v.len() as isize) as usize;
201 let mut pre_from = 0;
202 if offset > pad_prefix {
203 pre_from = pad_prefix;
204 }
205 while pre_from < offset && v[pre_from] == b'0' {
206 pre_from += 1;
207 }
208 let mut post_to = v.len();
209 if post_to - offset > pad_suffix {
210 post_to -= pad_suffix;
211 }
212 while post_to > offset && v[post_to - 1] == b'0' {
213 post_to -= 1;
214 }
215 if pre_from == offset {
216 ret.push('0');
217 } else {
218 ret.push_str(&val[pre_from..offset]);
219 }
220 if post_to != offset {
221 ret.push('.');
222 ret.push_str(&val[offset..post_to]);
223 }
224}
225
226pub fn amount(v: &[u8]) -> Value {
228 match v.len() {
229 48 => {
230 let x = be_u64(v);
231 let negative = x & 0x4000_0000_0000_0000 == 0;
232 let mantissa = x & ((1 << 54) - 1);
233 let offset = ((x >> 54) & 0xFF) as i32 - 97;
234 json!({
235 "currency": currency(&v[8..28]),
236 "issuer": account(&v[28..48]),
237 "value": iou_text(negative && mantissa != 0, mantissa, offset),
238 })
239 }
240 33 => {
241 let negative = v[0] & 0x40 == 0;
242 let value = be_u64(&v[1..9]);
243 let text = if negative && value != 0 {
244 format!("-{value}")
245 } else {
246 value.to_string()
247 };
248 json!({ "mpt_issuance_id": hex_upper(&v[9..33]), "value": text })
249 }
250 _ => {
251 let x = be_u64(v);
252 let drops = x & 0x3FFF_FFFF_FFFF_FFFF;
253 let negative = x & 0x4000_0000_0000_0000 == 0 && drops != 0;
254 Value::String(if negative {
255 format!("-{drops}")
256 } else {
257 drops.to_string()
258 })
259 }
260 }
261}
262
263pub fn number(v: &[u8]) -> String {
266 let m = i64::from_be_bytes(v[..8].try_into().unwrap_or_default());
267 let e = i32::from_be_bytes(v[8..12].try_into().unwrap_or_default());
268 number_text(m < 0, u128::from(m.unsigned_abs()), e, 15)
269}
270
271pub(crate) fn number_text(negative: bool, mantissa: u128, exponent: i32, range_log: i32) -> String {
274 if mantissa == 0 {
275 return "0".into();
276 }
277 let min = 10u128.pow(range_log as u32);
278 let max = min * 10 - 1;
279 let (mut mantissa, mut exponent) = (mantissa, exponent);
280 while mantissa < min {
281 mantissa *= 10;
282 exponent -= 1;
283 }
284 while mantissa > max {
285 mantissa /= 10;
286 exponent += 1;
287 }
288 let mut ret = String::new();
289 if negative {
290 ret.push('-');
291 }
292 if exponent != 0 && (exponent < -(range_log + 10) || exponent > -(range_log - 10)) {
293 while mantissa % 10 == 0 {
294 mantissa /= 10;
295 exponent += 1;
296 }
297 ret.push_str(&mantissa.to_string());
298 if exponent != 0 {
299 ret.push('e');
300 ret.push_str(&exponent.to_string());
301 }
302 return ret;
303 }
304 let pad_prefix = (range_log + 12) as usize;
305 let pad_suffix = (range_log + 8) as usize;
306 let offset = exponent as isize + pad_prefix as isize + range_log as isize + 1;
307 decimal(
308 &mut ret,
309 &mantissa.to_string(),
310 offset,
311 pad_prefix,
312 pad_suffix,
313 );
314 ret
315}
316
317fn issue(v: &[u8]) -> Value {
318 match v.len() {
319 20 => json!({ "currency": "XRP" }),
320 44 => {
321 let mut id = Vec::with_capacity(24);
325 id.extend(v[40..44].iter().rev());
326 id.extend_from_slice(&v[..20]);
327 json!({ "mpt_issuance_id": hex_upper(&id) })
328 }
329 _ => json!({ "currency": currency(&v[..20]), "issuer": account(&v[20..40]) }),
330 }
331}
332
333fn pathset(v: &[u8]) -> Value {
334 let mut paths = Vec::new();
335 let mut path = Vec::new();
336 let mut at = 0;
337 while at < v.len() {
338 let t = v[at];
339 at += 1;
340 match t {
341 0x00 => break,
342 0xFF => {
343 paths.push(Value::Array(std::mem::take(&mut path)));
344 continue;
345 }
346 _ => {}
347 }
348 let mut step = Map::new();
349 step.insert("type".into(), json!(t));
350 let take20 = |at: &mut usize| {
351 let s = &v[*at..(*at + 20).min(v.len())];
352 *at += 20;
353 s
354 };
355 if t & 0x01 != 0 {
356 step.insert("account".into(), json!(account(take20(&mut at))));
357 }
358 if t & 0x10 != 0 {
359 step.insert("currency".into(), json!(currency(take20(&mut at))));
360 }
361 if t & 0x20 != 0 {
362 step.insert("issuer".into(), json!(account(take20(&mut at))));
363 }
364 path.push(Value::Object(step));
365 }
366 paths.push(Value::Array(path));
367 Value::Array(paths)
368}
369
370fn xchain_bridge(v: &[u8]) -> Value {
371 let issue_len = |at: usize| -> usize {
374 if v[at..at + 20].iter().all(|b| *b == 0) {
375 20
376 } else {
377 40
378 }
379 };
380 let mut at = 1;
381 let locking_door = account(&v[at..at + 20]);
382 at += 20;
383 let l1 = issue_len(at);
384 let locking_issue = issue(&v[at..at + l1]);
385 at += l1 + 1;
386 let issuing_door = account(&v[at..at + 20]);
387 at += 20;
388 let l2 = issue_len(at);
389 let issuing_issue = issue(&v[at..at + l2]);
390 json!({
391 "LockingChainDoor": locking_door,
392 "LockingChainIssue": locking_issue,
393 "IssuingChainDoor": issuing_door,
394 "IssuingChainIssue": issuing_issue,
395 })
396}
397
398fn field_value(d: &Definitions, f: &Field<'_>) -> Result<Value, String> {
399 let v = f.value;
400 let id = f.id;
401 Ok(match id.type_code {
402 types::UINT8 => {
403 if (id.type_code, id.field_code) == (types::UINT8, 3) {
404 match d.result(i32::from(v[0])) {
405 Some(n) => json!(n),
406 None => json!(v[0]),
407 }
408 } else {
409 json!(v[0])
410 }
411 }
412 types::UINT16 => {
413 let n = u16::from_be_bytes([v[0], v[1]]);
414 let name = match id.field_code {
415 1 => d.ledger_entry_type(n),
416 2 => d.transaction_type(n),
417 _ => None,
418 };
419 name.map_or(json!(n), |s| json!(s))
420 }
421 types::UINT32 => {
422 let n = u32::from_be_bytes([v[0], v[1], v[2], v[3]]);
423 if Some((id.type_code, id.field_code)) == d.permission_value {
424 let name = if n > 65536 {
425 GRANULAR_PERMISSIONS.get((n - 65537) as usize).copied()
426 } else if n > 0 {
427 u16::try_from(n - 1)
428 .ok()
429 .and_then(|t| d.transaction_type(t))
430 } else {
431 None
432 };
433 if let Some(name) = name {
434 return Ok(json!(name));
435 }
436 }
437 json!(n)
438 }
439 types::UINT64 => {
440 let n = be_u64(v);
441 if BASE_TEN_UINT64.contains(&id.field_code) {
442 json!(n.to_string())
443 } else {
444 json!(format!("{n:x}"))
445 }
446 }
447 types::INT32 => json!(i32::from_be_bytes([v[0], v[1], v[2], v[3]])),
448 types::INT64 => json!(be_u64(v) as i64),
449 types::HASH128
450 | types::HASH160
451 | types::HASH192
452 | types::HASH256
453 | types::UINT384
454 | types::UINT512
455 | types::UINT96
456 | types::BLOB => json!(hex_upper(v)),
457 types::AMOUNT => amount(v),
458 types::ACCOUNT => json!(account(v)),
459 types::NUMBER => json!(number(v)),
460 types::OBJECT => object(d, v)?,
461 types::ARRAY => {
462 let mut out = Vec::new();
463 for item in stobject::items(v).map_err(|e| e.to_string())? {
464 let mut m = Map::new();
465 m.insert(name(d, &item)?, object(d, item.value)?);
466 out.push(Value::Object(m));
467 }
468 Value::Array(out)
469 }
470 types::PATHSET => pathset(v),
471 types::VECTOR256 => Value::Array(v.chunks(32).map(|c| json!(hex_upper(c))).collect()),
472 types::ISSUE => issue(v),
473 types::XCHAIN_BRIDGE => xchain_bridge(v),
474 types::CURRENCY => json!(currency(v)),
475 t => return Err(format!("field type {t} is not supported")),
476 })
477}
478
479fn name(d: &Definitions, f: &Field<'_>) -> Result<String, String> {
480 d.fields
481 .get(&(f.id.type_code, f.id.field_code))
482 .cloned()
483 .ok_or_else(|| format!("unknown field {}:{}", f.id.type_code, f.id.field_code))
484}
485
486pub fn object(d: &Definitions, buf: &[u8]) -> Result<Value, String> {
488 let mut m = Map::new();
489 for f in stobject::fields(buf).map_err(|e| e.to_string())? {
490 m.insert(name(d, &f)?, field_value(d, &f)?);
491 }
492 Ok(Value::Object(m))
493}
494
495pub fn transaction(tx: &[u8]) -> Result<Map<String, Value>, String> {
497 let Value::Object(mut m) = object(definitions(), tx)? else {
498 return Err("transaction is not an object".into());
499 };
500 m.insert("hash".into(), json!(hex_upper(&tx_id(tx))));
501 Ok(m)
502}
503
504pub fn ledger_entry(key: &[u8; 32], data: &[u8]) -> Result<Map<String, Value>, String> {
507 let Value::Object(mut m) = object(definitions(), data)? else {
508 return Err("state object is not an object".into());
509 };
510 m.insert("index".into(), json!(hex_upper(key)));
511 if m.get("LedgerEntryType").and_then(Value::as_str) == Some("MPTokenIssuance")
512 && let Some(id) = mpt_issuance_id(&m)
513 {
514 m.insert("mpt_issuance_id".into(), json!(id));
515 }
516 Ok(m)
517}
518
519fn mpt_issuance_id(m: &Map<String, Value>) -> Option<String> {
520 let seq = u32::try_from(m.get("Sequence")?.as_u64()?).ok()?;
521 let (0, issuer) = witness_core::keys::decode_base58(m.get("Issuer")?.as_str()?)? else {
522 return None;
523 };
524 let mut id = seq.to_be_bytes().to_vec();
525 id.extend(issuer);
526 Some(hex_upper(&id))
527}
528
529pub fn metadata(meta: &[u8]) -> Result<Map<String, Value>, String> {
530 match object(definitions(), meta)? {
531 Value::Object(m) => Ok(m),
532 _ => Err("metadata is not an object".into()),
533 }
534}
535
536#[cfg(test)]
537mod tests {
538 use super::*;
539
540 #[test]
541 fn definitions_load() {
542 let d = load().unwrap();
543 assert_eq!(d.transaction_type(0), Some("Payment"));
544 assert_eq!(d.ledger_entry_type(0x61), Some("AccountRoot"));
545 assert_eq!(d.result(0), Some("tesSUCCESS"));
546 assert_eq!(d.fields.get(&(8, 1)).map(String::as_str), Some("Account"));
547 }
548
549 #[test]
550 fn amounts_render_like_xrpld() {
551 let mut xrp = (0x4000_0000_0000_0000u64 | 1000).to_be_bytes().to_vec();
553 assert_eq!(amount(&xrp), json!("1000"));
554 xrp = 1000u64.to_be_bytes().to_vec();
555 assert_eq!(amount(&xrp), json!("-1000"));
556 let enc = |neg: bool, m: u64, e: i32| {
558 let mut x = 0x8000_0000_0000_0000u64 | m | (((e + 97) as u64) << 54);
559 if !neg {
560 x |= 0x4000_0000_0000_0000;
561 }
562 let mut v = x.to_be_bytes().to_vec();
563 let mut cur = [0u8; 20];
564 cur[12..15].copy_from_slice(b"USD");
565 v.extend(cur);
566 v.extend([1u8; 20]);
567 v
568 };
569 let text = |v: &Vec<u8>| amount(v)["value"].as_str().unwrap().to_owned();
570 assert_eq!(text(&enc(false, 1_500_000_000_000_000, -15)), "1.5");
571 assert_eq!(text(&enc(true, 1_000_000_000_000_000, -15)), "-1");
572 assert_eq!(
573 text(&enc(false, 1_234_567_890_123_456, -3)),
574 "1234567890123456e-3"
575 );
576 assert_eq!(
577 text(&enc(false, 1_000_000_000_000_000, -30)),
578 "1000000000000000e-30"
579 );
580 assert_eq!(text(&enc(false, 1_200_000_000_000_000, -20)), "0.000012");
581 assert_eq!(amount(&enc(false, 1, -15))["currency"], json!("USD"));
582 }
583
584 #[test]
585 fn currency_codes() {
586 let mut c = [0u8; 20];
587 assert_eq!(currency(&c), "XRP");
588 c[12..15].copy_from_slice(b"EUR");
589 assert_eq!(currency(&c), "EUR");
590 c[0] = 0x53;
591 assert_eq!(currency(&c).len(), 40);
592 }
593
594 #[test]
595 fn mpt_issue_like_xrpld() {
596 let v = hex::decode(concat!(
598 "934C43A14646B54DF3F161456697284B593CBBA4",
599 "0000000000000000000000000000000000000001",
600 "D6100200",
601 ))
602 .unwrap();
603 assert_eq!(
604 issue(&v),
605 json!({"mpt_issuance_id": "000210D6934C43A14646B54DF3F161456697284B593CBBA4"})
606 );
607 }
608
609 #[test]
610 fn numbers() {
611 let enc = |m: i64, e: i32| {
612 let mut v = m.to_be_bytes().to_vec();
613 v.extend(e.to_be_bytes());
614 v
615 };
616 assert_eq!(number(&enc(15, -1)), "1.5");
617 assert_eq!(number(&enc(-2, 0)), "-2");
618 assert_eq!(number(&enc(0, 5)), "0");
619 }
620}