1use std::collections::{HashMap, HashSet};
20use std::sync::Arc;
21use std::sync::Mutex;
22use std::sync::atomic::{AtomicU64, Ordering};
23use std::time::Duration;
24
25use serde_json::{Map, Value, json};
26use tokio::sync::mpsc;
27use tracing::warn;
28use witness_core::ledger::LedgerHeader;
29
30use crate::api::{
31 Engine, Res, RpcError, account_id, currency_code, internal, invalid_params, keylet, rpc_err,
32 time_iso,
33};
34use crate::index::{AccountId, affected_accounts};
35use crate::xrpl_json;
36
37pub const QUEUE: usize = 1500;
39const POLL: Duration = Duration::from_millis(250);
41const MAX_BEHIND: u32 = 256;
43pub const MAX_ACCOUNTS: usize = 10_000;
46
47const LSF_GLOBAL_FREEZE: u32 = 0x0040_0000;
48const LSF_LOW_FREEZE: u32 = 0x0040_0000;
49const LSF_HIGH_FREEZE: u32 = 0x0080_0000;
50
51#[derive(Debug)]
52struct Sub {
53 api: u32,
54 ledger: bool,
55 ledger_after: u32,
58 transactions: bool,
59 book_changes: bool,
60 validations: bool,
61 manifests: bool,
62 accounts: HashSet<AccountId>,
63 out: mpsc::Sender<String>,
64}
65
66#[derive(Debug, Default)]
68pub struct Hub {
69 subs: Mutex<HashMap<u64, Sub>>,
70 next: AtomicU64,
71 dropped: AtomicU64,
73}
74
75#[derive(Debug, Default, PartialEq, Eq)]
77pub struct HubStats {
78 pub ledger: u64,
79 pub transactions: u64,
80 pub book_changes: u64,
81 pub validations: u64,
82 pub manifests: u64,
83 pub account_sessions: u64,
85 pub accounts: u64,
86 pub dropped: u64,
87}
88
89#[derive(Debug, Default, PartialEq, Eq)]
91pub struct Request {
92 pub ledger: bool,
93 pub transactions: bool,
94 pub book_changes: bool,
95 pub validations: bool,
96 pub manifests: bool,
97 pub accounts: Vec<AccountId>,
98}
99
100fn not_supported(what: &str) -> RpcError {
101 rpc_err(
102 "notSupported",
103 75,
104 format!("Operation not supported: {what}."),
105 )
106}
107
108pub fn parse(p: &Map<String, Value>) -> Result<Request, RpcError> {
110 let mut r = Request::default();
111 match p.get("streams") {
112 None => {}
113 Some(Value::Array(a)) => {
114 for s in a {
115 match s.as_str() {
116 None => return Err(invalid_params("streamNotString")),
117 Some("ledger") => r.ledger = true,
118 Some("transactions") => r.transactions = true,
119 Some("book_changes") => r.book_changes = true,
120 Some("validations") => r.validations = true,
121 Some("manifests") => r.manifests = true,
122 Some(s @ "transactions_proposed") => return Err(not_supported(s)),
123 Some(_) => return Err(rpc_err("malformedStream", 71, "Stream malformed.")),
124 }
125 }
126 }
127 Some(_) => return Err(invalid_params("streamsNotArray")),
128 }
129 match p.get("accounts") {
130 None => {}
131 Some(Value::Array(a)) if a.is_empty() => {
132 return Err(rpc_err("actMalformed", 35, "accounts malformed."));
133 }
134 Some(Value::Array(a)) if a.len() > MAX_ACCOUNTS => {
135 return Err(invalid_params("accountsTooMany"));
136 }
137 Some(Value::Array(a)) => {
138 for v in a {
139 if !v.is_string() {
140 return Err(invalid_params("accounts'sItemNotString"));
141 }
142 r.accounts.push(
143 account_id(v)
144 .map_err(|_| rpc_err("actMalformed", 35, "accounts'sItemMalformed"))?,
145 );
146 }
147 }
148 Some(_) => return Err(invalid_params("accountsNotArray")),
149 }
150 for k in ["accounts_proposed", "books"] {
151 if p.contains_key(k) {
152 return Err(not_supported(k));
153 }
154 }
155 Ok(r)
156}
157
158impl Hub {
159 pub fn join(&self) -> (u64, mpsc::Receiver<String>) {
161 let id = self.next.fetch_add(1, Ordering::Relaxed);
162 let (out, rx) = mpsc::channel(QUEUE);
163 self.lock().insert(
164 id,
165 Sub {
166 api: 2,
167 ledger: false,
168 ledger_after: 0,
169 transactions: false,
170 book_changes: false,
171 validations: false,
172 manifests: false,
173 accounts: HashSet::new(),
174 out,
175 },
176 );
177 (id, rx)
178 }
179
180 pub fn leave(&self, id: u64) {
181 self.lock().remove(&id);
182 }
183
184 pub fn stats(&self) -> HubStats {
185 let g = self.lock();
186 let mut st = HubStats {
187 dropped: self.dropped.load(Ordering::Relaxed),
188 ..HubStats::default()
189 };
190 for s in g.values() {
191 st.ledger += u64::from(s.ledger);
192 st.transactions += u64::from(s.transactions);
193 st.book_changes += u64::from(s.book_changes);
194 st.validations += u64::from(s.validations);
195 st.manifests += u64::from(s.manifests);
196 st.account_sessions += u64::from(!s.accounts.is_empty());
197 st.accounts += s.accounts.len() as u64;
198 }
199 st
200 }
201
202 pub fn accounts_of(&self, id: u64) -> usize {
204 self.lock().get(&id).map_or(0, |s| s.accounts.len())
205 }
206
207 pub fn subscribe(&self, id: u64, r: &Request, api: u32, top: u32) {
209 if let Some(s) = self.lock().get_mut(&id) {
210 s.api = api;
211 if r.ledger {
212 s.ledger_after = top;
213 }
214 s.ledger |= r.ledger;
215 s.transactions |= r.transactions;
216 s.book_changes |= r.book_changes;
217 s.validations |= r.validations;
218 s.manifests |= r.manifests;
219 s.accounts.extend(r.accounts.iter().copied());
220 }
221 }
222
223 pub fn unsubscribe(&self, id: u64, r: &Request) {
224 if let Some(s) = self.lock().get_mut(&id) {
225 s.ledger &= !r.ledger;
226 s.transactions &= !r.transactions;
227 s.book_changes &= !r.book_changes;
228 s.validations &= !r.validations;
229 s.manifests &= !r.manifests;
230 for a in &r.accounts {
231 s.accounts.remove(a);
232 }
233 }
234 }
235
236 fn lock(&self) -> std::sync::MutexGuard<'_, HashMap<u64, Sub>> {
237 self.subs.lock().unwrap_or_else(|p| p.into_inner())
238 }
239
240 fn wants_anything(&self) -> bool {
241 self.lock()
242 .values()
243 .any(|s| s.ledger || s.transactions || s.book_changes || !s.accounts.is_empty())
244 }
245
246 fn deliver(&self, targets: &[(u64, String)]) {
249 let mut dead = Vec::new();
250 {
251 let g = self.lock();
252 for (id, msg) in targets {
253 if let Some(s) = g.get(id)
254 && s.out.try_send(msg.clone()).is_err()
255 {
256 dead.push(*id);
257 }
258 }
259 }
260 for id in dead {
261 self.dropped.fetch_add(1, Ordering::Relaxed);
262 warn!("subscriptions: session {id} can't keep up reading, disconnected");
263 self.leave(id);
264 }
265 }
266}
267
268const SEEN_STREAM_MESSAGES: usize = 4096;
271
272impl Hub {
273 fn node_message(
276 &self,
277 text: &str,
278 seen: &mut (HashSet<String>, std::collections::VecDeque<String>),
279 ) {
280 let Ok(v) = serde_json::from_str::<Value>(text) else {
281 return;
282 };
283 let (validation, key) = match v.get("type").and_then(Value::as_str) {
284 Some("validationReceived") => (true, v.get("data")),
285 Some("manifestReceived") => (false, v.get("manifest")),
286 _ => return,
287 };
288 let Some(key) = key.and_then(Value::as_str) else {
289 return;
290 };
291 if !seen.0.insert(key.to_owned()) {
292 return;
293 }
294 seen.1.push_back(key.to_owned());
295 if seen.1.len() > SEEN_STREAM_MESSAGES
296 && let Some(old) = seen.1.pop_front()
297 {
298 seen.0.remove(&old);
299 }
300 let targets: Vec<(u64, String)> = self
301 .lock()
302 .iter()
303 .filter(|(_, s)| {
304 if validation {
305 s.validations
306 } else {
307 s.manifests
308 }
309 })
310 .map(|(id, _)| (*id, text.to_owned()))
311 .collect();
312 if !targets.is_empty() {
313 self.deliver(&targets);
314 }
315 }
316}
317
318pub async fn forward_streams(hub: Arc<Hub>, mut rx: tokio::sync::broadcast::Receiver<Arc<str>>) {
320 use tokio::sync::broadcast::error::RecvError;
321 let mut seen = (HashSet::new(), std::collections::VecDeque::new());
322 loop {
323 match rx.recv().await {
324 Ok(m) => hub.node_message(&m, &mut seen),
325 Err(RecvError::Lagged(n)) => {
328 warn!("subscriptions: {n} validation stream messages skipped")
329 }
330 Err(RecvError::Closed) => return,
331 }
332 }
333}
334
335impl Engine {
336 pub(crate) fn ledger_stream(
338 &self,
339 seq: u32,
340 txn_count: Option<usize>,
341 ) -> Res<Map<String, Value>> {
342 let (min, max) = self.range()?;
343 let (_, h) = self.header(seq)?;
344 let (base, reserve, inc) = self
345 .fee_drops(seq)?
346 .ok_or_else(|| internal(format!("no FeeSettings for ledger {seq}")))?;
347 let mut m = Map::new();
348 if txn_count.is_some() {
349 m.insert("type".into(), json!("ledgerClosed"));
350 }
351 m.insert("ledger_index".into(), json!(seq));
352 m.insert("ledger_hash".into(), json!(hex::encode_upper(h.hash())));
353 m.insert("ledger_time".into(), json!(h.close_time));
354 m.insert("fee_base".into(), json!(base));
355 m.insert("reserve_base".into(), json!(reserve));
356 m.insert("reserve_inc".into(), json!(inc));
357 m.insert("validated_ledgers".into(), json!(format!("{min}-{max}")));
358 if let Some(n) = txn_count {
359 m.insert("txn_count".into(), json!(n));
360 }
361 m.insert("network_id".into(), json!(self.network_id));
362 Ok(m)
363 }
364
365 pub(crate) fn tx_stream(
367 &self,
368 seq: u32,
369 h: &LedgerHeader,
370 tx: &[u8],
371 meta: &[u8],
372 api: u32,
373 ) -> Res<Map<String, Value>> {
374 let e = self.expand(tx, meta, seq, api, false, true)?;
375 let mut t = e.tx;
376 t.insert("date".into(), json!(h.close_time));
377 if t.get("TransactionType").and_then(Value::as_str) == Some("OfferCreate")
378 && let Some(f) = self.owner_funds(seq, &t)?
379 {
380 t.insert("owner_funds".into(), json!(f));
381 }
382 let result = e
383 .meta
384 .get("TransactionResult")
385 .and_then(Value::as_str)
386 .unwrap_or("")
387 .to_owned();
388 let mut m = Map::new();
389 if api < 2 {
390 m.insert("transaction".into(), Value::Object(t));
391 } else {
392 let hash = t.remove("hash").unwrap_or(Value::Null);
393 m.insert("tx_json".into(), Value::Object(t));
394 m.insert("hash".into(), hash);
395 }
396 m.insert("meta".into(), Value::Object(e.meta));
397 if let Some(c) = self.ctid(seq, e.index) {
398 m.insert("ctid".into(), json!(c));
399 }
400 m.insert("type".into(), json!("transaction"));
401 m.insert("validated".into(), json!(true));
402 m.insert("status".into(), json!("closed"));
403 m.insert("close_time_iso".into(), json!(time_iso(h.close_time)));
404 m.insert("ledger_index".into(), json!(seq));
405 m.insert("ledger_hash".into(), json!(hex::encode_upper(h.hash())));
406 if let Some((code, message)) = crate::ter::result(&result) {
407 m.insert("engine_result_code".into(), json!(code));
408 m.insert("engine_result_message".into(), json!(message));
409 }
410 m.insert("engine_result".into(), json!(result));
411 Ok(m)
412 }
413
414 fn owner_funds(&self, seq: u32, t: &Map<String, Value>) -> Res<Option<String>> {
417 let Some(acc) = t.get("Account").and_then(|a| account_id(a).ok()) else {
418 return Ok(None);
419 };
420 let obj = |k: &[u8; 32]| -> Res<Option<Map<String, Value>>> {
421 match self.state.get(k, seq).map_err(internal)? {
422 None => Ok(None),
423 Some(d) => xrpl_json::ledger_entry(k, &d).map(Some).map_err(internal),
424 }
425 };
426 let flags =
427 |o: &Map<String, Value>| o.get("Flags").and_then(Value::as_u64).unwrap_or(0) as u32;
428 match t.get("TakerGets") {
429 Some(Value::String(_)) => {
430 let Some(root) = obj(&keylet(b'a', &[&acc]))? else {
431 return Ok(Some("0".into()));
432 };
433 let balance = root
434 .get("Balance")
435 .and_then(Value::as_str)
436 .and_then(|s| s.parse::<u64>().ok())
437 .unwrap_or(0);
438 let owners = root.get("OwnerCount").and_then(Value::as_u64).unwrap_or(0);
439 let (_, reserve, inc) = self.fee_drops(seq)?.unwrap_or((0, 0, 0));
440 let need = reserve.saturating_add(owners.saturating_mul(inc));
441 Ok(Some(balance.saturating_sub(need).to_string()))
442 }
443 Some(Value::Object(g)) => {
444 let (Some(issuer), Some(cur)) = (
445 g.get("issuer").and_then(|a| account_id(a).ok()),
446 g.get("currency")
447 .and_then(Value::as_str)
448 .and_then(currency_code),
449 ) else {
450 return Ok(None);
451 };
452 if issuer == acc {
453 return Ok(None);
454 }
455 if obj(&keylet(b'a', &[&issuer]))?
456 .is_some_and(|r| flags(&r) & LSF_GLOBAL_FREEZE != 0)
457 {
458 return Ok(Some("0".into()));
459 }
460 let (lo, hi) = if acc < issuer {
461 (acc, issuer)
462 } else {
463 (issuer, acc)
464 };
465 let Some(line) = obj(&keylet(b'r', &[&lo, &hi, &cur]))? else {
466 return Ok(Some("0".into()));
467 };
468 let freeze = if issuer > acc {
469 LSF_HIGH_FREEZE
470 } else {
471 LSF_LOW_FREEZE
472 };
473 if flags(&line) & freeze != 0 {
474 return Ok(Some("0".into()));
475 }
476 let v = line
477 .get("Balance")
478 .and_then(|b| b.get("value"))
479 .and_then(Value::as_str)
480 .unwrap_or("0");
481 Ok(Some(if acc > issuer {
482 crate::owned::negate(v)
483 } else {
484 v.to_owned()
485 }))
486 }
487 _ => Ok(None),
488 }
489 }
490}
491
492struct Wants {
494 id: u64,
495 api: u32,
496 ledger: bool,
497 transactions: bool,
498 book_changes: bool,
499 accounts: HashSet<AccountId>,
500}
501
502fn publish(engine: &Engine, hub: &Hub, seq: u32) -> Res<()> {
504 let subs: Vec<Wants> = hub
506 .lock()
507 .iter()
508 .map(|(id, s)| Wants {
509 id: *id,
510 api: s.api,
511 ledger: s.ledger && seq > s.ledger_after,
512 transactions: s.transactions,
513 book_changes: s.book_changes,
514 accounts: s.accounts.clone(),
515 })
516 .collect();
517 let l = engine.ledger(seq)?;
518 if subs.iter().any(|s| s.ledger) {
519 let msg = Value::Object(engine.ledger_stream(seq, Some(l.transactions.len()))?).to_string();
520 let targets: Vec<(u64, String)> = subs
521 .iter()
522 .filter(|s| s.ledger)
523 .map(|s| (s.id, msg.clone()))
524 .collect();
525 hub.deliver(&targets);
526 }
527 let (_, h) = engine.header(seq)?;
528 if subs
529 .iter()
530 .any(|s| s.transactions || !s.accounts.is_empty())
531 {
532 publish_transactions(engine, hub, seq, &h, &l, &subs);
533 }
534 if subs.iter().any(|s| s.book_changes) {
535 let mut m = Map::new();
536 m.insert("type".into(), json!("bookChanges"));
537 m.insert("ledger_index".into(), json!(seq));
538 m.insert("ledger_hash".into(), json!(hex::encode_upper(h.hash())));
539 m.insert("ledger_time".into(), json!(h.close_time));
540 m.insert(
541 "changes".into(),
542 Value::Array(crate::bookchanges::compute(&l.transactions)),
543 );
544 let msg = Value::Object(m).to_string();
545 let targets: Vec<(u64, String)> = subs
546 .iter()
547 .filter(|s| s.book_changes)
548 .map(|s| (s.id, msg.clone()))
549 .collect();
550 hub.deliver(&targets);
551 }
552 Ok(())
553}
554
555fn publish_transactions(
556 engine: &Engine,
557 hub: &Hub,
558 seq: u32,
559 h: &LedgerHeader,
560 l: &crate::ledger::Ledger,
561 subs: &[Wants],
562) {
563 let mut txs = Vec::with_capacity(l.transactions.len());
564 for (tx, meta) in &l.transactions {
567 match affected_accounts(meta) {
568 Ok((index, accounts)) => txs.push((index, tx, meta, accounts)),
569 Err(e) => warn!("subscriptions: ledger {seq}, transaction skipped: {e}"),
570 }
571 }
572 txs.sort_by_key(|t| t.0);
573 for (_, tx, meta, accounts) in txs {
574 let to: Vec<&Wants> = subs
575 .iter()
576 .filter(|s| s.transactions || accounts.iter().any(|a| s.accounts.contains(a)))
577 .collect();
578 if to.is_empty() {
579 continue;
580 }
581 let mut by_api: HashMap<u32, String> = HashMap::new();
582 let mut targets = Vec::with_capacity(to.len());
583 for s in to {
584 let msg = match by_api.get(&s.api) {
585 Some(m) => m.clone(),
586 None => match engine.tx_stream(seq, h, tx, meta, s.api) {
587 Ok(m) => {
588 let m = Value::Object(m).to_string();
589 by_api.insert(s.api, m.clone());
590 m
591 }
592 Err(e) => {
593 warn!(
594 "subscriptions: ledger {seq}, transaction skipped: {}",
595 e.message
596 );
597 break;
598 }
599 },
600 };
601 targets.push((s.id, msg));
602 }
603 hub.deliver(&targets);
604 }
605}
606
607pub async fn run(engine: Arc<Engine>, hub: Arc<Hub>) {
610 let mut last: Option<u32> = None;
611 loop {
612 tokio::time::sleep(POLL).await;
613 let Ok((_, max)) = engine.range() else {
614 continue;
615 };
616 let from = match last {
617 Some(l) if l >= max => continue,
618 Some(l) if max - l > MAX_BEHIND => {
619 warn!(
620 "subscriptions: {} ledgers behind, catching up from {}",
621 max - l,
622 max - MAX_BEHIND
623 );
624 max - MAX_BEHIND + 1
625 }
626 Some(l) => l + 1,
627 None => max,
628 };
629 last = Some(max);
630 if !hub.wants_anything() {
631 continue;
632 }
633 let (e, h) = (engine.clone(), hub.clone());
634 let done = tokio::task::spawn_blocking(move || {
635 for seq in from..=max {
636 if let Err(err) = publish(&e, &h, seq) {
637 warn!("subscriptions: ledger {seq} not published: {}", err.message);
638 }
639 }
640 })
641 .await;
642 if let Err(e) = done {
643 warn!("subscriptions: {e}");
644 }
645 }
646}
647
648#[cfg(test)]
649mod tests {
650 use super::*;
651
652 fn p(v: Value) -> Map<String, Value> {
653 v.as_object().cloned().unwrap_or_default()
654 }
655
656 #[test]
657 fn node_validations_go_once_to_their_subscribers() {
658 let hub = Hub::default();
659 let (a, mut ra) = hub.join();
660 let (b, mut rb) = hub.join();
661 let r = parse(&p(json!({"streams": ["validations"]}))).unwrap();
662 assert!(r.validations && !r.manifests);
663 hub.subscribe(a, &r, 2, 0);
664 hub.subscribe(
665 b,
666 &parse(&p(json!({"streams": ["manifests"]}))).unwrap(),
667 2,
668 0,
669 );
670 let mut seen = (HashSet::new(), std::collections::VecDeque::new());
671 let v = r#"{"type":"validationReceived","data":"AB","ledger_index":"5"}"#;
672 let m = r#"{"type":"manifestReceived","manifest":"JA=="}"#;
673 hub.node_message(v, &mut seen);
675 hub.node_message(v, &mut seen);
676 hub.node_message(m, &mut seen);
677 hub.node_message(r#"{"type":"ledgerClosed"}"#, &mut seen);
678 assert_eq!(ra.try_recv().unwrap(), v);
679 assert!(ra.try_recv().is_err());
680 assert_eq!(rb.try_recv().unwrap(), m);
681 assert!(rb.try_recv().is_err());
682 hub.unsubscribe(a, &r);
683 hub.node_message(r#"{"type":"validationReceived","data":"CD"}"#, &mut seen);
684 assert!(ra.try_recv().is_err());
685 assert_eq!(hub.stats().manifests, 1);
686 }
687
688 #[test]
689 fn requests_parse_with_clio_errors() {
690 let err = |v: Value| parse(&p(v)).unwrap_err();
691 assert_eq!(err(json!({"streams": "ledger"})).message, "streamsNotArray");
692 assert_eq!(err(json!({"streams": [1]})).message, "streamNotString");
693 assert_eq!(err(json!({"streams": ["nope"]})).error, "malformedStream");
694 assert_eq!(
695 err(json!({"streams": ["transactions_proposed"]})).error,
696 "notSupported"
697 );
698 assert_eq!(err(json!({"accounts": "x"})).message, "accountsNotArray");
699 assert_eq!(err(json!({"accounts": []})).message, "accounts malformed.");
700 assert_eq!(
701 err(json!({"accounts": [1]})).message,
702 "accounts'sItemNotString"
703 );
704 assert_eq!(
705 err(json!({"accounts": ["x"]})).message,
706 "accounts'sItemMalformed"
707 );
708 assert_eq!(err(json!({"books": []})).error, "notSupported");
709 let r = parse(&p(json!({
710 "streams": ["ledger", "transactions", "book_changes"],
711 "accounts": ["rrrrrrrrrrrrrrrrrrrrrhoLvTp"],
712 })))
713 .unwrap();
714 assert!(r.ledger && r.transactions && r.book_changes);
715 assert_eq!(r.accounts, vec![[0u8; 20]]);
716 assert_eq!(parse(&Map::new()).unwrap(), Request::default());
717 }
718
719 #[test]
720 fn hub_tracks_and_drops_slow_sessions() {
721 let hub = Hub::default();
722 let (a, mut rx) = hub.join();
723 let r = Request {
724 ledger: true,
725 ..Request::default()
726 };
727 hub.subscribe(a, &r, 1, 0);
728 assert!(hub.wants_anything());
729 let st = hub.stats();
730 assert_eq!((st.ledger, st.transactions, st.dropped), (1, 0, 0));
731 hub.deliver(&[(a, "x".into())]);
732 assert_eq!(rx.try_recv().unwrap(), "x");
733 let flood: Vec<(u64, String)> = (0..=QUEUE).map(|_| (a, "y".into())).collect();
734 hub.deliver(&flood);
735 assert!(!hub.wants_anything());
736 assert_eq!(
737 hub.stats(),
738 HubStats {
739 dropped: 1,
740 ..HubStats::default()
741 }
742 );
743 hub.unsubscribe(a, &r);
744 }
745}