alloy_node_bindings/nodes/
reth.rs1use crate::{
4 utils::{extract_endpoint, GracefulShutdown},
5 NodeError, NODE_STARTUP_TIMEOUT,
6};
7use alloy_genesis::Genesis;
8use rand::Rng;
9use std::{
10 ffi::OsString,
11 fs::create_dir,
12 io::{BufRead, BufReader},
13 path::PathBuf,
14 process::{Child, ChildStdout, Command, Stdio},
15 time::Instant,
16};
17use url::Url;
18
19const API: &str = "eth,net,web3,txpool,trace,rpc,reth,ots,admin,debug";
21
22const RETH: &str = "reth";
24
25const DEFAULT_HTTP_PORT: u16 = 8545;
27
28const DEFAULT_WS_PORT: u16 = 8546;
30
31const DEFAULT_AUTH_PORT: u16 = 8551;
33
34const DEFAULT_P2P_PORT: u16 = 30303;
36
37#[derive(Debug)]
41pub struct RethInstance {
42 pid: Child,
43 host: String,
44 instance: u16,
45 http_port: u16,
46 ws_port: u16,
47 auth_port: Option<u16>,
48 p2p_port: Option<u16>,
49 ipc: Option<PathBuf>,
50 data_dir: Option<PathBuf>,
51 genesis: Option<Genesis>,
52}
53
54impl RethInstance {
55 pub fn host(&self) -> &str {
57 &self.host
58 }
59
60 pub const fn instance(&self) -> u16 {
62 self.instance
63 }
64
65 pub const fn http_port(&self) -> u16 {
67 self.http_port
68 }
69
70 pub const fn ws_port(&self) -> u16 {
72 self.ws_port
73 }
74
75 pub const fn auth_port(&self) -> Option<u16> {
77 self.auth_port
78 }
79
80 pub const fn p2p_port(&self) -> Option<u16> {
83 self.p2p_port
84 }
85
86 #[doc(alias = "http_endpoint")]
88 pub fn endpoint(&self) -> String {
89 format!("http://{}:{}", self.host, self.http_port)
90 }
91
92 pub fn ws_endpoint(&self) -> String {
94 format!("ws://{}:{}", self.host, self.ws_port)
95 }
96
97 pub fn ipc_endpoint(&self) -> String {
99 self.ipc.as_ref().map_or_else(|| "reth.ipc".to_string(), |ipc| ipc.display().to_string())
100 }
101
102 #[doc(alias = "http_endpoint_url")]
104 pub fn endpoint_url(&self) -> Url {
105 Url::parse(&self.endpoint()).unwrap()
106 }
107
108 pub fn ws_endpoint_url(&self) -> Url {
110 Url::parse(&self.ws_endpoint()).unwrap()
111 }
112
113 pub const fn data_dir(&self) -> Option<&PathBuf> {
115 self.data_dir.as_ref()
116 }
117
118 pub const fn genesis(&self) -> Option<&Genesis> {
120 self.genesis.as_ref()
121 }
122
123 pub fn stdout(&mut self) -> Result<ChildStdout, NodeError> {
128 self.pid.stdout.take().ok_or(NodeError::NoStdout)
129 }
130}
131
132impl Drop for RethInstance {
133 fn drop(&mut self) {
134 GracefulShutdown::shutdown(&mut self.pid, 10, "reth");
135 }
136}
137
138#[derive(Clone, Debug)]
157#[must_use = "This Builder struct does nothing unless it is `spawn`ed"]
158pub struct Reth {
159 dev: bool,
160 host: Option<String>,
161 http_port: u16,
162 ws_port: u16,
163 auth_port: u16,
164 p2p_port: u16,
165 block_time: Option<String>,
166 instance: u16,
167 discovery_enabled: bool,
168 program: Option<PathBuf>,
169 ipc_path: Option<PathBuf>,
170 ipc_enabled: bool,
171 data_dir: Option<PathBuf>,
172 chain_or_path: Option<String>,
173 genesis: Option<Genesis>,
174 args: Vec<OsString>,
175 keep_stdout: bool,
176}
177
178impl Default for Reth {
179 fn default() -> Self {
180 Self::new()
181 }
182}
183
184impl Reth {
185 pub fn new() -> Self {
191 Self {
192 dev: false,
193 host: None,
194 http_port: DEFAULT_HTTP_PORT,
195 ws_port: DEFAULT_WS_PORT,
196 auth_port: DEFAULT_AUTH_PORT,
197 p2p_port: DEFAULT_P2P_PORT,
198 block_time: None,
199 instance: rand::thread_rng().gen_range(1..200),
200 discovery_enabled: true,
201 program: None,
202 ipc_path: None,
203 ipc_enabled: false,
204 data_dir: None,
205 chain_or_path: None,
206 genesis: None,
207 args: Vec::new(),
208 keep_stdout: false,
209 }
210 }
211
212 pub fn at(path: impl Into<PathBuf>) -> Self {
225 Self::new().path(path)
226 }
227
228 pub fn path<T: Into<PathBuf>>(mut self, path: T) -> Self {
233 self.program = Some(path.into());
234 self
235 }
236
237 pub const fn dev(mut self) -> Self {
239 self.dev = true;
240 self
241 }
242
243 pub fn host<T: Into<String>>(mut self, host: T) -> Self {
247 self.host = Some(host.into());
248 self
249 }
250
251 pub const fn http_port(mut self, http_port: u16) -> Self {
254 self.http_port = http_port;
255 self.instance = 0;
256 self
257 }
258
259 pub const fn ws_port(mut self, ws_port: u16) -> Self {
262 self.ws_port = ws_port;
263 self.instance = 0;
264 self
265 }
266
267 pub const fn auth_port(mut self, auth_port: u16) -> Self {
270 self.auth_port = auth_port;
271 self.instance = 0;
272 self
273 }
274
275 pub const fn p2p_port(mut self, p2p_port: u16) -> Self {
278 self.p2p_port = p2p_port;
279 self.instance = 0;
280 self
281 }
282
283 pub fn block_time(mut self, block_time: &str) -> Self {
287 self.block_time = Some(block_time.to_string());
288 self
289 }
290
291 pub const fn disable_discovery(mut self) -> Self {
293 self.discovery_enabled = false;
294 self
295 }
296
297 pub fn chain_or_path(mut self, chain_or_path: &str) -> Self {
300 self.chain_or_path = Some(chain_or_path.to_string());
301 self
302 }
303
304 pub const fn enable_ipc(mut self) -> Self {
306 self.ipc_enabled = true;
307 self
308 }
309
310 pub const fn instance(mut self, instance: u16) -> Self {
313 self.instance = instance;
314 self
315 }
316
317 pub fn ipc_path<T: Into<PathBuf>>(mut self, path: T) -> Self {
321 self.ipc_path = Some(path.into());
322 self.ipc_enabled = true;
323 self
324 }
325
326 pub fn data_dir<T: Into<PathBuf>>(mut self, path: T) -> Self {
328 self.data_dir = Some(path.into());
329 self
330 }
331
332 pub fn genesis(mut self, genesis: Genesis) -> Self {
339 self.genesis = Some(genesis);
340 self
341 }
342
343 pub const fn keep_stdout(mut self) -> Self {
347 self.keep_stdout = true;
348 self
349 }
350
351 pub fn arg<T: Into<OsString>>(mut self, arg: T) -> Self {
355 self.args.push(arg.into());
356 self
357 }
358
359 pub fn args<I, S>(mut self, args: I) -> Self
363 where
364 I: IntoIterator<Item = S>,
365 S: Into<OsString>,
366 {
367 for arg in args {
368 self = self.arg(arg);
369 }
370 self
371 }
372
373 #[track_caller]
379 pub fn spawn(self) -> RethInstance {
380 self.try_spawn().unwrap()
381 }
382
383 pub fn try_spawn(self) -> Result<RethInstance, NodeError> {
385 let bin_path = self
386 .program
387 .as_ref()
388 .map_or_else(|| RETH.as_ref(), |bin| bin.as_os_str())
389 .to_os_string();
390 let mut cmd = Command::new(&bin_path);
391 cmd.stdout(Stdio::piped());
393
394 cmd.arg("node");
396
397 if self.http_port != DEFAULT_HTTP_PORT {
399 cmd.arg("--http.port").arg(self.http_port.to_string());
400 }
401
402 if self.ws_port != DEFAULT_WS_PORT {
403 cmd.arg("--ws.port").arg(self.ws_port.to_string());
404 }
405
406 if self.auth_port != DEFAULT_AUTH_PORT {
407 cmd.arg("--authrpc.port").arg(self.auth_port.to_string());
408 }
409
410 if self.p2p_port != DEFAULT_P2P_PORT {
411 cmd.arg("--discovery.port").arg(self.p2p_port.to_string());
412 }
413
414 if self.dev {
416 cmd.arg("--dev");
423
424 if let Some(block_time) = self.block_time {
426 cmd.arg("--dev.block-time").arg(block_time);
427 }
428 }
429
430 if !self.ipc_enabled {
432 cmd.arg("--ipcdisable");
433 }
434
435 cmd.arg("--http");
437 cmd.arg("--http.api").arg(API);
438
439 if let Some(ref host) = self.host {
440 cmd.arg("--http.addr").arg(host);
441 }
442
443 cmd.arg("--ws");
445 cmd.arg("--ws.api").arg(API);
446
447 if let Some(ref host) = self.host {
448 cmd.arg("--ws.addr").arg(host);
449 }
450
451 if let Some(ipc) = &self.ipc_path {
453 cmd.arg("--ipcpath").arg(ipc);
454 }
455
456 if self.instance > 0 {
461 cmd.arg("--instance").arg(self.instance.to_string());
462 }
463
464 if let Some(data_dir) = &self.data_dir {
465 cmd.arg("--datadir").arg(data_dir);
466
467 if !data_dir.exists() {
469 create_dir(data_dir).map_err(NodeError::CreateDirError)?;
470 }
471 }
472
473 if self.discovery_enabled {
474 cmd.arg("--verbosity").arg("-vvv");
476 } else {
477 cmd.arg("--disable-discovery");
478 cmd.arg("--no-persist-peers");
479 }
480
481 if let Some(chain_or_path) = self.chain_or_path {
482 cmd.arg("--chain").arg(chain_or_path);
483 }
484
485 cmd.arg("--color").arg("never");
487
488 cmd.args(self.args);
490
491 let mut child = cmd.spawn().map_err(NodeError::SpawnError)?;
492
493 let stdout = child.stdout.take().ok_or(NodeError::NoStdout)?;
494
495 let start = Instant::now();
496 let mut reader = BufReader::new(stdout);
497
498 let mut http_port = 0;
499 let mut ws_port = 0;
500 let mut auth_port = 0;
501 let mut p2p_port = 0;
502
503 let mut ports_started = false;
504 let mut p2p_started = !self.discovery_enabled;
505
506 loop {
507 if start + NODE_STARTUP_TIMEOUT <= Instant::now() {
508 let _ = child.kill();
509 return Err(NodeError::Timeout);
510 }
511
512 let mut line = String::with_capacity(120);
513 reader.read_line(&mut line).map_err(NodeError::ReadLineError)?;
514
515 if line.contains("RPC HTTP server started") {
516 if let Some(addr) = extract_endpoint("url=", &line) {
517 http_port = addr.port();
518 }
519 }
520
521 if line.contains("RPC WS server started") {
522 if let Some(addr) = extract_endpoint("url=", &line) {
523 ws_port = addr.port();
524 }
525 }
526
527 if line.contains("RPC auth server started") {
528 if let Some(addr) = extract_endpoint("url=", &line) {
529 auth_port = addr.port();
530 }
531 }
532
533 if line.contains("ERROR") {
535 let _ = child.kill();
536 return Err(NodeError::Fatal(line));
537 }
538
539 if http_port != 0 && ws_port != 0 && auth_port != 0 {
540 ports_started = true;
541 }
542
543 if self.discovery_enabled {
544 if line.contains("Updated local ENR") {
545 if let Some(port) = extract_endpoint("IpV4 UDP Socket", &line) {
546 p2p_port = port.port();
547 p2p_started = true;
548 }
549 }
550 } else {
551 p2p_started = true;
552 }
553
554 if ports_started && p2p_started {
556 break;
557 }
558 }
559
560 if self.keep_stdout {
561 child.stdout = Some(reader.into_inner());
563 }
564
565 Ok(RethInstance {
566 pid: child,
567 host: self.host.unwrap_or_else(|| "localhost".to_string()),
568 instance: self.instance,
569 http_port,
570 ws_port,
571 p2p_port: (p2p_port != 0).then_some(p2p_port),
572 ipc: self.ipc_path,
573 data_dir: self.data_dir,
574 auth_port: Some(auth_port),
575 genesis: self.genesis,
576 })
577 }
578}
579
580#[cfg(test)]
581mod tests {
582 use super::*;
583
584 #[test]
585 fn can_set_host() {
586 let reth = Reth::new().host("0.0.0.0").dev().try_spawn();
587 if let Ok(reth) = reth {
588 assert_eq!(reth.host(), "0.0.0.0");
589 assert!(reth.endpoint().starts_with("http://0.0.0.0:"));
590 assert!(reth.ws_endpoint().starts_with("ws://0.0.0.0:"));
591 }
592 }
593
594 #[test]
595 fn default_host_is_localhost() {
596 let reth = Reth::new().dev().try_spawn();
597 if let Ok(reth) = reth {
598 assert_eq!(reth.host(), "localhost");
599 assert!(reth.endpoint().starts_with("http://localhost:"));
600 assert!(reth.ws_endpoint().starts_with("ws://localhost:"));
601 }
602 }
603
604 #[test]
605 fn default_matches_new_semantics() {
606 let reth = Reth::default();
607
608 assert!(!reth.dev);
609 assert_eq!(reth.host, None);
610 assert_eq!(reth.http_port, DEFAULT_HTTP_PORT);
611 assert_eq!(reth.ws_port, DEFAULT_WS_PORT);
612 assert_eq!(reth.auth_port, DEFAULT_AUTH_PORT);
613 assert_eq!(reth.p2p_port, DEFAULT_P2P_PORT);
614 assert_eq!(reth.block_time, None);
615 assert!((1..200).contains(&reth.instance));
616 assert!(reth.discovery_enabled);
617 assert_eq!(reth.program, None);
618 assert_eq!(reth.ipc_path, None);
619 assert!(!reth.ipc_enabled);
620 assert_eq!(reth.data_dir, None);
621 assert_eq!(reth.chain_or_path, None);
622 assert_eq!(reth.genesis, None);
623 assert!(reth.args.is_empty());
624 assert!(!reth.keep_stdout);
625 }
626}