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.clone().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, Default)]
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 Reth {
179 pub fn new() -> Self {
185 Self {
186 dev: false,
187 host: None,
188 http_port: DEFAULT_HTTP_PORT,
189 ws_port: DEFAULT_WS_PORT,
190 auth_port: DEFAULT_AUTH_PORT,
191 p2p_port: DEFAULT_P2P_PORT,
192 block_time: None,
193 instance: rand::thread_rng().gen_range(1..200),
194 discovery_enabled: true,
195 program: None,
196 ipc_path: None,
197 ipc_enabled: false,
198 data_dir: None,
199 chain_or_path: None,
200 genesis: None,
201 args: Vec::new(),
202 keep_stdout: false,
203 }
204 }
205
206 pub fn at(path: impl Into<PathBuf>) -> Self {
219 Self::new().path(path)
220 }
221
222 pub fn path<T: Into<PathBuf>>(mut self, path: T) -> Self {
227 self.program = Some(path.into());
228 self
229 }
230
231 pub const fn dev(mut self) -> Self {
233 self.dev = true;
234 self
235 }
236
237 pub fn host<T: Into<String>>(mut self, host: T) -> Self {
241 self.host = Some(host.into());
242 self
243 }
244
245 pub const fn http_port(mut self, http_port: u16) -> Self {
248 self.http_port = http_port;
249 self.instance = 0;
250 self
251 }
252
253 pub const fn ws_port(mut self, ws_port: u16) -> Self {
256 self.ws_port = ws_port;
257 self.instance = 0;
258 self
259 }
260
261 pub const fn auth_port(mut self, auth_port: u16) -> Self {
264 self.auth_port = auth_port;
265 self.instance = 0;
266 self
267 }
268
269 pub const fn p2p_port(mut self, p2p_port: u16) -> Self {
272 self.p2p_port = p2p_port;
273 self.instance = 0;
274 self
275 }
276
277 pub fn block_time(mut self, block_time: &str) -> Self {
281 self.block_time = Some(block_time.to_string());
282 self
283 }
284
285 pub const fn disable_discovery(mut self) -> Self {
287 self.discovery_enabled = false;
288 self
289 }
290
291 pub fn chain_or_path(mut self, chain_or_path: &str) -> Self {
294 self.chain_or_path = Some(chain_or_path.to_string());
295 self
296 }
297
298 pub const fn enable_ipc(mut self) -> Self {
300 self.ipc_enabled = true;
301 self
302 }
303
304 pub const fn instance(mut self, instance: u16) -> Self {
307 self.instance = instance;
308 self
309 }
310
311 pub fn ipc_path<T: Into<PathBuf>>(mut self, path: T) -> Self {
313 self.ipc_path = Some(path.into());
314 self
315 }
316
317 pub fn data_dir<T: Into<PathBuf>>(mut self, path: T) -> Self {
319 self.data_dir = Some(path.into());
320 self
321 }
322
323 pub fn genesis(mut self, genesis: Genesis) -> Self {
330 self.genesis = Some(genesis);
331 self
332 }
333
334 pub const fn keep_stdout(mut self) -> Self {
338 self.keep_stdout = true;
339 self
340 }
341
342 pub fn arg<T: Into<OsString>>(mut self, arg: T) -> Self {
346 self.args.push(arg.into());
347 self
348 }
349
350 pub fn args<I, S>(mut self, args: I) -> Self
354 where
355 I: IntoIterator<Item = S>,
356 S: Into<OsString>,
357 {
358 for arg in args {
359 self = self.arg(arg);
360 }
361 self
362 }
363
364 #[track_caller]
370 pub fn spawn(self) -> RethInstance {
371 self.try_spawn().unwrap()
372 }
373
374 pub fn try_spawn(self) -> Result<RethInstance, NodeError> {
376 let bin_path = self
377 .program
378 .as_ref()
379 .map_or_else(|| RETH.as_ref(), |bin| bin.as_os_str())
380 .to_os_string();
381 let mut cmd = Command::new(&bin_path);
382 cmd.stdout(Stdio::piped());
384
385 cmd.arg("node");
387
388 if self.http_port != DEFAULT_HTTP_PORT {
390 cmd.arg("--http.port").arg(self.http_port.to_string());
391 }
392
393 if self.ws_port != DEFAULT_WS_PORT {
394 cmd.arg("--ws.port").arg(self.ws_port.to_string());
395 }
396
397 if self.auth_port != DEFAULT_AUTH_PORT {
398 cmd.arg("--authrpc.port").arg(self.auth_port.to_string());
399 }
400
401 if self.p2p_port != DEFAULT_P2P_PORT {
402 cmd.arg("--discovery.port").arg(self.p2p_port.to_string());
403 }
404
405 if self.dev {
407 cmd.arg("--dev");
414
415 if let Some(block_time) = self.block_time {
417 cmd.arg("--dev.block-time").arg(block_time);
418 }
419 }
420
421 if !self.ipc_enabled {
423 cmd.arg("--ipcdisable");
424 }
425
426 cmd.arg("--http");
428 cmd.arg("--http.api").arg(API);
429
430 if let Some(ref host) = self.host {
431 cmd.arg("--http.addr").arg(host);
432 }
433
434 cmd.arg("--ws");
436 cmd.arg("--ws.api").arg(API);
437
438 if let Some(ref host) = self.host {
439 cmd.arg("--ws.addr").arg(host);
440 }
441
442 if let Some(ipc) = &self.ipc_path {
444 cmd.arg("--ipcpath").arg(ipc);
445 }
446
447 if self.instance > 0 {
452 cmd.arg("--instance").arg(self.instance.to_string());
453 }
454
455 if let Some(data_dir) = &self.data_dir {
456 cmd.arg("--datadir").arg(data_dir);
457
458 if !data_dir.exists() {
460 create_dir(data_dir).map_err(NodeError::CreateDirError)?;
461 }
462 }
463
464 if self.discovery_enabled {
465 cmd.arg("--verbosity").arg("-vvv");
467 } else {
468 cmd.arg("--disable-discovery");
469 cmd.arg("--no-persist-peers");
470 }
471
472 if let Some(chain_or_path) = self.chain_or_path {
473 cmd.arg("--chain").arg(chain_or_path);
474 }
475
476 cmd.arg("--color").arg("never");
478
479 cmd.args(self.args);
481
482 let mut child = cmd.spawn().map_err(NodeError::SpawnError)?;
483
484 let stdout = child.stdout.take().ok_or(NodeError::NoStdout)?;
485
486 let start = Instant::now();
487 let mut reader = BufReader::new(stdout);
488
489 let mut http_port = 0;
490 let mut ws_port = 0;
491 let mut auth_port = 0;
492 let mut p2p_port = 0;
493
494 let mut ports_started = false;
495 let mut p2p_started = !self.discovery_enabled;
496
497 loop {
498 if start + NODE_STARTUP_TIMEOUT <= Instant::now() {
499 let _ = child.kill();
500 return Err(NodeError::Timeout);
501 }
502
503 let mut line = String::with_capacity(120);
504 reader.read_line(&mut line).map_err(NodeError::ReadLineError)?;
505
506 if line.contains("RPC HTTP server started") {
507 if let Some(addr) = extract_endpoint("url=", &line) {
508 http_port = addr.port();
509 }
510 }
511
512 if line.contains("RPC WS server started") {
513 if let Some(addr) = extract_endpoint("url=", &line) {
514 ws_port = addr.port();
515 }
516 }
517
518 if line.contains("RPC auth server started") {
519 if let Some(addr) = extract_endpoint("url=", &line) {
520 auth_port = addr.port();
521 }
522 }
523
524 if line.contains("ERROR") {
526 let _ = child.kill();
527 return Err(NodeError::Fatal(line));
528 }
529
530 if http_port != 0 && ws_port != 0 && auth_port != 0 {
531 ports_started = true;
532 }
533
534 if self.discovery_enabled {
535 if line.contains("Updated local ENR") {
536 if let Some(port) = extract_endpoint("IpV4 UDP Socket", &line) {
537 p2p_port = port.port();
538 p2p_started = true;
539 }
540 }
541 } else {
542 p2p_started = true;
543 }
544
545 if ports_started && p2p_started {
547 break;
548 }
549 }
550
551 if self.keep_stdout {
552 child.stdout = Some(reader.into_inner());
554 }
555
556 Ok(RethInstance {
557 pid: child,
558 host: self.host.unwrap_or_else(|| "localhost".to_string()),
559 instance: self.instance,
560 http_port,
561 ws_port,
562 p2p_port: (p2p_port != 0).then_some(p2p_port),
563 ipc: self.ipc_path,
564 data_dir: self.data_dir,
565 auth_port: Some(auth_port),
566 genesis: self.genesis,
567 })
568 }
569}
570
571#[cfg(test)]
572mod tests {
573 use super::*;
574
575 #[test]
576 fn can_set_host() {
577 let reth = Reth::new().host("0.0.0.0").dev().try_spawn();
578 if let Ok(reth) = reth {
579 assert_eq!(reth.host(), "0.0.0.0");
580 assert!(reth.endpoint().starts_with("http://0.0.0.0:"));
581 assert!(reth.ws_endpoint().starts_with("ws://0.0.0.0:"));
582 }
583 }
584
585 #[test]
586 fn default_host_is_localhost() {
587 let reth = Reth::new().dev().try_spawn();
588 if let Ok(reth) = reth {
589 assert_eq!(reth.host(), "localhost");
590 assert!(reth.endpoint().starts_with("http://localhost:"));
591 assert!(reth.ws_endpoint().starts_with("ws://localhost:"));
592 }
593 }
594}