Skip to main content

ledger_engine/
forward.rs

1//! Forwarding to a node: methods that Clio does not serve itself but passes
2//! to xrpld (node state, fees, the current ledger, field definitions).
3//! Nodes are tried round-robin, each with its own timeout; the node's
4//! response is returned as is and marked `forwarded`, as in Clio. Identical
5//! requests within `CACHE_FOR` get the same response; this is how Clio absorbs
6//! bursts of fee polling. One request gets `TOTAL_LIMIT` over all nodes, and a
7//! node that just failed is tried last, so that one dead node doesn't cost half
8//! of the requests a timeout.
9//!
10//! `submit` and `simulate` go to a node only when the operator turned them on,
11//! never carry signing material, and `submit` is never cached or retried once
12//! it may have reached a node (`send_transaction`).
13
14use std::collections::HashMap;
15use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering};
16use std::sync::{Arc, Mutex};
17use std::time::{Duration, Instant};
18
19use serde_json::{Map, Value, json};
20
21use crate::api::RpcError;
22
23/// Methods that go to the node.
24pub const FORWARDED: [&str; 4] = [
25    "server_state",
26    "fee",
27    "ledger_current",
28    "server_definitions",
29];
30/// Methods that Clio always serves itself, even for the current ledger.
31const CLIO_ONLY: [&str; 6] = [
32    "mpt_holders",
33    "nft_history",
34    "nft_info",
35    "nfts_by_issuer",
36    "ledger_index",
37    "version",
38];
39
40/// Public read methods that go to the node when asked about the current or
41/// closed ledger. Nothing else ever does; otherwise `ledger_index: "current"`
42/// would pass anything to the node, from `submit` to the admin `stop` and `log_level`.
43const CURRENT_ON_NODE: [&str; 21] = [
44    "account_channels",
45    "account_currencies",
46    "account_info",
47    "account_lines",
48    "account_nfts",
49    "account_objects",
50    "account_offers",
51    "amm_info",
52    "book_changes",
53    "book_offers",
54    "deposit_authorized",
55    "feature",
56    "gateway_balances",
57    "ledger",
58    "ledger_data",
59    "ledger_entry",
60    "nft_buy_offers",
61    "nft_sell_offers",
62    "noripple_check",
63    "ripple_path_find",
64    "vault_info",
65];
66
67/// Whether a request goes to the node, following Clio's rule: node methods; a
68/// public read method asking about the current or closed ledger (Astraea keeps
69/// only validated ones); the transaction queue in `account_info` and `ledger`.
70pub fn forwarded(method: &str, params: &Map<String, Value>) -> bool {
71    if FORWARDED.contains(&method) {
72        return true;
73    }
74    if CLIO_ONLY.contains(&method) || !CURRENT_ON_NODE.contains(&method) {
75        return false;
76    }
77    if matches!(
78        params.get("ledger_index").and_then(Value::as_str),
79        Some("current" | "closed")
80    ) {
81        return true;
82    }
83    matches!(method, "account_info" | "ledger") && params.get("queue") == Some(&Value::Bool(true))
84}
85
86/// Methods that send a transaction to a node or try one out.
87pub fn submission(method: &str) -> bool {
88    matches!(method, "submit" | "simulate")
89}
90
91fn invalid(message: &str) -> RpcError {
92    RpcError {
93        error: "invalidParams",
94        code: 31,
95        message: message.into(),
96    }
97}
98
99/// The parameters of `submit` or `simulate` that may reach the node. A request
100/// that would have the node sign is refused: a secret must not travel through
101/// this server, and a node that trusts us might act on it.
102pub fn submission_params(
103    method: &str,
104    params: &Map<String, Value>,
105) -> Result<Map<String, Value>, RpcError> {
106    for k in ["secret", "seed", "seed_hex", "passphrase", "key_type"] {
107        if params.contains_key(k) {
108            return Err(invalid("signingNotSupported"));
109        }
110    }
111    let keep: &[&str] = if method == "submit" {
112        if !params.get("tx_blob").is_some_and(Value::is_string) {
113            return Err(invalid("submit takes a signed tx_blob."));
114        }
115        &["tx_blob", "fail_hard", "api_version"]
116    } else {
117        &["tx_blob", "tx_json", "binary", "api_version"]
118    };
119    Ok(params
120        .iter()
121        .filter(|(k, _)| keep.contains(&k.as_str()))
122        .map(|(k, v)| (k.clone(), v.clone()))
123        .collect())
124}
125
126/// Node fields in `server_info`, as in Clio: the fee multiplier (clients such
127/// as xrpl.js compute fees from it; hundreds under escalation) and the xrpld version.
128/// `node` is the `result` of the node's `server_info` response.
129pub fn node_info(result: &mut Map<String, Value>, node: &Map<String, Value>) {
130    let (Some(Value::Object(info)), Some(n)) = (
131        result.get_mut("info"),
132        node.get("info").and_then(Value::as_object),
133    ) else {
134        return;
135    };
136    if let Some(v) = n.get("load_factor").filter(|v| v.is_number()) {
137        info.insert("load_factor".into(), v.clone());
138    }
139    if let Some(v) = n.get("build_version").filter(|v| v.is_string()) {
140        info.insert("rippled_version".into(), v.clone());
141    }
142}
143
144/// Fields of a node's `server_state` (and `server_info`) that describe the node
145/// itself rather than the network: its peer key, listening ports and host name.
146/// A public listener leaves them out.
147const NODE_IDENTITY: [&str; 3] = ["pubkey_node", "ports", "hostid"];
148
149/// Leaves the node's own fields out of a forwarded node-state reply.
150pub fn hide_node(method: &str, result: &mut Map<String, Value>) {
151    let key = match method {
152        "server_state" => "state",
153        "server_info" => "info",
154        _ => return,
155    };
156    if let Some(Value::Object(m)) = result.get_mut(key) {
157        for f in NODE_IDENTITY {
158            m.remove(f);
159        }
160    }
161}
162
163/// How long a node response stays cached: `forwarding.cache_timeout` in Clio.
164const CACHE_FOR: Duration = Duration::from_millis(250);
165/// Maximum number of cached responses; the key is the method and params.
166const CACHE_MAX: usize = 64;
167/// How long to answer `failedToForward` immediately after all nodes failed:
168/// a hung node must not hold request slots and slow down server_info.
169const DOWN_FOR: Duration = Duration::from_secs(5);
170
171/// How long one forwarded request may take over all nodes. Clients commonly give
172/// up after 10 seconds, and the answer is no use to them after that.
173const TOTAL_LIMIT: Duration = Duration::from_secs(8);
174/// How long a request may spend connecting. Past this nothing was sent, so
175/// another node can safely be asked.
176const CONNECT_LIMIT: Duration = Duration::from_secs(2);
177
178/// How old the node's server_info may be and still be merged into ours while
179/// a refresh runs; older than this (the node stopped answering), it is dropped.
180const INFO_KEEP: Duration = Duration::from_secs(10);
181
182/// Why a node gave no answer.
183#[derive(Debug)]
184struct AskError {
185    /// The request can't have reached the node.
186    nothing_sent: bool,
187    text: String,
188}
189
190impl AskError {
191    fn after_send(text: impl Into<String>) -> AskError {
192        AskError {
193            nothing_sent: false,
194            text: text.into(),
195        }
196    }
197}
198
199/// Whether a failed request can't have reached the node. Anything else, a reset
200/// connection or a timeout while waiting, may have delivered it.
201fn nothing_sent(e: &ureq::Error) -> bool {
202    use ureq::Timeout;
203    match e {
204        ureq::Error::HostNotFound | ureq::Error::ConnectionFailed => true,
205        ureq::Error::Timeout(Timeout::Resolve | Timeout::Connect) => true,
206        ureq::Error::Io(e) => e.kind() == std::io::ErrorKind::ConnectionRefused,
207        _ => false,
208    }
209}
210
211/// Method and params → when the node response was received, and the response.
212type Cache = HashMap<String, (Instant, Map<String, Value>)>;
213
214#[derive(Debug)]
215pub struct Forwarder {
216    /// Node JSON-RPC endpoints, e.g. `http://<node>:51234`.
217    sources: Vec<String>,
218    agent: ureq::Agent,
219    /// Timeout for each node.
220    timeout: Duration,
221    /// When each node last failed, in the order of `sources`.
222    failed_at: Mutex<Vec<Option<Instant>>>,
223    next: AtomicUsize,
224    cache: Mutex<Cache>,
225    /// When all nodes last failed to respond.
226    down: Mutex<Option<Instant>>,
227    /// The node's last server_info and when it came, for `node_server_info`.
228    info: Mutex<Option<(Instant, Map<String, Value>)>>,
229    info_refreshing: AtomicBool,
230}
231
232impl Forwarder {
233    pub fn new(sources: Vec<String>, timeout: Duration) -> Forwarder {
234        Forwarder {
235            failed_at: Mutex::new(vec![None; sources.len()]),
236            sources,
237            timeout,
238            agent: ureq::Agent::config_builder()
239                .timeout_global(Some(timeout))
240                .user_agent(concat!("astraea/", env!("CARGO_PKG_VERSION")))
241                .build()
242                .into(),
243            next: AtomicUsize::new(0),
244            cache: Mutex::new(HashMap::new()),
245            down: Mutex::new(None),
246            info: Mutex::new(None),
247            info_refreshing: AtomicBool::new(false),
248        }
249    }
250
251    /// The node's server_info, for the fields merged into ours. Never waits for
252    /// a node: a client's server_info is answered from our own data, and with
253    /// every node silent, waiting would outlast a client's timeout. Returns the
254    /// last answer if it is younger than `INFO_KEEP`, and once it is older than
255    /// `CACHE_FOR`, or there is none, refreshes it in the background.
256    pub fn node_server_info(self: &Arc<Self>) -> Option<Map<String, Value>> {
257        let (fresh, info) = match &*self.info.lock().unwrap_or_else(|p| p.into_inner()) {
258            Some((at, m)) => (
259                at.elapsed() < CACHE_FOR,
260                (at.elapsed() < INFO_KEEP).then(|| m.clone()),
261            ),
262            None => (false, None),
263        };
264        if !fresh && !self.info_refreshing.swap(true, Ordering::AcqRel) {
265            let f = self.clone();
266            std::thread::spawn(move || {
267                f.refresh_info();
268                f.info_refreshing.store(false, Ordering::Release);
269            });
270        }
271        info
272    }
273
274    fn refresh_info(&self) {
275        if let Ok(r) = self.forward("server_info", &Map::new()) {
276            *self.info.lock().unwrap_or_else(|p| p.into_inner()) = Some((Instant::now(), r));
277        }
278    }
279
280    /// `result` of the node's response. An error from the node itself (`status: error`)
281    /// is returned as is, since it is an answer to the request; all nodes down gives `failedToForward`.
282    pub fn forward(
283        &self,
284        method: &str,
285        params: &Map<String, Value>,
286    ) -> Result<Map<String, Value>, RpcError> {
287        let key = format!("{method} {}", Value::Object(params.clone()));
288        if let Some((at, hit)) = self.lock().get(&key)
289            && at.elapsed() < CACHE_FOR
290        {
291            return Ok(hit.clone());
292        }
293        let failed = || RpcError {
294            error: "failedToForward",
295            code: 90,
296            message: "Failed to forward request to p2p node".into(),
297        };
298        if self
299            .down
300            .lock()
301            .unwrap_or_else(|p| p.into_inner())
302            .is_some_and(|t| t.elapsed() < DOWN_FOR)
303        {
304            return Err(failed());
305        }
306        let body = json!({ "method": method, "params": [params] }).to_string();
307        let deadline = Instant::now() + TOTAL_LIMIT;
308        let mut last = String::from("no nodes to forward to");
309        for i in self.order() {
310            let url = &self.sources[i];
311            let left = deadline.saturating_duration_since(Instant::now());
312            if left.is_zero() {
313                break;
314            }
315            match self.ask(url, &body, self.timeout.min(left)) {
316                Ok(r) => {
317                    let mut c = self.lock();
318                    if c.len() >= CACHE_MAX {
319                        c.retain(|_, (at, _)| at.elapsed() < CACHE_FOR);
320                    }
321                    if c.len() < CACHE_MAX {
322                        c.insert(key, (Instant::now(), r.clone()));
323                    }
324                    *self.down.lock().unwrap_or_else(|p| p.into_inner()) = None;
325                    self.mark(i, None);
326                    return Ok(r);
327                }
328                Err(e) => {
329                    self.mark(i, Some(Instant::now()));
330                    last = format!("{url}: {}", e.text);
331                }
332            }
333        }
334        tracing::warn!("forwarding {method} failed: {last}");
335        *self.down.lock().unwrap_or_else(|p| p.into_inner()) = Some(Instant::now());
336        Err(failed())
337    }
338
339    /// Sends a signed transaction to one node. Unlike `forward` this is never
340    /// cached: a retry has to reach the network. Another node is asked only when
341    /// the first can't have received it. Sending it again after a timeout could
342    /// give `tefPAST_SEQ` for a transaction that in fact went through, and the
343    /// client would take that for a failure; so it gets `failedToForward` and
344    /// must look the transaction up by hash.
345    pub fn send_transaction(
346        &self,
347        params: &Map<String, Value>,
348    ) -> Result<Map<String, Value>, RpcError> {
349        let body = json!({ "method": "submit", "params": [params] }).to_string();
350        let deadline = Instant::now() + TOTAL_LIMIT;
351        let mut last = String::from("no nodes to forward to");
352        for i in self.order() {
353            let url = &self.sources[i];
354            let left = deadline.saturating_duration_since(Instant::now());
355            if left.is_zero() {
356                break;
357            }
358            match self.ask(url, &body, self.timeout.min(left)) {
359                Ok(r) => {
360                    self.mark(i, None);
361                    return Ok(r);
362                }
363                Err(e) => {
364                    self.mark(i, Some(Instant::now()));
365                    if !e.nothing_sent {
366                        tracing::warn!("submit to {url} has no answer: {}", e.text);
367                        return Err(RpcError {
368                            error: "failedToForward",
369                            code: 90,
370                            message: "No answer from the node; the transaction may have been \
371                                      sent. Look it up by hash before sending it again."
372                                .into(),
373                        });
374                    }
375                    last = format!("{url}: {}", e.text);
376                }
377            }
378        }
379        tracing::warn!("submit failed, nothing sent: {last}");
380        Err(RpcError {
381            error: "failedToForward",
382            code: 90,
383            message: "Failed to forward request to p2p node".into(),
384        })
385    }
386
387    /// Nodes to try, in turn, with those that just failed last.
388    fn order(&self) -> Vec<usize> {
389        let n = self.sources.len();
390        let start = self.next.fetch_add(1, Ordering::Relaxed);
391        let failed = self.failed_at.lock().unwrap_or_else(|p| p.into_inner());
392        let mut order: Vec<usize> = (0..n).map(|k| (start + k) % n).collect();
393        order.sort_by_key(|&i| failed[i].is_some_and(|t| t.elapsed() < DOWN_FOR));
394        order
395    }
396
397    fn mark(&self, node: usize, failed: Option<Instant>) {
398        self.failed_at.lock().unwrap_or_else(|p| p.into_inner())[node] = failed;
399    }
400
401    fn ask(&self, url: &str, body: &str, limit: Duration) -> Result<Map<String, Value>, AskError> {
402        let mut resp = self
403            .agent
404            .post(url)
405            .config()
406            .timeout_global(Some(limit))
407            .timeout_connect(Some(CONNECT_LIMIT.min(limit)))
408            .build()
409            .header("content-type", "application/json")
410            .send(body)
411            .map_err(|e| AskError {
412                nothing_sent: nothing_sent(&e),
413                text: e.to_string(),
414            })?;
415        let text = resp
416            .body_mut()
417            .read_to_string()
418            .map_err(|e| AskError::after_send(e.to_string()))?;
419        match serde_json::from_str::<Value>(&text) {
420            Ok(Value::Object(mut o)) => match o.remove("result") {
421                Some(Value::Object(r)) => Ok(r),
422                _ => Err(AskError::after_send("no result in the response")),
423            },
424            _ => Err(AskError::after_send("response is not JSON")),
425        }
426    }
427
428    fn lock(&self) -> std::sync::MutexGuard<'_, Cache> {
429        self.cache.lock().unwrap_or_else(|p| p.into_inner())
430    }
431}
432
433#[cfg(test)]
434mod tests {
435    use super::*;
436
437    #[test]
438    fn public_listener_trims_node_state() {
439        let mut r = json!({"state": {
440            "pubkey_node": "n9M8", "ports": [{"port": "51235"}], "hostid": "HOST",
441            "build_version": "3.4.1", "server_state": "full"
442        }})
443        .as_object()
444        .cloned()
445        .unwrap();
446        hide_node("server_state", &mut r);
447        assert_eq!(
448            Value::Object(r),
449            json!({"state": {"build_version": "3.4.1", "server_state": "full"}})
450        );
451        let mut fee = json!({"drops": {"base_fee": "10"}, "ports": 1})
452            .as_object()
453            .cloned()
454            .unwrap();
455        hide_node("fee", &mut fee);
456        assert!(fee.contains_key("ports"));
457    }
458
459    #[test]
460    fn forwarding_follows_clio_rule() {
461        let on = |m: &str, v: Value| forwarded(m, v.as_object().unwrap());
462        assert!(on("fee", json!({})));
463        assert!(on("account_info", json!({"ledger_index": "current"})));
464        assert!(on("account_lines", json!({"ledger_index": "closed"})));
465        assert!(on("account_info", json!({"queue": true})));
466        assert!(!on("account_info", json!({"ledger_index": "validated"})));
467        assert!(!on("account_info", json!({"ledger_index": 5})));
468        assert!(!on("mpt_holders", json!({"ledger_index": "current"})));
469        assert!(!on("account_tx", json!({})));
470        // Nothing goes to the node except public reads.
471        for m in [
472            "stop",
473            "submit",
474            "sign",
475            "peers",
476            "log_level",
477            "ledger_accept",
478        ] {
479            assert!(!on(m, json!({"ledger_index": "current"})), "{m}");
480        }
481    }
482
483    #[test]
484    fn server_info_takes_load_factor_and_version_from_node() {
485        let mut r = json!({"info": {"load_factor": 1, "complete_ledgers": "1-2"}});
486        let r = r.as_object_mut().unwrap();
487        let node = json!({"info": {"load_factor": 509.9, "build_version": "3.4.1"}});
488        node_info(r, node.as_object().unwrap());
489        assert_eq!(r["info"]["load_factor"], json!(509.9));
490        assert_eq!(r["info"]["rippled_version"], json!("3.4.1"));
491        // Node response without info: our own fields are left alone.
492        node_info(r, json!({"error": "x"}).as_object().unwrap());
493        assert_eq!(r["info"]["complete_ledgers"], json!("1-2"));
494    }
495
496    /// Reads one whole HTTP request, headers and body. A test node must not
497    /// answer before the body is in: headers and body can arrive apart, and a
498    /// socket closed with unread data resets the connection under the client,
499    /// which then can't tell whether the node got the request.
500    fn read_request(s: &mut std::net::TcpStream) {
501        use std::io::Read;
502        let mut got = Vec::new();
503        let mut buf = [0u8; 4096];
504        loop {
505            let n = s.read(&mut buf).unwrap_or(0);
506            got.extend_from_slice(&buf[..n]);
507            if let Some(end) = got.windows(4).position(|w| w == b"\r\n\r\n") {
508                let head = String::from_utf8_lossy(&got[..end]);
509                let len = head
510                    .lines()
511                    .find_map(|l| {
512                        let (k, v) = l.split_once(':')?;
513                        k.eq_ignore_ascii_case("content-length")
514                            .then(|| v.trim().parse::<usize>().ok())?
515                    })
516                    .unwrap_or(0);
517                if got.len() >= end + 4 + len {
518                    return;
519                }
520            }
521            if n == 0 {
522                return;
523            }
524        }
525    }
526
527    /// A node that answers server_info after `delay`, with a load factor
528    /// counting its answers.
529    fn slow_node(delay: Duration) -> String {
530        use std::io::Write;
531        let l = std::net::TcpListener::bind("127.0.0.1:0").unwrap();
532        let url = format!("http://{}", l.local_addr().unwrap());
533        std::thread::spawn(move || {
534            for (n, s) in l.incoming().enumerate() {
535                let mut s = s.unwrap();
536                read_request(&mut s);
537                std::thread::sleep(delay);
538                let body = json!({"result": {"info": {"load_factor": n + 1}}}).to_string();
539                let _ = write!(
540                    s,
541                    "HTTP/1.1 200 OK\r\ncontent-type: application/json\r\ncontent-length: {}\r\nconnection: close\r\n\r\n{body}",
542                    body.len()
543                );
544            }
545        });
546        url
547    }
548
549    #[test]
550    fn server_info_from_the_node_is_refreshed_in_the_background() {
551        let f = Arc::new(Forwarder::new(
552            vec![slow_node(Duration::from_millis(150))],
553            Duration::from_secs(5),
554        ));
555        let lf = |m: Map<String, Value>| m["info"]["load_factor"].as_u64().unwrap();
556        // The first call has nothing to give yet and doesn't wait for the node.
557        let t = Instant::now();
558        assert!(f.node_server_info().is_none());
559        assert!(t.elapsed() < Duration::from_millis(50));
560        let deadline = Instant::now() + Duration::from_secs(10);
561        while f.info.lock().unwrap().is_none() {
562            assert!(Instant::now() < deadline, "no first answer");
563            std::thread::sleep(Duration::from_millis(20));
564        }
565        std::thread::sleep(CACHE_FOR);
566        // Stale: the old answer comes at once, the new one arrives behind it.
567        let t = Instant::now();
568        assert_eq!(lf(f.node_server_info().unwrap()), 1);
569        assert_eq!(lf(f.node_server_info().unwrap()), 1);
570        assert!(t.elapsed() < Duration::from_millis(50));
571        // The refresh lands after the node's delay; a loaded machine may take longer.
572        // A refresh that failed on the way still used up one of the node's answers,
573        // so the next good one may count higher than 2.
574        let deadline = Instant::now() + Duration::from_secs(10);
575        while lf(f.node_server_info().unwrap()) < 2 {
576            assert!(Instant::now() < deadline, "no refresh");
577            std::thread::sleep(Duration::from_millis(20));
578        }
579    }
580
581    #[test]
582    fn server_info_does_not_wait_for_nodes_that_went_silent() {
583        // Two hung nodes, as when their network is gone: a request to them only
584        // ends at the timeout, 10 seconds in all. That is as long as clients wait.
585        let hung = || slow_node(Duration::from_secs(60));
586        let f = Arc::new(Forwarder::new(vec![hung(), hung()], Duration::from_secs(5)));
587        // The last answer is too old to pass on.
588        *f.info.lock().unwrap() = Some((
589            Instant::now() - INFO_KEEP,
590            json!({"info": {"load_factor": 7}})
591                .as_object()
592                .unwrap()
593                .clone(),
594        ));
595        let t = Instant::now();
596        for _ in 0..3 {
597            assert!(f.node_server_info().is_none());
598        }
599        assert!(t.elapsed() < Duration::from_millis(50));
600        assert!(f.info_refreshing.load(Ordering::Acquire));
601    }
602
603    #[test]
604    fn a_request_has_one_deadline_over_all_nodes() {
605        let hung = || slow_node(Duration::from_secs(60));
606        // Two nodes at 5 s each would take 10 s; the deadline ends it at 8.
607        let f = Forwarder::new(vec![hung(), hung()], Duration::from_secs(5));
608        let t = Instant::now();
609        assert!(f.forward("fee", &Map::new()).is_err());
610        let took = t.elapsed();
611        assert!(took >= TOTAL_LIMIT - Duration::from_millis(100), "{took:?}");
612        assert!(took < TOTAL_LIMIT + Duration::from_secs(1), "{took:?}");
613    }
614
615    #[test]
616    fn a_node_that_just_failed_is_tried_last() {
617        let f = Forwarder::new(
618            vec!["http://127.0.0.1:1".into(), "http://127.0.0.1:2".into()],
619            Duration::from_secs(1),
620        );
621        f.mark(0, Some(Instant::now()));
622        for _ in 0..4 {
623            assert_eq!(f.order(), vec![1, 0]);
624        }
625        // Once the mark is old, the nodes take turns again.
626        f.mark(0, Some(Instant::now() - DOWN_FOR));
627        let (a, b) = (f.order()[0], f.order()[0]);
628        assert_ne!(a, b);
629    }
630
631    #[test]
632    fn signing_on_the_node_is_refused() {
633        let p = |v: Value| v.as_object().unwrap().clone();
634        for k in ["secret", "seed", "seed_hex", "passphrase", "key_type"] {
635            for m in ["submit", "simulate"] {
636                let e = submission_params(m, &p(json!({"tx_blob": "00", k: "x"}))).unwrap_err();
637                assert_eq!(e.error, "invalidParams");
638                assert_eq!(e.message, "signingNotSupported");
639            }
640        }
641        assert!(submission_params("submit", &p(json!({"tx_json": {}}))).is_err());
642        let kept = submission_params(
643            "submit",
644            &p(json!({"tx_blob": "00", "fail_hard": true, "admin": 1})),
645        )
646        .unwrap();
647        assert_eq!(kept, p(json!({"tx_blob": "00", "fail_hard": true})));
648        let kept = submission_params(
649            "simulate",
650            &p(json!({"tx_json": {"TransactionType": "Payment"}, "other": 1})),
651        )
652        .unwrap();
653        assert_eq!(kept, p(json!({"tx_json": {"TransactionType": "Payment"}})));
654    }
655
656    #[test]
657    fn a_transaction_goes_to_the_next_node_only_if_nothing_was_sent() {
658        let p = json!({"tx_blob": "00"}).as_object().unwrap().clone();
659        // The first node refuses the connection, so the second one gets it.
660        let (up, seen) = counting_node();
661        let f = Forwarder::new(
662            vec!["http://127.0.0.1:1".into(), up],
663            Duration::from_secs(2),
664        );
665        f.mark(1, Some(Instant::now()));
666        assert!(f.send_transaction(&p).is_ok());
667        assert_eq!(seen.load(Ordering::Relaxed), 1);
668
669        // A node that took it and went silent: no second attempt, and the client
670        // is told the outcome is unknown.
671        let (up, seen) = counting_node();
672        let hung = slow_node(Duration::from_secs(60));
673        let f = Forwarder::new(vec![hung, up], Duration::from_millis(300));
674        f.mark(1, Some(Instant::now()));
675        let e = f.send_transaction(&p).unwrap_err();
676        assert_eq!(e.error, "failedToForward");
677        assert!(e.message.contains("may have been sent"), "{}", e.message);
678        assert_eq!(seen.load(Ordering::Relaxed), 0);
679    }
680
681    #[test]
682    fn a_transaction_is_never_answered_from_the_cache() {
683        let (url, seen) = counting_node();
684        let f = Forwarder::new(vec![url], Duration::from_secs(2));
685        let p = json!({"tx_blob": "00"}).as_object().unwrap().clone();
686        f.send_transaction(&p).unwrap();
687        f.send_transaction(&p).unwrap();
688        assert_eq!(seen.load(Ordering::Relaxed), 2);
689    }
690
691    /// A node that answers at once and counts the requests it got.
692    fn counting_node() -> (String, Arc<AtomicUsize>) {
693        use std::io::Write;
694        let l = std::net::TcpListener::bind("127.0.0.1:0").unwrap();
695        let url = format!("http://{}", l.local_addr().unwrap());
696        let seen = Arc::new(AtomicUsize::new(0));
697        let count = seen.clone();
698        std::thread::spawn(move || {
699            for s in l.incoming() {
700                let mut s = s.unwrap();
701                read_request(&mut s);
702                count.fetch_add(1, Ordering::Relaxed);
703                let body = r#"{"result":{"engine_result":"tesSUCCESS"}}"#;
704                let _ = write!(
705                    s,
706                    "HTTP/1.1 200 OK\r\ncontent-type: application/json\r\ncontent-length: {}\r\nconnection: close\r\n\r\n{body}",
707                    body.len()
708                );
709            }
710        });
711        (url, seen)
712    }
713
714    #[test]
715    fn unreachable_nodes_give_failed_to_forward_quickly() {
716        let f = Forwarder::new(
717            vec!["http://127.0.0.1:1".into(), "http://127.0.0.1:2".into()],
718            Duration::from_secs(2),
719        );
720        let t = Instant::now();
721        let e = f.forward("fee", &Map::new()).unwrap_err();
722        assert_eq!((e.error, e.code), ("failedToForward", 90));
723        assert!(t.elapsed() < Duration::from_secs(5));
724        // Right after a failure: respond without waiting for nodes.
725        let t = Instant::now();
726        assert!(f.forward("server_state", &Map::new()).is_err());
727        assert!(t.elapsed() < Duration::from_millis(50));
728    }
729}